Showing posts with label javascript scope. Show all posts
Showing posts with label javascript scope. Show all posts

Thursday, July 30, 2015

JavaScript declarations and their scope limits


Types of JavaScript variable declarations:

  1. Var keyword
  2. Let keyword
  3. Const keyword
  4. Undeclared variable (Ex: a =2;)

Scope of declarations:

  • Var keyword
    • Limited to function level.
    • Can be used in strict mode and non-strict mode.
    • For example, function scopeOfVar(){ var a; }, here the scope is limited to function scopeOfVar().
    • If the variable declared with var inside of a block in a function, then also that variable has scope throughout the function.
    • But the variable can be accessed before it’s declaration, if it accessed before declaration will give a ‘undefined’ as the value, which is called as ‘hoisting’.
    • Usage var variableName [= value];
  • Let keyword
    • Should be used only if strict mode is enabled.
    • Let will have scope only in the block it is declared.
    • Commonly used for  small blocks or scopes.
    • Usage let variableName [= value];
  • Const keyword
    • Should be used only if strict mode is enabled.
    • Const will have scope only in the block it is declared.
    • Const should be initialized while declaring.
    • It can be an object also like var and let.
    • Usage: const variableName = constant value;
  • Undeclared variable (Ex: a =2;)
    • Should be used only in non-strict mode.
    • Will throw reference error if used in strict mode.
    • If a variable is declared without any keyword in any scope will become a member of global object, i.e., undeclared variable is always in global scope.
    • It is not suggested as a best practice to use like this.
    • Usage: variableName = value;