Checking if a Variable Exists
>>> if (typeof somevar !== "undefined"){result = 'yes';}
variable somevar may have been declared but not assigned a value yet and you'll still get the same result
>>> var somevar;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""
typeof will always return a string and you can compare this string with "undefined"
>>> var somevar;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""
>>> somevar = undefined;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""
Alternative if Syntax
var result = (a === 1) ? "a is one" : "a is not one";
Switch
var a = '1';
var result = '';
switch (a) {
case 1:
result = 'Number 1';
break;
case '1':
result = 'String 1';
break;
default:
result = 'I don\'t know';
break;
}
result;
Loops
In JavaScript, there are four types of loops:
while loops
do-while loops
for loops
for-in loops
var punishment = '';
for (var i = 0; i < 100; i++) {
punishment += 'I will never do this again, ';
}
var a = [ 'a', 'b', 'c', 'x', 'y', 'z'];
var result = '\n';
for (var i in a) {
result += 'index: ' + i + ', value: ' + a[i] + '\n';
}
No comments:
Post a Comment