728x90
05_Conditional_Code.html
<script>
//Flow control
var foo = true;
var bar = false;
if ( bar ) {
// This code will never run.
console.log( "hello!" );
}
if ( bar ) {
// This code won't run.
} else {
if ( foo ) {
// This code will run.
} else {
// This code would run if foo and bar were both false.
}
}
// [Truthy and Falsy Things]
// Values that evaluate to false:
false;
""; // An empty string.
NaN; // JavaScript's "not-a-number" variable.
null;
undefined; // Be careful -- undefined can be redefined!
0; // The number zero.
//Everything else evaluates to true, some examples:
"0";
"any string";
[]; // An empty array.
{}; // An empty object.
1; // Any non-zero number.
// [Conditional Variable Assignment with the Ternary Operator]
//Set foo to 1 if bar is true; otherwise, set foo to 0:
var foo = bar ? 1 : 0;
// [Switch Statements]
switch ( bar ) {
case "bar":
alert( "the value was bar -- yay!" );
break;
case "baz":
alert( "boo baz :(" );
break;
default:
alert( "everything else is just ok" );
}
//Switch statements have somewhat fallen out of favor in JavaScript,
//because often the same behavior can be accomplished by creating an object
//that has more potential for reuse or testing. For example:
var stuffToDo = {
"bar": function() {
alert( "the value was bar -- yay!" );
},
"baz": function() {
alert( "boo baz :(" );
},
"default": function() {
alert( "everything else is just ok" );
}
};
// Check if the property exists in the object.
if ( stuffToDo[ "foo" ] ) {
// This code won't run.
stuffToDo[ "foo" ]();
} else {
// This code will run.
stuffToDo[ "default" ]();
}
</script>
728x90
'JS > JavaScript' 카테고리의 다른 글
[JS] 07. Array (0) | 2017.08.28 |
---|---|
[JS] 06. Loop (0) | 2017.08.28 |
[JS] 04. Operator (0) | 2017.08.28 |
[JS] 03. Type (0) | 2017.08.28 |
[JS] 02. SyntaxBasic (0) | 2017.08.28 |
댓글