if (<expression>) {
do a...
} else if (<expression2>) {
do b...
} else if (<expression3>) {
do c...
} else {
do d...
}
function doSomething(person) {
if (!person) return; // <-- defensive check
...
....
}
if (<expression>) {
do a...
} else if (<expression2>) {
do b...
do a...
} else if (<expression3>) {
do c...
do a...
} else {
do d...
do a...
}
var mnemonicWord;
switch (<checked value>) {
case <value>: //<-- case clause
//...do something
break;
default:
mnemonicWord = '';
}
switch (rainbowColor) {
case 'red':
mnemonicWord = 'Richard';
break;
case 'orange':
mnemonicWord = 'of';
break;
default:
mnemonicWord = '';
}
switch (<main) {
case 'a':
case 'b':
... ;
break;
default:
mnemonicWord = '';
}
for(){
// do something
}
//In the parenthesis we make 3 conditions
// - the initial starting conditions
// - the condition required to continue
// - what we do after every cycle of the loop
for(var i=0; //first part
for(var i=0; i < 10; //second part
for(var i=0; i < 10; i++){ //third part
// do something
}
//maybe
var buttons =
document.getElementsByClassName('button');
for(var i=0; i < buttons.length; i+=1){
console.log('text: '
+ button[i].innerText);
}
var i = 0;
while (i < 3) {
console.log('while', i);
i+=1;
}
// OUTPUT
// 'while', 0
// 'while', 1
// 'while', 2
var i = 0;
do {
console.log('do...while', i);
} while (i > 0)
// OUTPUT
// 'do...while', 0
var obj = {a: 1, b: 2, c: 3};
for (var prop in obj) {
console.log('obj.' + prop
+ ' = ' + obj[prop]);
}
// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"
// AVOIDING THE PROTOTYPE CHAIN
var triangle = {a: 1, b: 2, c: 3};
function ColoredTriangle() {
this.color = 'red';
}
ColoredTriangle.prototype = triangle;
var obj = new ColoredTriangle();
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log('obj.' + prop
+ ' = ' + obj[prop]);
}
}
// Output:
// "obj.color = red"
Used to wait a while and then do something
var timer = setTimeout(function(){
console.log('BOO!');
}, 3000);
// ^ Waits 3 seconds then
// logs 'BOO!' to the console
// Clear using:
clearTimeout(timer);
Used to do something every <x> timespan
var seconds = 0;
var timer = setInterval(function(){
seconds += 1;
}, 1000);
// 'timer' gives you id of the timer
document.getElementById('seconds')
.innerText = seconds;
// ^ Updates the seconds display
// on a page
// TO CLEAR
clearInterval(timer);
See new presentation
See new presentation