What’s the difference between using “let” and “var” in JavaScript?

In simple terms var is function scoped and let is block scoped.

var

  • var variables can be globally accessed
  • var variables can be re-declared
  • let and var variables work the same way when used in a function block.

let

  • let variables cannot be globally accessed
  • let variables cannot be re-declared
  • let variables are usually used when there is a limited use of those variables. 
  • let and var variables work the same way when used in a function block.
'use strict';
let me = 'foo';
let me = 'bar'; // SyntaxError: Identifier 'me' has already been declared
'use strict';
var me = 'foo';
var me = 'bar'; // No problem, `me` is replaced.

Thank you so much for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *