Tutorial by Examples

In its most simple form, an if condition can be used like this: var i = 0; if (i < 1) { console.log("i is smaller than 1"); } The condition i < 1 is evaluated, and if it evaluates to true the block that follows is executed. If it evaluates to false, the block is skipped....
Switch statements compare the value of an expression against 1 or more values and executes different sections of code based on that comparison. var value = 1; switch (value) { case 1: console.log('I will always run'); break; case 2: console.log('I will never run'); break;...
Can be used to shorten if/else operations. This comes in handy for returning a value quickly (i.e. in order to assign it to another variable). For example: var animal = 'kitty'; var result = (animal === 'kitty') ? 'cute' : 'still nice'; In this case, result gets the 'cute' value, because the v...
A strategy pattern can be used in Javascript in many cases to replace a switch statement. It is especially helpful when the number of conditions is dynamic or very large. It allows the code for each condition to be independent and separately testable. Strategy object is simple an object with multip...
The Boolean operators || and && will "short circuit" and not evaluate the second parameter if the first is true or false respectively. This can be used to write short conditionals like: var x = 10 x == 10 && alert("x is 10") x == 10 || alert("x is not 1...

Page 1 of 1