In JavaScript, statements are instructions that are executed by the web browser or Node.js. A statement can be a simple or complex operation that performs an action, such as assigning a value to a variable, calling a function, or controlling the program flow.
JavaScript programs are essentially a sequence of these statements. Together, they create the logical flow of the application.
There are several different types of statements in JavaScript, each serving a unique purpose.
Declaration statements are used to introduce variables, functions, or classes into a program. These statements begin with a keyword (like var, let, const, or function) followed by an identifier (its name).
Variables are containers for storing data values.
var x = 5; var y = 6; var X = 4; var z = x + y;console.log(z); // Outputs 11
Note: JavaScript identifiers are highly case-sensitive. Notice that the variable
xis not the same as the variableX.
Expression statements, such as function calls or assignments, evaluate an expression and generate a value in JavaScript. They can be assigned to a variable or used as part of a larger expression.
// Function call expression
console.log('Hello World');
// Assignment expression
var x = 5;
x = 6; // Re-assigning the value
console.log(x); // Outputs 6
Conditional statements, such as if statements or switch statements, control the flow of a program based on a specific condition evaluating to true or false.
// If statement
var x = 10;
if (x > 5) {
console.log('x is greater than 5');
}
// Switch statement
var y = 2;
switch (y) {
case 1:
console.log('y is 1');
break;
case 2:
console.log('y is 2'); // This will execute
break;
default:
console.log('y is neither 1 nor 2');
}
Loop statements, such as while loops or for loops, are used to repeatedly execute a block of code as long as a specified condition remains true.
Convention: The
letkeyword is conventionally used to declare counter variables (likei) insideforloops.
// While loop
var x = 4;
while (x < 5) {
console.log(x); // Outputs 4
x++;
}
// For loop
for (let i = 0; i < 5; i++) {
console.log(i); // Outputs 0, 1, 2, 3, 4
}
Jump statements, such as break or return statements, forcefully transfer control to another part of the program, overriding normal sequential execution.
// Break statement: Stops the loop entirely
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
}
console.log(i); // Outputs 0, 1, 2
}
// Return statement: Exits a function and outputs a value
function add(x, y) {
return x + y;
}
console.log(add(5, 5)); // Outputs 10
Which type of statement transfers control to another part of the program (e.g., using the break keyword)?