Control Structures Flashcards

0
Q

Switch statement

A
switch (test) {
    case "value":
        statement;
        break;
    default:
        statement;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
1
Q

Initialize 1+ local variables

A

var name1, name2 = true;

name1; // undefined
name2; // true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

4 loops

A

while (test) {

}

do {
….
} while (test);

for (var i=0; i < ?; i++) {
    ...
}

for (fieldName in objName) {
if (objName.hasOwnProperty(fieldName))

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Useful pattern when wanting to setup the test and run the test on each loop? Why does this work?

A

while (setup , test) { … }

This works because the comma operator evaluates each operand but returns the value of the last operand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Increasing clarity about the contents you are working with inside loops.

A

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
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Simple way to turn arguments into an array of arguments.

A

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);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Variable assignment tricks.

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Test if object has property (including prototype chain).

Test if object has it’s own property (not in prototype chain).

Works with arrays?

A

“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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly