let & const: A closer look

3 tips for better 'let' and 'const' usage in Javascript

let & const: A closer look

Table of contents

No heading

No headings in the article.

ES6 changed the way we used variables in JS forever. It brought the sudden demise of var as the popular choice for declaring variables. let and const now allow variables to be truly block-scoped.

The difference between let and const is pretty much folk wisdom right now in the Web Dev circles. Here are some things about let and const that might trip you up nonetheless -

  • It's possible to re-assign the value of the property of an object even if the object was declared with const before, like so -

      const changeValue = {x: 20, y: 40};
      changeValue.x = 100;
      console.log(changeValue.x);
      // No error
    

    Output -

  • const also allows adding another property to an already declared object like so -

      const changeValue = {x: 20, y: 40};
      changeValue.z = 60;
      console.log(changeValue.z);
    

    Output -

  • Re-declaring let or const variables in the same scope isn't allowed anymore. An error will be thrown and you'll be handed over to the Javascript police before you even know it.
    Fret not, though! Re-declaring these variables in a different block is perfectly fine and won't impact your life as a free and peaceful Javascript citizen.
    Example code -


It's a wrap! Stay tuned for my next blog post.