Scope and Closures Flashcards
What does nested scope look like?
function foo(a) { console.log( a + b ); } var b = 2; foo( 2 ); // 4
The RHS reference for b cannot be resolved inside the function foo, but it can be resolved in the Scope surrounding it (in this case, the global).
What does a += 2 represent?
a = a +2
How are variable constraints written?
EX: TAX_RATE
What is Lexical Scope
lexical scope is based on where variables and blocks of scope are authored, by you, at write time, and thus is (mostly) set in stone by the time the lexer processes your code.
Operator that displays the type of something
typeof
ex: a = ‘the’
typeof a // string
What is an array?
an object w/o properties/keys but indexed positions
Name all of the falsy values
" " empty string 0, -0 NaN (invalid numbers) Null Undefined False
What is the difference? == and ===
== checks for value equality w/ coercion allowed
and
=== checks for value equality w/o allowing coercion
method to specify the number of decimal places and what does it return?
toFixed() ex: amount = 10.97777 amount.toFixed(2) // '10.97'
When to use a switch statement?
Can be used instead of many if, else if statements
How to execute a function immediately
place function in ():
ex: (function (){
do something})();
What is closure
Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope. ex: function foo() { var a = 2; function bar() { console.log( a ); } return bar; }
var baz = foo(); baz(); // 2 -- Whoa, closure was just observed, man.
Example of closure
function wait(message) { setTimeout( function timer(){ console.log( message ); }, 1000 ); } wait( "Hello, closure!" );
We take an inner function (named timer) and pass it to setTimeout(..). But timer has a scope closure over the scope of wait(..), indeed keeping and using a reference to the variable message.
A thousand milliseconds after we have executed wait(..), and its inner scope should otherwise be long gone, that inner function timer still has closure over that scope.
What are modules
Most common used of closure. Modules let you define private variables/functions that are hidden from the outside world
What is Polyfilling
Taking the definition of a newer feature and producing a piece of code that equivalent to behavior but is able to run in an older js environment