As other programming languages, Javascript has two types of scopes: global and local.
Block Statements
Unlike function, block statements such as if
, switch
, for
, and while
do not create a new scope. For example,
Note: ES6 introduced let
and const
keywords, which supports the declaration of local scope inside block statements.
Global scope lives as long as application lives. Local scope lives as long as functions are called and executed.
Context
Context is used to refer to the value of this
. The global scope context is always the Window object.
The context will change if scope is in the method of an object. For example,
Public vs Private
Not as other programming languages, Javascript does not have public or private scope. However, we can emulate this feature using closures. For example,
Call, Apply vs Bind
You can use Call and Apply to change the context while calling a function. For example,
Call and Apply are only different in how to pass the arguments. However, Call is slightly faster in performance than Apply.
Bind is introduced in ES5. Unlike Call and Apply, Bind does not itself call the function. It binds the context and other arguments before calling the function. For example,
Quiz 1
What is the result of executing this code?
Quiz 2
What is the result of executing this code?