Control Structures Flashcards
Switch statement
switch (test) { case "value": statement; break; default: statement; }
Initialize 1+ local variables
var name1, name2 = true;
name1; // undefined
name2; // true
4 loops
while (test) {
…
}
do {
….
} while (test);
for (var i=0; i < ?; i++) { ... }
for (fieldName in objName) {
if (objName.hasOwnProperty(fieldName))
…
}
Useful pattern when wanting to setup the test and run the test on each loop? Why does this work?
while (setup , test) { … }
This works because the comma operator evaluates each operand but returns the value of the last operand.
Increasing clarity about the contents you are working with inside loops.
When you are in a loop, you will often work on elements like record[i][field]
, which you might know to be the product’s price when you’re creating the loop, but that won’t be clear 6 months from now. It can be useful to rename elements to variable names that semantically represent the element, such as:
var model, tag; for (var i=0 ; i < collection ; i++) { model = collection[i]; for (var y=0 ; y < model ; y++) { tag = model[y]; // ... work on `tag` now } }
Simple way to turn arguments
into an array of arguments.
Array.prototype.slice.call(arguments, [startIndex])
// for example, if you want all args in the array Array.prototype.slice.call(arguments, 0); // or, simple Array.prototype.slice.call(arguments);
// if you want all args after the first arg Array.prototype.slice.call(arguments, 1);
Variable assignment tricks.
When assigning a value to a variable, after the assignment is finished, the value that was assigned is returned from the expression. This means you can do things like:
var a; if (a = "string") // works. the expression is evaluated and "string" is returned, which is truthy
func(a = “this string is passed in as the function argument AFTER this string is ALSO assigned to a
”);
console.log(a = "this works too"); // "this works too" is printed to console
Test if object has property (including prototype chain).
Test if object has it’s own property (not in prototype chain).
Works with arrays?
“PI” in Math // => true
// also works on arrays var a = new Array("red", "blue");
0 in a //=> true
“red” in a //=> false
“length” in a //=> true
a.hasOwnProperty(0); //=> true