0

I modified the original script from the MDN website given below.

  1. What is the type of var? Is the type assigned only after a value is assigned to a variable.

  2. Does var b = 1 overwrite the previous statement var b = 10? Or just the variable b?

  3. Is let a non-standard language feature? I read here that it is supported in ECMAScript 6.

var a = 5;
var b = 10;

if (a === 5) {
  let a = 4; // The scope is inside the if-block
  var b = 1; // The scope is inside the function

  alert(a);  // 4
  alert(b);  // 1
} 

alert(a); // 5
alert(b); // 1
thor
  • 21,418
  • 31
  • 87
  • 173
wonderful world
  • 10,969
  • 20
  • 97
  • 194

2 Answers2

1
  1. Yes, var x has no type. var x = 1 has a type of number.
  2. var b doesn't overwrite the other statement, it just sets a new variable for the given scope. It means within that scope you get the newly assigned value for b.
  3. let is es6. So yes and no, depending on where your code is running.
Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40
1

What is the type of var?

var has no type. It's a keyword used to declare variables.

Is the type assigned only after a value is assigned to a variable?

When you declare a variable but don't assign any value to it, its value will be undefined, whose type is Undefined.

Does var b = 1 overwrite the previous statement var b = 10? Or just the variable b?

Variable statements are hoisted to the top. That means that those are equivalent:

// ...
var b = 10;
if(cond) var b = 1;
var b;
// ...
b = 10;
if(cond) b = 1;

So, since b was already declared, var b = 1 will be equivalent to b = 1.

Is let a non-standard language feature? I read here that it is supported in ECMAScript 6.

let was introduced in JavaScript 1.7, and was not part of any ECMA-262 standard at the time.

Now ECMAScript 6 has standardized it (in a bit different way than JS 1.7). However, be aware that ECMAScript 6 is still a draft.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • According to the MDN, let is being deprecated and being removed in the future. I would advise against using it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – Norman Breau Apr 18 '15 at 18:07
  • Only [non-standard let extensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Non-standard_let_extensions) ([let block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_block) and [let expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#let_expressions)) will be removed. – Oriol Apr 18 '15 at 18:10