Table of contents
Block Statement
A set of curly braces forms a block in JavaScript. One or more statements can be written inside a block statement.
{
var a = 10;
let b = "test";
}
Conditionals in JavaScript
Conditional flows help us to alter the flow of code during execution. They execute a statement only if the condition is satisfied. The boolean datatype helps us in keeping track of the conditions. There are two ways for conditional flows in JavaScript:
if else
The
if
block of the statement is executed when the condition is satisfied otherwise theelse
block is executed. However, writing anelse
block is optional. Also, we can check for multiple conditions in the if block or add another condition using theelse if
block. This is basically anelse
block with another if condition.if(condition) { // execute if the condition is true /* any number of statements */ } else if (condition2) { // execute if the condition2 is true /* any number of statements */ } else { //execute if non of the above if satisfies /* any number of statements */ }
💡Indenting your code makes it easier to read, write and debug.💡While checking the equality of variables, use the strict equality operator(=== or !==) unless you explicitly need the equality operator(== or !=).switch
The switch helps to execute the code block which satisfies the condition based on the given variable. It is a better alternative to
if
conditional when there are a lot ofelse if
statements. The condition in this case is usually not a boolean, but rather a string or a number. Although, it can be a boolean as well. The else case is written in the form of a default case.var a = "test"; switch(a) { case "test": console.log("Hi"); break; case "greet": console.log("Hello"); break; default: console.log("Bye"); }
As we can see in the above example, each match is written as a case. There is a break statement at the end. This is needed so that we do not execute the case below it. This is also known as a fall-through switch case in JavaScript and is sometimes needed. For example, when we want to perform the same task for multiple conditions. See the below example for this.
var dayOfWeek = 3; switch(dayOfWeek) { case 0: case 1: case 2: case 3: case 4: console.log("WeekDay"); break; case 5: case 6: console.log("Weekend"); break; default: console.log("Invalid Day";) }
💡Always define the default case with a switch conditional.Ternary conditionals
An
if else
can also be converted to a ternary. It is an abstract way of writing the if conditionals using the?
and:
.var a = 10; var result = a === 10 ? 5 : 2; console.log(result); // 5
If the condition is true, then the statement following the
?
is executed otherwise, the statement following the:
is executed.
Falsy Values in JavaScript
JavaScript behaves a bit differently. For conditions, apart from the boolean true
and false
values, certain other values also evaluate to false
. All the falsy values are listed below:
false
null
undefined
0 (number zero)
NaN
"" (empty string)