Difference between let and var in javascript

Something Like that:
let vs var

var will take scoping to the nearest function block.
let will take scoping to the nearest enclosing block.
Only difference is scoping

We will start with create function and block into this.

Var

For that you need to create first html code.

HTML

<p id="demo1"></p>
<p id="demo2"></p>

After that add this JS code.

JS

function forVar(){
  var x = "Google";
  if (x == "Google") {
  var x = "Home2it";
  document.getElementById("demo1").innerHTML = x;
  }
  document.getElementById("demo2").innerHTML = x;
}
forVar();

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”qXQQOW” default_tab=”result” user=”pradeepanvi”]See the Pen Difference between let and var by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see the both x value has been update

Home2it
Home2it

But in the let scope will not.

For that you need to create first html code.

HTML

<p id="demo3"></p>
<p id="demo4"></p>

After that add this JS code.

JS

function forLet(){
  let y = "Google";
  if (y == "Google") {
  let y = "Home2it";
  document.getElementById("demo3").innerHTML = y;
  }
  document.getElementById("demo4").innerHTML = y;
}
forLet();

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”eEQxpE” default_tab=”result” user=”pradeepanvi”]See the Pen Difference between let and var 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Now you can see the both y value is not update

Home2it
Google

Leave a Reply

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