Introduction to JavaScript
JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based, and multi-paradigm.
What is JavaScript?
- JavaScript is the programming language of the Web
- It allows you to implement complex features on web pages
- It enables interactive web pages and is an essential part of web applications
- It is supported by all modern web browsers without plugins
- It is not the same as Java (despite the similar name)
JavaScript was created by Brendan Eich in 1995 while he was an engineer at Netscape. It was originally developed under the name Mocha, then LiveScript, and finally renamed to JavaScript.
What Can JavaScript Do?
JavaScript can change HTML content, attributes, and styles. It can hide and show HTML elements, and it can be used to validate form data before submission. Here are some key capabilities:
- DOM Manipulation - JavaScript can access and modify the Document Object Model (DOM), allowing dynamic changes to web page content
- Event Handling - JavaScript can respond to user actions like clicks, form submissions, and keyboard input
- AJAX - JavaScript can send and receive data from a server asynchronously without reloading the page
- Animations and Effects - JavaScript can create animations and visual effects
- Form Validation - JavaScript can validate user input before sending data to a server
- Web APIs - JavaScript can interact with various Web APIs like Geolocation, Web Storage, and Canvas
Adding JavaScript to HTML
There are three ways to add JavaScript to your HTML:
1. Internal JavaScript
You can add JavaScript directly within your HTML document using the <script>
element.
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript Example</title>
</head>
<body>
<h1>My Web Page</h1>
<!-- Internal JavaScript -->
<script>
// JavaScript code goes here
document.write("Hello, World!");
console.log("This is logged to the console");
</script>
</body>
</html>
2. External JavaScript
You can write your JavaScript in a separate file with a .js extension and then reference it in your HTML using the src
attribute of the <script>
element.
HTML File (index.html)
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
<!-- External JavaScript -->
<script src="script.js"></script>
</head>
<body>
<h1>My Web Page</h1>
</body>
</html>
JavaScript File (script.js)
// JavaScript code goes here
document.write("Hello, World!");
console.log("This is logged to the console");
3. Inline JavaScript
You can add JavaScript directly to HTML elements using event attributes.
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript Example</title>
</head>
<body>
<h1>My Web Page</h1>
<!-- Inline JavaScript -->
<button onclick="alert('Hello, World!')">Click Me</button>
</body>
</html>
Best Practices
For maintainability and separation of concerns, it's generally recommended to:
- Use external JavaScript files whenever possible
- Place
<script>
elements at the bottom of the<body>
element or use thedefer
attribute to improve page loading performance - Avoid inline JavaScript when possible
JavaScript Syntax
JavaScript syntax is the set of rules that define how JavaScript programs are constructed.
JavaScript Statements
JavaScript statements are commands to the browser. They are composed of values, operators, expressions, keywords, and comments.
// This is a statement
let x = 5;
// This is another statement
console.log("Hello, World!");
// Multiple statements can be grouped in a block using curly braces
{
let x = 5;
console.log(x);
}
JavaScript Comments
Comments are used to explain JavaScript code and make it more readable. They are ignored by the browser.
// This is a single-line comment
/* This is a
multi-line comment */
JavaScript Identifiers
Identifiers are names given to variables, functions, etc. They must begin with a letter, underscore (_), or dollar sign ($). Subsequent characters can also be digits (0-9).
// Valid identifiers
let firstName = "John";
let _value = 10;
let $price = 99.99;
// Invalid identifiers
// let 1name = "John"; // Cannot start with a digit
// let my-name = "John"; // Cannot contain a hyphen
JavaScript is Case Sensitive
JavaScript is case sensitive. This means that variables, function names, and other identifiers must be typed with consistent capitalization.
let name = "John";
let Name = "Jane";
// name and Name are different variables
JavaScript and Semicolons
Semicolons separate JavaScript statements. Although semicolons are optional in JavaScript (due to automatic semicolon insertion), it's considered good practice to use them.
let x = 5;
let y = 6;
let z = x + y;
JavaScript Variables
Variables are containers for storing data values. In JavaScript, there are three ways to declare a variable:
// Using var (function-scoped, older way)
var x = 5;
// Using let (block-scoped, introduced in ES6)
let y = 10;
// Using const (block-scoped, constant value, introduced in ES6)
const z = 15;
Variable Declaration
You can declare a variable without assigning a value to it. In this case, the variable will have the value undefined
.
let x; // Declared but not assigned, value is undefined
console.log(x); // Output: undefined
x = 5; // Now x has a value
console.log(x); // Output: 5
let vs var
The let
keyword was introduced in ES6 (2015) to address some issues with var
. The main differences are:
Feature | var | let |
---|---|---|
Scope | Function scope | Block scope |
Hoisting | Hoisted (can be used before declaration) | Hoisted but not initialized (cannot be used before declaration) |
Redeclaration | Allowed | Not allowed in the same scope |
// var example - function scope
function varExample() {
var x = 1;
if (true) {
var x = 2; // Same variable!
console.log(x); // 2
}
console.log(x); // 2
}
// let example - block scope
function letExample() {
let x = 1;
if (true) {
let x = 2; // Different variable!
console.log(x); // 2
}
console.log(x); // 1
}
const
The const
keyword is used to declare constants - variables that cannot be reassigned. However, for objects and arrays, the properties or elements can still be changed.
// const with primitive value
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable
// const with object
const person = {
name: "John",
age: 30
};
// This is allowed
person.age = 31;
console.log(person.age); // 31
// But this is not allowed
// person = { name: "Jane", age: 25 }; // Error: Assignment to constant variable
Best Practices for Variables
- Use
const
by default - Use
let
when you need to reassign a variable - Avoid using
var
in modern JavaScript - Use meaningful variable names that describe what the variable contains
- Use camelCase for variable names (e.g.,
firstName
,totalAmount
)
JavaScript Data Types
JavaScript has several built-in data types that can be categorized as primitive and non-primitive (reference) types.
Primitive Data Types
Primitive data types are immutable (cannot be changed) and are passed by value.
Data Type | Description | Example |
---|---|---|
String | Represents textual data | "Hello, World!" , 'JavaScript' |
Number | Represents numeric values | 42 , 3.14 , NaN , Infinity |
Boolean | Represents logical values | true , false |
Undefined | Represents a variable that has been declared but not assigned a value | undefined |
Null | Represents the intentional absence of any object value | null |
Symbol | Represents a unique identifier | Symbol('description') |
BigInt | Represents integers larger than the Number type can handle | 9007199254740991n |
Non-Primitive (Reference) Data Types
Non-primitive data types are mutable (can be changed) and are passed by reference.
Data Type | Description | Example |
---|---|---|
Object | Represents a collection of related data | { name: "John", age: 30 } |
Array | Represents a list-like collection of values | [1, 2, 3, 4] |
Function | Represents a reusable block of code | function() { return "Hello"; } |
Date | Represents a date and time | new Date() |
RegExp | Represents a regular expression | /pattern/ |
Type Checking
JavaScript provides the typeof
operator to check the data type of a value.
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known bug in JavaScript)
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects in JavaScript)
console.log(typeof function(){}); // "function"
Type Conversion
JavaScript is a loosely typed language, which means variables can change types. There are two types of type conversion:
Implicit Conversion (Type Coercion)
JavaScript automatically converts one data type to another when needed.
let result = "5" + 2; // "52" (number is converted to string)
console.log(result);
result = "5" - 2; // 3 (string is converted to number)
console.log(result);
result = "5" * "2"; // 10 (both strings are converted to numbers)
console.log(result);
result = 5 + true; // 6 (true is converted to 1)
console.log(result);
result = 5 + false; // 5 (false is converted to 0)
console.log(result);
Explicit Conversion
You can explicitly convert values using built-in functions like Number()
, String()
, and Boolean()
.
// String to Number
let num = Number("5"); // 5
console.log(num);
// Number to String
let str = String(5); // "5"
console.log(str);
// Value to Boolean
let bool = Boolean(0); // false
console.log(bool);
bool = Boolean(1); // true
console.log(bool);
bool = Boolean(""); // false
console.log(bool);
bool = Boolean("Hello"); // true
console.log(bool);
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on numbers.
Operator | Description | Example |
---|---|---|
+ | Addition | 5 + 2 = 7 |
- | Subtraction | 5 - 2 = 3 |
* | Multiplication | 5 * 2 = 10 |
/ | Division | 5 / 2 = 2.5 |
% | Modulus (Remainder) | 5 % 2 = 1 |
++ | Increment | let x = 5; x++; // x is now 6 |
-- | Decrement | let x = 5; x--; // x is now 4 |
** | Exponentiation (ES2016) | 5 ** 2 = 25 |
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Example | Same As |
---|---|---|
= | x = y |
x = y |
+= | x += y |
x = x + y |
-= | x -= y |
x = x - y |
*= | x *= y |
x = x * y |
/= | x /= y |
x = x / y |
%= | x %= y |
x = x % y |
**= | x **= y |
x = x ** y |
Comparison Operators
Comparison operators are used to compare values and return a boolean result.
Operator | Description | Example |
---|---|---|
== | Equal to (value) | 5 == "5" // true |
=== | Equal to (value and type) | 5 === "5" // false |
!= | Not equal to (value) | 5 != "6" // true |
!== | Not equal to (value and type) | 5 !== "5" // true |
> | Greater than | 5 > 3 // true |
< | Less than | 5 < 3 // false |
>= | Greater than or equal to | 5 >= 5 // true |
<= | Less than or equal to | 5 <= 3 // false |
Logical Operators
Logical operators are used to determine the logic between variables or values.
Operator | Description | Example |
---|---|---|
&& | Logical AND | x > 5 && x < 10 |
|| | Logical OR | x < 5 || x > 10 |
! | Logical NOT | !(x > 5) |
String Operators
The + operator can also be used to concatenate (join) strings.
let text1 = "Hello";
let text2 = "World";
let result = text1 + " " + text2; // "Hello World"
console.log(result);
// String concatenation with +=
let greeting = "Hello";
greeting += " World"; // "Hello World"
console.log(greeting);
Ternary Operator
The ternary operator is a shorthand for an if-else statement.
// Syntax: condition ? expressionIfTrue : expressionIfFalse
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // "Adult"
Control Structures
Control structures are used to control the flow of execution in a program.
Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
if Statement
The if
statement executes a block of code if a specified condition is true.
let hour = 14;
if (hour < 18) {
console.log("Good day!");
}
if...else Statement
The if...else
statement executes one block of code if a condition is true and another block if the condition is false.
let hour = 20;
if (hour < 18) {
console.log("Good day!");
} else {
console.log("Good evening!");
}
if...else if...else Statement
The if...else if...else
statement executes different blocks of code for more than two conditions.
let hour = 14;
if (hour < 12) {
console.log("Good morning!");
} else if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
switch Statement
The switch
statement selects one of many blocks of code to be executed.
let day = 2;
let dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName); // "Tuesday"
Loops
Loops are used to execute a block of code multiple times.
for Loop
The for
loop repeats a block of code a specified number of times.
// Syntax: for (initialization; condition; increment) { code block }
for (let i = 0; i < 5; i++) {
console.log("Iteration " + i);
}
while Loop
The while
loop repeats a block of code while a specified condition is true.
// Syntax: while (condition) { code block }
let i = 0;
while (i < 5) {
console.log("Iteration " + i);
i++;
}
do...while Loop
The do...while
loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
// Syntax: do { code block } while (condition);
let i = 0;
do {
console.log("Iteration " + i);
i++;
} while (i < 5);
for...in Loop
The for...in
loop iterates over the properties of an object.
// Syntax: for (variable in object) { code block }
const person = {
firstName: "John",
lastName: "Doe",
age: 30
};
for (let prop in person) {
console.log(prop + ": " + person[prop]);
}
for...of Loop
The for...of
loop iterates over the values of an iterable object (like an array).
// Syntax: for (variable of iterable) { code block }
const colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
Break and Continue
The break
statement "jumps out" of a loop, while the continue
statement "jumps over" one iteration in the loop.
// break example
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i is 5
}
console.log(i);
}
// continue example
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue; // Skip iteration when i is 5
}
console.log(i);
}
JavaScript Functions
A function is a block of code designed to perform a particular task. It is executed when "something" invokes it (calls it).
Function Declaration
A function declaration defines a named function.
// Syntax: function name(parameters) { code block }
function greet(name) {
return "Hello, " + name + "!";
}
// Calling the function
let message = greet("John");
console.log(message); // "Hello, John!"
Function Expression
A function expression defines a function as part of a larger expression, typically a variable assignment.
// Syntax: let variableName = function(parameters) { code block };
let greet = function(name) {
return "Hello, " + name + "!";
};
// Calling the function
let message = greet("John");
console.log(message); // "Hello, John!"
Arrow Functions
Arrow functions provide a shorter syntax for writing function expressions. They were introduced in ES6.
// Syntax: (parameters) => { code block }
let greet = (name) => {
return "Hello, " + name + "!";
};
// Shorter syntax for simple functions
let greetShort = name => "Hello, " + name + "!";
// Calling the function
let message = greet("John");
console.log(message); // "Hello, John!"
message = greetShort("Jane");
console.log(message); // "Hello, Jane!"
Function Parameters
Function parameters are the names listed in the function definition. Function arguments are the real values passed to the function.
// Function with multiple parameters
function add(a, b) {
return a + b;
}
let sum = add(5, 3);
console.log(sum); // 8
// Default parameters (ES6)
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet()); // "Hello, Guest!"
console.log(greet("John")); // "Hello, John!"
// Rest parameters (ES6)
function sum(...numbers) {
let total = 0;
for (let number of numbers) {
total += number;
}
return total;
}
console.log(sum(1, 2, 3, 4, 5)); // 15
Function Return
The return
statement stops the execution of a function and returns a value.
function multiply(a, b) {
return a * b; // Return the product
}
let product = multiply(5, 3);
console.log(product); // 15
// Function without a return statement
function greet(name) {
console.log("Hello, " + name + "!");
// No return statement, so the function returns undefined
}
let result = greet("John"); // Logs "Hello, John!"
console.log(result); // undefined
Practice Exercises
Now that you've learned the basics of JavaScript, it's time to practice! Here are some exercises to help you reinforce what you've learned.
Exercise 1: Variables and Data Types
Create variables of different data types (string, number, boolean, array, object) and log their values and types to the console.
Exercise 2: Control Flow
Write a program that checks if a number is positive, negative, or zero, and logs an appropriate message to the console.
Exercise 3: Loops
Write a program that uses a loop to print all even numbers from 1 to 20.
Exercise 4: Functions
Write a function that takes two numbers as parameters and returns the larger of the two.