Statements
A statement is a complete unit of JavaScript code that can be executed and evaluated to produce a value. JavaScript’s programs are made up of statements, which are executed in the order they are written. A statement can be one of the following:
- Expression statement: An expression followed by a semicolon (
;
). The expression is evaluated and its result is returned as the value of the statement. - Declaration statement: A statement that declares a variable, function, or class.
- Control statement: A statement that controls the flow of execution in a program, such as
if
,for
, andswitch
. - Empty statement: A statement that consists of a single semicolon (
;
). It does nothing and is used when a statement is required syntactically but no action is needed. - Block statement: A statement that groups other statements together. It consists of a pair of curly braces (
{ ... }
) and can be used anywhere a statement is expected.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Expression statement
let x = 1 + 2;
// Declaration statement
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Control statement
if (x > 0) {
console.log("x is positive.");
} else {
console.log("x is negative.");
}
// Empty statement
let y = [];
for (let i = 0; i < 10; y[i++] = 0) /* empty */ ;
// Block statement
{
let x = 1;
let y = 2;
console.log(x + y);
}
Conditional Statements
Conditional statements allow us to control the flow of execution in a program. They are used to execute a block of code if a certain condition is met. JavaScript has two conditional statements: if
and switch
.
The if
Statement
The if
statement executes a block of code if a specified condition is true. It can optionally be followed by an else
clause, which executes a block of code if the condition is false.
1
2
3
4
5
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
The condition
can be any expression that evaluates to a boolean value. If the condition is true, the code in the first block is executed. Otherwise, the code in the second block is executed.
1
2
3
4
5
6
let x = 42;
if (x > 0) {
console.log("x is positive.");
} else {
console.log("x is negative.");
}
The else
clause is optional. If it is omitted, the code in the first block is executed if the condition is true, and nothing happens if the condition is false.
1
2
3
4
let x = 42;
if (x > 0) {
console.log("x is positive.");
}
The if
statement can be followed by an else if
clause, which executes a block of code if the condition is false and the specified condition is true.
1
2
3
4
5
6
7
8
let x = 42;
if (x > 0) {
console.log("x is positive.");
} else if (x < 0) {
console.log("x is negative.");
} else {
console.log("x is zero.");
}
The else if
clause can be repeated as many times as necessary.
1
2
3
4
5
6
7
8
9
10
let x = 42;
if (x > 0) {
console.log("x is positive.");
} else if (x < 0) {
console.log("x is negative.");
} else if (x === 0) {
console.log("x is zero.");
} else {
console.log("x is not a number.");
}
The switch
Statement
The switch
statement executes a block of code depending on different cases. It is similar to the if
statement, but it is more concise and easier to read.
1
2
3
4
5
6
7
8
9
10
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if expression is different from both value1 and value2
}
The expression
is evaluated and compared to each case
value. If it matches, the code in the corresponding block is executed. If it doesn’t match, the code in the default
block is executed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday.");
break;
case "Tuesday":
console.log("Today is Tuesday.");
break;
case "Wednesday":
console.log("Today is Wednesday.");
break;
case "Thursday":
console.log("Today is Thursday.");
break;
case "Friday":
console.log("Today is Friday.");
break;
case "Saturday":
console.log("Today is Saturday.");
break;
case "Sunday":
console.log("Today is Sunday.");
break;
default:
console.log("Invalid day.");
}
The break
statement is used to exit the switch
statement. If it is omitted, the code in the next block is executed, even if the condition is not met.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday.");
case "Tuesday":
console.log("Today is Tuesday.");
case "Wednesday":
console.log("Today is Wednesday.");
case "Thursday":
console.log("Today is Thursday.");
case "Friday":
console.log("Today is Friday.");
case "Saturday":
console.log("Today is Saturday.");
case "Sunday":
console.log("Today is Sunday.");
default:
console.log("Invalid day.");
}
Loop Statements
Loop statements allow us to execute a block of code repeatedly. They are used to iterate over a collection of items and perform a certain action on each item. JavaScript has three loop statements: for
, while
, and do...while
.
The for
Statement
The for
statement executes a block of code repeatedly until a specified condition is met. It is used to iterate over a collection of items and perform a certain action on each item.
1
2
3
for (initialization; condition; final-expression) {
// Code to execute repeatedly
}
The initialization
is executed before the loop starts. It is used to initialize the loop variable.
The condition
is evaluated before each iteration. If it is true, the code in the block is executed. If it is false, the loop is terminated.
The final-expression
is executed at the end of each iteration. It is used to update the loop variable.
1
2
3
for (let i = 0; i < 10; i++) {
console.log(i);
}
The for
statement can be used to iterate over an array.
1
2
3
4
let fruits = ["Apple", "Banana", "Cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
The for...in
Statement
The for...in
statement iterates over the properties of an object. It is used to iterate over the keys of an object and perform a certain action on each key.
1
2
3
for (variable in object) {
// Code to execute repeatedly
}
The variable
is assigned the key of each property in the object.
1
2
3
4
5
6
7
8
9
let person = {
name: "John",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key); // name age city
console.log(person[key]); // John 30 New York
}
The for...in
statement can be used to iterate over the keys of an array.
1
2
3
4
let fruits = ["Apple", "Banana", "Cherry"];
for (let key in fruits) {
console.log(key); // 0 1 2
}
The for...of
Statement
The for...of
statement iterates over the values of an iterable object. It is used to iterate over the values of an array and perform a certain action on each value.
1
2
3
for (variable of iterable) {
// Code to execute repeatedly
}
The variable
is assigned the value of each item in the iterable object.
1
2
3
4
let fruits = ["Apple", "Banana", "Cherry"];
for (let fruit of fruits) {
console.log(fruit); // Apple Banana Cherry
}
The for...of
statement can be used to iterate over the values of a string.
1
2
3
4
let str = "Hello";
for (let char of str) {
console.log(char); // H e l l o
}
The while
Statement
The while
statement executes a block of code repeatedly until a specified condition is met. It is used to iterate over a collection of items and perform a certain action on each item.
1
2
3
while (condition) {
// Code to execute repeatedly
}
The condition
is evaluated before each iteration. If it is true, the code in the block is executed. If it is false, the loop is terminated.
1
2
3
4
5
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
The while
statement can be used to iterate over an array.
1
2
3
4
5
6
let fruits = ["Apple", "Banana", "Cherry"];
let i = 0;
while (i < fruits.length) {
console.log(fruits[i]);
i++;
}
The do...while
Statement
The do...while
statement executes a block of code repeatedly until a specified condition is met. It is used to iterate over a collection of items and perform a certain action on each item.
It executes the code block at least once, even if the condition is false.
1
2
3
do {
// Code to execute repeatedly
} while (condition);
The condition
is evaluated after each iteration. If it is true, the code in the block is executed. If it is false, the loop is terminated.
1
2
3
4
5
let i = 0;
do {
console.log(i);
i++;
} while (i < 10);
The do...while
statement can be used to iterate over an array.
1
2
3
4
5
6
let fruits = ["Apple", "Banana", "Cherry"];
let i = 0;
do {
console.log(fruits[i]); // Apple Banana Cherry
i++;
} while (i < fruits.length);
Jump Statements
Jump statements allow us to control the flow of a program. They are used to jump to another part of the program. JavaScript has three jump statements: break
, continue
, and return
.
The break
Statement
The break
statement is used to terminate a loop or a switch
statement. It is used to exit a loop or a switch
statement.
1
2
3
4
5
6
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i); // 0 1 2 3 4
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday.");
break;
case "Tuesday":
console.log("Today is Tuesday.");
break;
case "Wednesday":
console.log("Today is Wednesday.");
break;
case "Thursday":
console.log("Today is Thursday.");
break;
case "Friday":
console.log("Today is Friday.");
break;
case "Saturday":
console.log("Today is Saturday.");
break;
case "Sunday":
console.log("Today is Sunday.");
break;
default:
console.log("Invalid day.");
}
The continue
Statement
The continue
statement is used to skip the current iteration of a loop. It is used to skip the current iteration of a loop.
1
2
3
4
5
6
for (let i = 0; i < 10; i++) {
if (i === 5) {
continue;
}
console.log(i); // 0 1 2 3 4 6 7 8 9
}
The return
Statement
The return
statement is used to end the execution of a function. It is used to return a value from a function.
1
2
3
4
function sum(a, b) {
return a + b;
}
console.log(sum(2, 3)); // 5
The throw
Statement
The throw
statement is used to throw an exception. It is used to throw an exception.
1
2
3
4
5
6
7
8
9
function sum(a, b) {
if (typeof a !== "number" || typeof b !== "number") {
throw new Error("Both arguments must be numbers.");
}
return a + b;
}
console.log(sum(2, 3)); // 5
console.log(sum("2", "3")); // Error: Both arguments must be numbers.
The try...catch
Statement
The try...catch
statement is used to handle errors. It is used to handle errors.
1
2
3
4
5
try {
// Code to try
} catch (error) {
// Code to handle errors
}
The try
block contains the code that may throw an exception. The catch
block contains the code that handles the exception.
1
2
3
4
5
6
try {
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[3]);
} catch (error) {
console.log(error); // TypeError: Cannot read property '3' of undefined
}
It is possible to have multiple catch
blocks to handle different types of errors. The catch
block that matches the type of the error is executed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
try {
// Code that might throw an exception
const result = doSomething();
console.log(result);
} catch (error) {
if (error instanceof TypeError) {
// Handle TypeError
console.log("Oops! There was a type error.");
} else if (error instanceof RangeError) {
// Handle RangeError
console.log("Oops! There was a range error.");
} else {
// Handle other types of errors
console.log("Oops! An error occurred:", error.message);
}
}
A finally
block can be used to execute code after a try...catch
statement regardless of whether an error occurs or not.
1
2
3
4
5
6
7
8
try {
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[3]);
} catch (error) {
console.log(error); // TypeError: Cannot read property '3' of undefined
} finally {
console.log("This code is executed regardless of whether an error occurs or not.");
}
Miscellaneous Statements
The debugger
Statement
The debugger
statement is used to invoke any available debugging functionality.
Note that it is not enough to have a debugger available: the debugger statement won’t start the debugger for you. If you’re using a web browser and have the developer tools console open, however, this statement will cause a breakpoint.
1
2
3
4
5
function sum(a, b) {
debugger;
return a + b;
}
console.log(sum(2, 3)); // 5
The with
Statement
The with
statement is used to extend the scope chain. It is used to extend the scope chain.
1
2
3
with (Math) {
console.log(sqrt(4)); // 2
}
The with
statement is not allowed in strict mode.
1
2
3
4
"use strict";
with (Math) {
console.log(sqrt(4)); // SyntaxError: Strict mode code may not include a with statement
}
The use strict
Directive
The use strict
directive is used to enforce stricter parsing and error handling of JavaScript code. It is used to enforce stricter parsing and error handling of JavaScript code.
1
"use strict";
The use strict
directive is only recognized at the beginning of a script or a function.
1
2
3
4
5
6
"use strict";
function sum(a, b) {
"use strict";
return a + b;
}
console.log(sum(2, 3)); // 5
Strict code is executed in strict mode. Strict mode is a restricted subset of the language that fixes important language deficiencies and provides stronger error checking and increased security. Because strict mode is not the default, old JavaScript code that still uses the deficient legacy features of the language will continue to run correctly. The differences between strict mode and non-strict mode are the following (the first three are particularly important):
- Variables must be declared before they are used.
with
is not allowed.eval
cannot create variables in the scope from which it was called.this
is undefined in functions that are not called as methods.- assignment to a non-writable property or a getter-only property is an error.
- assignment to a non-existing property of a non-extensible object is an error.
- deleting a non-existing property is an error.
- function parameters must be unique.
- octal syntax is not allowed.
- duplicate property names in object literals are an error.
Declarations
The var
Statement, The let
Statement, and The const
Statement
All variables in JavaScript must be declared. The var
statement is used to declare a variable. The let
statement is used to declare a variable. The const
statement is used to declare a variable whose value cannot be changed.
The let keyword is block-scoped
Variables declared with the let
keyword have block scope, meaning they are limited to the block (enclosed within curly braces) where they are defined. They are not accessible outside of that block.
The var keyword is function-scoped
Variables declared with the var
keyword have function scope, meaning they are accessible throughout the entire function where they are defined, regardless of block boundaries. They are not limited to the block they are defined in.
The let keyword is not hoisted
Variables declared with let
are not hoisted to the top of their scope. They can only be accessed after they have been declared in the code.
The var keyword is hoisted
Variables declared with var
are hoisted to the top of their scope. This means they can be accessed and are assigned the value undefined
before the line where they are actually defined in the code.
The let keyword cannot be redeclared in the same scope
In the same scope, you cannot declare multiple variables with the same name using the let
keyword. Attempting to do so will result in a syntax error.
The var keyword can be redeclared in the same scope
Unlike let
, variables declared with var
can be redeclared multiple times within the same scope without causing an error. Each declaration creates a new variable instance within that scope.
The let keyword is not initialized until the line of code where it is declared has been executed
Variables declared with let
are not automatically assigned a value upon declaration. They are considered uninitialized until an assignment is made to them.
The var keyword is initialized with the value undefined until the line of code where it is declared has been executed
Variables declared with var
are automatically initialized with the value undefined
upon declaration if no explicit value is assigned to them. They are then updated with the assigned value when reached in the code execution.
The let keyword is a better choice than the var keyword for declaring variables in JavaScript
In modern JavaScript, using let
is generally preferred over var
. let
provides block scoping, avoids hoisting issues, and helps prevent accidental re-declarations. It offers more predictable behavior and better aligns with best practices.
The const keyword is block-scoped
Variables declared with the const
keyword have block scope, meaning they are limited to the block (enclosed within curly braces) where they are defined. They are not accessible outside of that block.
The const keyword is not hoisted
Variables declared with const
are not hoisted to the top of their scope. They can only be accessed after they have been declared in the code.
The const keyword cannot be redeclared in the same scope
In the same scope, you cannot declare multiple variables with the same name using the const
keyword. Attempting to do so will result in a syntax error.
The const keyword must be initialized with a value upon declaration
Variables declared with const
must be initialized with a value upon declaration. Attempting to declare a variable with const
without assigning a value to it will result in a syntax error.
function
Declarations and function
Expressions
A function declaration defines a function with the specified parameters.
We say that function declarations are “hoisted” because it is as if they had all been moved up to the top of whatever scope they are defined within. The upshot is that code that invokes a function can exist in your program before the code that declares the function.
A function expression defines a function as a part of a larger expression syntax (typically a variable assignment). Functions defined via function expressions can be named or anonymous. Function expressions are often used as IIFEs (Immediately Invoked Function Expressions) which run as soon as they are defined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// named function expression
var add = function add(a, b) {
return a + b;
};
// anonymous function expression
var add = function(a, b) {
return a + b;
};
// IIFE
(function(){
console.log("Hello, IIFE!");
})();
In the above example, we define an anonymous function using a function expression syntax (function() { … }). The function is immediately invoked by adding () at the end (function() { … })(). This means that the function is executed immediately without the need to call it separately.
Inside the IIFE, you can write any code you want to execute immediately. In this case, we simply log the message “Hello, IIFE!” to the console. You can include any other statements, variable declarations, or even create a private scope for your code within the IIFE.
The use of IIFEs is beneficial for encapsulating code and creating a separate scope to avoid polluting the global namespace. It’s commonly used to achieve module-like behavior or to execute code once without leaving any lasting variables or functions behind.
class
declaration
In ES6 and later, the class declaration creates a new class and gives it a name that we can use to refer to it.
Unlike functions, class declarations are not hoisted, and you cannot use a class declared this way in code that appears before the declaration.
1
2
3
4
5
class Circle {
constructor(radius) { this.r = radius; }
area() { return Math.PI * this.r * this.r; }
circumference() { return 2 * Math.PI * this.r; }
}
import
and export
statements
The import and export declarations are used together to make values defined in one module of JavaScript code available in another module. A module is a file of JavaScript code with its own global namespace, completely independent of all other modules. The only way that a value (such as function or class) defined in one module can be used in another module is if the defining module exports it with export and the using module imports it with import.
1
2
3
4
// geometry/constants.js
const PI = Math.PI;
const TAU = 2 * PI;
export { PI, TAU };
1
2
// Import to another module
import { PI, TAU } from './geometry/constants.js';
Made with ❤️ by Francis K.