Skip to content

JavaScript Statements

JavaScript statements are commands that perform actions. They are executed sequentially, in the order they are written. Here are some key types of statements:

1. Declarations

  • Variable Declarations: Using var, let, and const.

var x = 5;

let y = 10;

const z = 15;

2. Expressions

Expressions are combinations of values, variables, and operators that compute a value.

            let a = 5;

let b = 10;

let sum = a + b;  // Expression

3. Conditional Statements

These control the flow of execution based on conditions.

  • if…else

if (x > 5) {

    console.log(‘x is greater than 5’);

} else {

    console.log(‘x is less than or equal to 5’);

}

  • else if

if (x > 10) {

    console.log(‘x is greater than 10’);

} else if (x > 5) {

    console.log(‘x is greater than 5 but less than or equal to 10’);

} else {

    console.log(‘x is less than or equal to 5’);

}

  • switch

switch (x) {

    case 5:

        console.log(‘x is 5’);

        break;

    case 10:

        console.log(‘x is 10’);

        break;

    default:

        console.log(‘x is neither 5 nor 10’);

}

4. Looping Statements

Loops execute a block of code as long as a specified condition is true.

  • for loop

for (let i = 0; i < 5; i++) {

    console.log(i);

}

  • while loop

let i = 0;

while (i < 5) {

    console.log(i);

    i++;

}

  • do…while loop

let i = 0;

do {

    console.log(i);

    i++;

} while (i < 5);

5. Functions

Functions are blocks of code designed to perform a particular task.

function greet(name) {

    return ‘Hello, ‘ + name;

}

console.log(greet(‘Alice’));  // Output: Hello, Alice

6. Exception Handling

To handle errors gracefully, JavaScript provides try…catch statements.

try {

    let result = riskyFunction();

    console.log(result);

} catch (error) {

    console.error(‘An error occurred:’, error);

} finally {

    console.log(‘This code runs regardless of whether an error occurred.’);

}