Essential JS book Flashcards
What is Duff’s device?
A way to better handle loops when there are a lot of items to iterate over. It breaks the total into sets of 8 and then processes 8 at a time using a do/while and a switch statement with fall-through.
What is a best practice for avoiding global variables?
Namespacing.
MyNamespace = {};
MyNamespace.EventUtil = { … }
This is worth the tradeoff in lookups and code-writing because of maintainability
What is the difference between a comma operator and a comma separator?
Comma separators simply delimit members in a list (as in an array).
Comma operators partition expressions within statements.
What’s a good way to handle calculations with decimals (e.g. with currency)?
Convert to integers, do math, convert back to decimals.
Why is the isNaN( ) method problematic and what’s a more reliable solution?
It reports true for things that are not numbers, e.g. “foo” or undefined, because of type coercion.
return ( x !== x ) will solve this problem. “foo” !== “foo”; // false NaN !== NaN; // true
Semicolons are only inserted when?
Before a } token, after one or more newlines, or at the end of the program. However, if the new line’s initial token could be interpreted as a continuation of the statement. a + b \n var c; is fine. a + b \n +c; not fine.
Finally, semicolons are inserted after certain keywords, the ‘restricted productions’
What are JavaScript ‘restricted productions’ and what do they do?
return, throw, break, continue, ++, - -
You cannot inert a line break between one of these and the rest of the statement; a semicolon will be inserted.
return \n someObject will return nothing.
Never omit a semicolon before a statement beginning with what characters?
+, -, / , (, or [
What is the one exception to JavaScript’s lack of block scoping?
Exceptions. try / catch binds a caught exception to a variable that is scoped just to the catch block. That is, the x in catch( x ) { } will only have scope inside.
What is a higher order function?
A function that takes a function as an argument or returns a function as a result.
What is a variadic function?
one which accepts a variable number of arguments.
What is arity?
The number of arguments or operands a function or operation takes.
If you need to modify a function’s arguments object, what should you do?
First, never modify the arguments object directly.
Do it indirectly like so:
var args = Array.slice.call( arguments ) or Array.slice.call( arguments, 1 );
What is a the “receiver” of a method call?
It’s the thing that gets bound to “this” and it’s determined by the call itself.
obj1. someFunc( ); // obj1 is receiver
obj2. newFunc( ); // ( newFunc: obj1.someFunc;) obj2 is receiver
obj2. forEach( ob1.someFunc ); obj2 is the receiver
How can you use bind( ) to have setTimeout( ) use a particular object for ‘this’?
var timer = setTimeout( someObj.method.bind( someObj ), 1000 );