Jump to content

Difference between var and let

Go to solution Solved by 0x21,

Variables declared by let have their scope in the block for which they're defined, and any contained blocks. The scope of var is that of the entire enclosing function. Also, unlike var which will initialise with the value undefined, let variables are not initialised until evaluated.

function varExample() {
  var n = 1;
  if (n === 1) {
    var n = 2;
    console.log(n); // 2
  }
  console.log(n); // 2
}

function letExample() {
  let n = 1;
  if (n === 1) {
    let n = 2;
    console.log(n); // 2
  }
  console.log(n); // 1
}

For more information see: let, var, blocks.

Would someone explain to me what is the difference between let and var in this situation as I don't quite understand the exact difference between let and var ? 

 

The only statement that I kinda understand is this : 

var
Declares a variable, optionally initializing it to a value.
let
Declares a block-scoped, local variable, optionally initializing it to a value.
 

From the statement above let does make local variable but in the code below let y = 5; in a local scope is not defined ??? 

 

The situation is :

 

if (true) {
  var x = 5;
}
console.log(x);  // x is 5

------------------------------

if (true) {
  let y = 5;
}
console.log(y);  // ReferenceError: y is not defined
Link to comment
Share on other sites

Link to post
Share on other sites

16 minutes ago, BloodViolet said:

var is scoped to the nearest function block and let is scoped to the nearest enclosing block.

 

As I've read some article after your comment the only thing that I don't fully understand is what exactly is the enclosing block ? An example would be perfect if possible, thanks in advance !

Link to comment
Share on other sites

Link to post
Share on other sites

Variables declared by let have their scope in the block for which they're defined, and any contained blocks. The scope of var is that of the entire enclosing function. Also, unlike var which will initialise with the value undefined, let variables are not initialised until evaluated.

function varExample() {
  var n = 1;
  if (n === 1) {
    var n = 2;
    console.log(n); // 2
  }
  console.log(n); // 2
}

function letExample() {
  let n = 1;
  if (n === 1) {
    let n = 2;
    console.log(n); // 2
  }
  console.log(n); // 1
}

For more information see: let, var, blocks.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×