declare variable using let give different output than declare using var in JavaScript?

Viewed 19

I have declare variable x using let.

In the output of this program , the value of x is not visible.

but when I declare x using var , I can see the output of this line .

var x = "5" + 2 + 10;
  document.getElementById('para').innerHTML = `the value of x is : ${x}`;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=
    , initial-scale=1.0">
    <title>Document</title>
    <!-- <link  rel="stylesheet"  href="jslearn.js" type="text/javascript"> -->
</head>
<body>
    <h1> javascript </h1>
    <p>
       javascript is a wonderful programming language
    </p>
    <p> the result of adding is : </p>

    <p id="para"></p>

    <script src="jslearn.js"></script>
</body>
</html>

`

1 Answers

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

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();
Related