A program Control Flow
Control flow is the order in which individual statements, instructions, or function calls are executed or evaluated. The control flow of a Javascript program is regulated by conditional statements, loops, and function calls.
In JavaScript, comparison operators are used to compare two values. Here are the main comparison operators:
==): This operator checks if the values of two operands are equal or not. If yes, then the condition becomes true.console.log(5==5);// trueconsole.log(5=='5');// true, because it does type coercion!=): This operator checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.console.log(5!=4);// trueconsole.log(5!='5');// false, because it does type coercion===): This operator checks if the values of two operands are equal or not, and also checks the types. If yes, then the condition becomes true.console.log(5===5);// trueconsole.log(5==='5');// false, because the types are different!==): This operator checks if the values of two operands are equal or not, or the types are not the same. If yes, then the condition becomes true.console.log(5!==4);// trueconsole.log(5!=='5');// true, because the types are different>), Less than (<), Greater than or equal to (>=), Less than or equal to (<=): These operators are used to compare the values of two numbers.console.log(5>4);// trueconsole.log(5<4);// falseconsole.log(5>=5);// trueconsole.log(5<=4);// falseComparison operators always return a boolean value
Remember, comparison operators always return either `true` or `false`.
In JavaScript, Boolean operators are used to create more complex conditional statements using logical concepts. Here are the main Boolean operators:
&&): This operator returnstrue if both operands are true.console.log(true&&true);// trueconsole.log(true&&false);// false||): This operator returnstrue if at least one of the operands is true.console.log(true||false);// trueconsole.log(false||false);// false!): This operator returnstrue if the operand is false, andfalse if the operand is true. It basically reverses the Boolean value of the operand.console.log(!true);// falseconsole.log(!false);// trueThese operators are often used in combination with comparison operators to create complex logical conditions. For example:
let a=10;let b=20;if(a>5&& b>10){ console.log('Both conditions are true');}In this example, the message will be printed to the console because both conditions (a > 5 andb > 10) are true.
In JavaScript,if,else if, andelse are used to create conditional statements that allow your code to make decisions and take different actions depending on certain conditions. Here’s how they work:
This is used to specify a block of code to be executed if a specified condition is true.
let a=10;if(a>5){ console.log('a is greater than 5');}Becausea is indeed greater than 5, the message ‘a is greater than 5’ will be printed to the console.
This is used to specify a new condition to test if the first condition is false.
let a=5;if(a>5){ console.log('a is greater than 5');}elseif(a==5){ console.log('a is equal to 5');}Becausea is not greater than 5, the first block of code is not executed. However, becausea is indeed equal to 5, the message ‘a is equal to 5’ will be printed to the console.
This is used to specify a block of code to be executed if all previous conditions are false.
let a=4;if(a>5){ console.log('a is greater than 5');}elseif(a==5){ console.log('a is equal to 5');}else{ console.log('a is less than 5');}Becausea is neither greater than 5 nor equal to 5, the messagea is less than 5 will be printed to the console.
The ternary operator in JavaScript is a shortcut for theif statement. It’s called “ternary” because it takes three operands: a condition, a result fortrue, and a result forfalse.
condition? expressionIfTrue: expressionIfFalseIf thecondition istrue, the operator returns the value ofexpressionIfTrue; if thecondition isfalse, it returns the value ofexpressionIfFalse.
let a=10;let result= a>5?'a is greater than 5':'a is not greater than 5';console.log(result);// prints "a is greater than 5"a is indeed greater than 5, the variableresult is set to the string ‘a is greater than 5’, and that’s what gets printed to the console.
The ternary operator can be very useful for short, simple conditions, but for more complex conditions, usingif,else if, andelse can be more readable.
Theswitch statement in JavaScript is used to perform different actions based on different conditions. It’s a good alternative to a series ofif…else if statements when you have a single condition that can lead to several possible outcomes.
switch(expression){casevalue1:// code to be executed if expression equals value1break;casevalue2:// code to be executed if expression equals value2break;...default:// code to be executed if expression doesn't match any cases}Theswitch statement evaluates an expression, matching the expression’s value to acase clause, and executes statements associated with that case. If no matching case is found, it executes the code in thedefault clause.
let fruit='apple';switch(fruit){case'banana': console.log('I am a banana');break;case'apple': console.log('I am an apple');break;default: console.log('I am not a banana or an apple');}Becausefruit is ‘apple’, the message ‘I am an apple’ will be printed to the console. Iffruit was ‘banana’, it would print ‘I am a banana’. Iffruit was anything else, it would print ‘I am not a banana or an apple’. Thebreak keyword is used to prevent the code from running into the next case automatically.
Thewhile loop in JavaScript is used to repeatedly execute a block of code as long as a specified condition istrue. Here’s the syntax:
while(condition){// code to be executed as long as the condition is true}Thecondition can be any expression that evaluates to a boolean value, eithertrue orfalse. If the condition istrue, the code inside the loop will be executed. After each execution, the condition is checked again, and if it’s stilltrue, the loop continues to run. This process repeats until the condition becomesfalse.
let i=0;while(i<5){ console.log(i); i++;}The loop will print the numbers 0 through 4 to the console. The variablei starts at 0 and is incremented by 1 after each loop iteration. Wheni becomes 5, the conditioni < 5 is no longer true, so the loop stops running.
Always ensure the condition becomes false
Be careful when writing `while` loops, because if the condition never becomes `false`, the loop will run indefinitely, which can cause your program to crash.
Performance considerations
Keep in mind that looping operations can be resource-intensive, especially with large data sets. Always consider the performance implications of your code when using loops.
In JavaScript,break andcontinue are two control flow statements that you can use in loops.
Thebreak statement is used to exit the current loop prematurely, stopping its execution immediately. It’s often used inswitch statements, but can also be used infor,while, anddo...while loops.
for(let i=0; i<10; i++){if(i===5){break;} console.log(i);}// This will print the numbers 0 through 4 to the consoleThe loop stops running wheni is equal to 5, even though the loop conditioni < 10 would still be true.
Thecontinue statement is used to skip the current iteration of the loop and move directly to the next one. It ends the current iteration and continues with the next one.
for(let i=0; i<10; i++){if(i===5){continue;} console.log(i);}// This will print the numbers 0 through 4 and 6 through 9 to the consoleIn this example, the number 5 is not printed to the console because wheni is equal to 5, thecontinue statement is executed, ending that iteration of the loop early.
Use `break` and `continue` judiciously
Both `break` and `continue` can be very useful for controlling the flow of your loops, but they should be used judiciously, as they can make your code more difficult to read and understand if used excessively.
Thedo...while loop is a variant of thewhile loop in JavaScript. This loop will execute the block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
do{// code to be executed}while(condition);Thecondition can be any expression that evaluates to a boolean value, eithertrue orfalse. If the condition istrue, the loop will continue to run. This process repeats until the condition becomesfalse.
let i=0;do{ console.log(i); i++;}while(i<5);The loop will print the numbers 0 through 4 to the console. The variablei starts at 0 and is incremented by 1 after each loop iteration. Wheni becomes 5, the conditioni < 5 is no longer true, so the loop stops running.
Difference between `do...while` and `while`
The key difference between `do...while` and `while` is that `do...while` guarantees the loop will run at least once, because it checks the condition after executing the loop body. In a `while` loop, if the condition is false at the start, the loop body might not run at all.
Thefor loop in JavaScript is used to repeatedly execute a block of code a certain number of times. It’s often used when you know beforehand how many times you need to loop.
for(initialization; condition; finalExpression){// code to be executed on each loop iteration}initialization is executed before the loop starts. It’s often used to declare and initialize a counter variable.condition is checked before each loop iteration. If it’strue, the loop continues; if it’sfalse, the loop stops.finalExpression is executed at the end of each loop iteration, usually to update the counter.for(let i=0; i<5; i++){ console.log(i);}Thefor loop will print the numbers 0 through 4 to the console. The variablei starts at 0 and is incremented by 1 after each loop iteration. Wheni becomes 5, the conditioni < 5 is no longer true, so the loop stops running.
The choice between afor loop andarray methods likeforEach,map,filter,reduce, etc., depends on the specific situation and your personal preference. Both have their uses and can be better in different scenarios.
For Loop:
break statement, which is not possible with array methods likeforEach,map, etc.Array Methods:
map,filter,reduce etc., return a new array and do not mutate the original array, which helps in maintaining immutability in your code.Here’s an example of usingfor loop andmap method to double the elements in an array:
For Loop:
let arr=[1,2,3,4,5];for(let i=0; i< arr.length; i++){ arr[i]= arr[i]*2;}Map Method:
let arr=[1,2,3,4,5];let doubled= arr.map(num=> num*2);In general, if you’re working with arrays and don’t need to break out of the loop, array methods can be a cleaner and more readable choice. If you need more control over the loop or are working with larger datasets, afor loop might be a better choice.