This stuff should look really familiar …
423 === 423
→
!!5
→
¯\_(ツ)_/¯
{
's and }
'sConditionally execute a block of code (should look familiar):
if
followed by a boolean expression enclosed in parentheseselse if
's to chain conditionals, with corresponding block of code to executeelse
, with corresponding block of code to execute
if (some_boolean_expression) {
// do stuff here if expression is true
}
if (some_boolean_expression) {
// do stuff
} else if (another_boolean_expression) {
// do other stuff
} else {
// do other other stuff
}
Again, should look familiar… repeatedly execute a block of code:
// initialization
// | condition
// | | afterthought/increment
// | | |
for(let i = 0; i <= 5; i = i + 1) {
console.log(i);
}
// (i++ works too, of course)
Speaking JavaScript calls the three parts: initialization, check and update.
Hey - notice that let
in front of the loop variable declaration? Do that.
Conditionally repeat a block of code:
while (boolean_expression) {
// repeat this stuff as long as boolean expression is true
}
Conditionally repeat a block of code and ensure that code is executed at least once:
do {
// repeat this stuff at least once
} while (boolean_expression)
The keyword break
immediately stops the execution of a loop:
for (let num = 1; num < 30; num++) {
if (num % 7 == 0 && num % 3 == 0)
break;
console.log(num);
}
The keyword continue
stops the current iteration and immediately skips to the next one:
for(let num = 1; num < 30; num++) {
if (num % 7 == 0 && num % 3 == 0)
continue;
console.log(num);
}
What is the output of the above programs? →
1 through 20 and 1 through 29 skipping 21 respectively
Execute code based on value of switch.
var day = "thu";
switch (day) {
case "fri":
console.log("Friday");
break;
case "thu":
console.log("Thursday");
break;
case "wed":
console.log("Wednesday");
break;
}
What is the output of the above programs? →
Thursday
One way to define a function in JavaScript is to create a variable, and set it equal to a function:
var f = function(x) {
return x
}
From Eloquent JavaScript: