Asked 7 years ago
17 Jan 2017
Views 1701
lain

lain posted

difference between var statement and let statement in JavaScript ?

what is the difference between var statement and let statement in JavaScript ?

var var_name='arrayoverflow';
let let_name ='arrayoverflow';
console.log(var_name);//arrayoverflow
console.log(let_name);//arrayoverflow


both seems to work same. both , var and let statement define the variable and work same so what is the difference between var statement and let statement in JavaScript ?


var VS let
list all pros and cons also so i can use both with wise
yogi

yogi
answered Nov 30 '-1 00:00

var statement means global declaration

let statement means scope declaration


function varTest() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable!
    console.log(x);  // 2
  }
  console.log(x);  // 2
}
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}


if you see above code var statement is work like global variable , and let define scope variable it means each scope "{ }" have differ variable with same name
Rasi

Rasi
answered Nov 30 '-1 00:00

redeclaration problem with let statement


let name='array';
let name='overflow';

with let statement you cant re declare same variables .
above code will throw SyntaxError ;
SyntaxError: redeclaration of let name


var name='array';
var name='overflow';


but with var statement work with unlimited re initialization and you can change variable value by re-declaration anytime.

big difference between var statement and let statement ::
var statement allow to re-declare variable and let statement not allow that . it throw syntax error , let statement variable is like constant once defined no re-declaration
Post Answer