Javascript Patterns Book Flashcards
How does javascript read statements, right to left or left to right?
Right to left. var x = y = 10; // beware of the possible global variable y
Why is it faster for for-loops to count down to zero than up to max?
It’s faster to compare against zero than anything else.
How can you protect against naming collisions with the hasOwnProperty method? (e.g. make sure a method of that name isn’t added to your object)?
Create a shortcut to it: var hasOwn = Object.prototype.hasOwnProperty; Then say: hasOwn.call( myObj, "myProp" );
If augmenting a built-in function (which should only be done for purpose of polyfill) how should you check that the polyfill is needed?
if ( typeof Object.prototype.polyfillMethod !== "function" ) { // make the method
What is right way to use parseInt() function?
parseInt( num, radix ); use radix to avoid confusion. E.g. parseInt( ‘09’ ) will be 0 in ES3 because it assume octal number.
What is currying?
The process of making a function able to understand and handle partial application.
Partial application: passing just some and not all arguments to a function.
How do you make a generic curry function?
function (fn) { var storedArgs = Array.prototype.slice.call( arguments, 1); return function( ) { var newArgs = A.p.slice.call( arguments ), allArgs = storedArgs.concat(newArgs); return fn.apply( null, allArgs );
What are two reasons to use object literal not object constructor
Scope resolution will be more involved with constructor because js will need to make sure you aren’t using a local Object. Also, unexpected results with new Object( 5 ) or new Object ( true )
What gets returned from a constructor?
The object referred to by ‘this’ (default) or another object. Must be an object though. This is used by jQuery so you can say new or not — either way, a new unit obj is returned
What does it mean to throw an error as a literal?
It means not using new Error() constructor. Just say throw Error( ) or throw { message: "something", remedy: someFunc } Advantage is you can set custom parameters.