Tuesday, 4 August 2015

Let V/S Const in Javascript

Constant Looks Like const MAX_ITEMS = 30; you can use conventions like ALL_CAPS to show that certain values should not be modified.

  • Variables declared using const are considered to be constants
  • Constants are also block-level declarations, similar to let. That means constants are destroyed once execution flows out of the block in which they were declared, and declarations are not hoisted to the top of the block.
  • Also similar to let, an error is thrown whenever a const declaration is made with an identifier for an already-defined variable in the same scope. It doesn’t matter if that variable was declared using var (for global or function scope) or let (for block scope). For example:
    var message = "Hello!";
    let age = 25;
    
    // Each of these would cause an error given the previous declarations
    const message = "Goodbye!";
    const age = 30;
        
  • The big difference between let and const is that attempting to assign to a previously defined constant will throw an error in both strict and non-strict modes:

No comments:

Post a Comment