It is a fundamental aspect of programming that allows you to control the order in which statements are executed in your code.
They are used to execute different code blocks depending on whether a condition is true or false.
if/else statement:
if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }
switch statement:
switch (expression) { case value1: // code to be executed if expression matches value1 break; case value2: // code to be executed if expression matches value2 break; default: // code to be executed if expression doesn't match any case }
ternary operator: switch statement:
// If condition is true, expression1 is evaluated, otherwise expression2 is evaluated. condition ? expression1 : expression2;
They are used to repeat a block of code multiple times.
for loop:
for (initialization; condition; increment/decrement) { // code to be executed }
while loop:
while (condition) { // code to be executed }
do..while loop:
do { // code to be executed } while (condition);
Statements that allow you to modify the flow of your code.
break:
Whenbreakis encountered inside loop or switch statement, they immediately terminated and the program continues executing from the next statement.for (let i = 11; i <= 30; i++) { if (i === 17) { break; } console.log(i); }
continue:
Whencontinueis encountered inside loop, current iteration of loop is skipped and loop continues with next iteration.for (let i = 11; i <= 30; i++) { if (i % 2 === 0) { continue; } console.log(i); }
return:
Whenreturnis encountered inside function, it is immediately terminated and program continues executing from next statement.
If value is provided after return keyword, that value is returned as result of function.function addNumbers(num1, num2) { if (typeof num1 !== 'number' || typeof num2 !== 'number') { return 'Error: both arguments must be numbers'; } return num1 + num2; } console.log(addNumbers(2, 3)); // => 5 console.log(addNumbers('2', 3)); // => Error: both arguments must be numbers
JS provides a way to handle errors and unexpected situations using try..catch blocks.
It allows you to handle errors that may occur inside block of code.
try { // some code that may throw an error console.log('Executing try block'); } catch (error) { console.log('An error occurred:', error.message); } finally { console.log('Executing finally block'); }
_It allows you to explicitly
throwan error. _function divide(a, b) { if (b === 0) { throw new Error('Cannot divide by zero'); } return a / b; } try { console.log(divide(10, 0)); } catch (error) { console.log('An error occurred:', error.message); }