0

var x = 1;
if (x === 1) {
  var x = 3;
  console.log(x);
  // Expected output: 3
}
console.log(x);
// Expected output: 3

Can someone please explain this: in the loop, x should be printed as 3 because the condition is satisfied but out of the loop, the last line should print 1 because it's out of loop. However, the output is 3. Sorry if it's a dumb question – I am new to JS.

Q) Also can you please let me know good website for a code dry run?

Wongjn
  • 8,544
  • 2
  • 8
  • 24
Izza Ijaz
  • 9
  • 1

1 Answers1

1

The main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body while let variables are scoped to the immediate enclosing block denoted by { }.

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo"
    let baz = "Bazz";
    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();

Read more details in this link : What is the difference between "let" and "var"?