-2

I am new to JS and i have facing some issue on declaration of the Variables in three ways

These are test cases i have tried

as my understanding

a = "a";

and

var a = "var a";

are (global declaration) same thing

but

let a = "let a"

is declare as local variable

so as i have tested some combinations

let a ="let a"
a ="a"

workes

but

let a = "let a"
var a = "var a"

not works

could you tell me why is that ?

  • You can't declare an identifier more than once. (When you don't use `let` or `var`, you're assigning to the global object) – CertainPerformance Apr 18 '19 at 10:20
  • `var` is function scope, `let` and `const` a block scope declarations. And you can't declare a variable twice in the same scope. – t.niese Apr 18 '19 at 10:22
  • At the top level of programs and functions, `let`, unlike `var`, **does not create a property on the global object**. See: [let documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) – dNitro Apr 18 '19 at 10:22
  • 1
    Don't waste your time with archeology, just make a habit to always use `let` and strict mode and forget about other ways. – georg Apr 18 '19 at 10:29

2 Answers2

0

var is function scope, let and const a block scope declarations. And you can't declare a variable twice in the same scope (that's not completely true, because you can have two var a in the same scope due to backwards compatibility).

So it depends on where you write your last example:

function foo() {
  let a = "let a"
  var a = "var a"
}

fails because both let a and var a define the a in the same scope.

function test() {
  if (true) {
    let a = "let a"
    var a = "var a"
  }
}

Would work because they are defined in different scopes, as this would be equal to write:

function test() {
  var a
  if (true) {
    let a = "let a"
    a = "var a"
  }
}
t.niese
  • 39,256
  • 9
  • 74
  • 101
-1

You should read up more on different types of variable declarations on javascript from here. Basically the difference is: 1. var declarations are globally scoped or function/locally scoped. var variables can be re-declared and updated. 2. let is block scoped. let variables can be updated but not re-declared.

So to answer your question:

let a ="let a" 
a ="a" // This works as you are reassigning the let variable, not redeclaring it.

let a = "let a";
var a = "a"; // This won't work as you are redeclaring the variable.
Dblaze47
  • 868
  • 5
  • 17