Use strict and let it not work as expected in Javascript

I have declared variables twice in my function while I am using "use strict". I know this function has global scope and variables are also treated as global with window scope ie window.car

But it shouldn't re-declare rate and capacity variables inside an if statement with a let data type. ("let" declares a local block-scope variable, optionally initializing it with a value.)

(function car() {
    "use strict";
    var speed = 100;
    const capacity = '1000CC';

    if(speed)  {
        let speed = 200;
        let capacity = '5000CC';
        console.log(speed,capacity);

    }
    console.log(speed,capacity);

})();

      

Please let me know what I am missing here.

+3


source to share


2 answers


"let" Declares a local block scope variable. But a global variable can be changed in the local scope.

(function car() {
    "use strict";
    var speed = 100;
    const capacity = '1000CC';

    if(speed)  {
        let speed = 200;
        let capacity = '5000CC';
        console.log(speed,capacity);//inside local it is modified to 200

    }
    console.log(speed,capacity);//outside scope it pull from global scope to 100

})();

      

You can re-declare / change global variables even in strict mode.




You will only get an error when you re-declare the same variable in the same scope. Take a look at the following example taken from MDN

if (x) {
  let foo;
  let foo; // TypeError thrown.
}

      

However, function bodies do not have this limitation! (But it throws a bug in ES6, but as @Bergi commented, there might be incorrect documentation on MDN)

function do_something() {
  let foo;
  let foo; // This works fine.
}

      

+3


source


A variable speed

declared with var

, and speed

declared with let

, are two different variables.



Within the body of the statement, the if

local declaration speed

hides the variable declared in the outer block β€” it does not update it.

0


source







All Articles