Introduction to Javascript 2
Understanding Scope
The scope of a variable controls where it can be accessed from in the program. It can be of
- Global Scope
- Function scope
- Block scope ( if / for etc )
Variable defination
Variables can be defined with var
, const
and let
keywords.
var
keyword is function scopedlet
andconst
keyword are block scoped.
this
keyword
- Different from how other languages use this.
- In JS land, value of this depends on how a function is called.
call
andapply
helps in setting correctthis
value- the difference is in the way the arguments are provided
apply
takes a array of arguments whereascall
takes in individual arguments.
Hoisting
- All variable declarations are hoisted on the top of their scope.
- Hence they are processed before the code gets executed.
var
is set as undefined and can be accessed before declaration.let
andconst
cannot be accessed and throws a referenceError if tried.
Sources