Friday, August 10, 2018

Javascript let vs var


Javascript Let vs Var


Into this post we are going to discuss difference between Javascript var and Let.

we are going to discuss about Javascipt variable declaration method like where user can declare variable with var and where user can declare variable with let.



Global Variable Declaration:

If we define var and let variable same globally then let variable will not get added into global window object while var variable will get added to global window object.

So let's declare two variables at the time of window loaded
let Visionfortech_let = "Visionfortech is defined as let variable"

var Visionfortech_var = "Visionfortech is defined as var variable"

console.log(Visionfortech_let);
o/p : undefined

console.log(Visionfortech_var);
o/p : Visionfortech is defined as var variable
  

Redeclare Variable:


So Here let's discuss about one more example of let vs var into Javascript.You can not declare let variable but you can redeclare var variable


'use strict';
var let_vs_var = "Javascript let vs var";
var let_vs_var = "Difference Between let and var Javascript"; //replaced easily
'use strict';
let let_vs_var = "Javascript let vs var";
let let_vs_var = "Difference Between let and var Javascript"; // Error: let_vs_var is already declared

Javascript Let Example : 
let vision = 1;

if (vision === 1) {
  let vision = 2;

  console.log(vision);
  // output: 2
}

console.log(vision);
// output: 1
  

Now let see the scope example of Javascript let vs var.

var let_vs_var = 1;
var javascript_var = 2;
if (a === 1) {
var let_vs_var = 11; // the scope is global
let javascript_var = 22; // the scope is inside the if-block
console.log(let_vs_var); // 11
console.log(javascript_var); // 22
}
console.log(let_vs_var); // 11
console.log(javascript_var); // 2

Enjoy....!!!!

Feel free to comment below your experience with above approach and If you still find any problem  with above steps Let me know I would love to help you to resolve your  problem.

 If you want to take your Technological Knowledge to the Next Level and For More Technological information Stay tuned to Visionfortech

2 comments:

  1. var let_vs_var = 11; // the scope is global


    let javascript_var = 22; // the scope is inside the if-block

    Is it wrong statement?

    Isn't it should be like

    let let_vs_var = 11; // the scope is global


    var javascript_var = 22; // the scope is inside the if-block

    , the first variable as 'let' and 2nd as var.?

    ReplyDelete
    Replies
    1. No, let me clarify your doubt.
      We can use var for Global Variable Declaration and let for Local Variable Declaration.
      Hope i have answered your question.
      Please post your valuable feedback.

      Delete

Protected by Copyscape