Hello,
If I create a new variable, I ‘m going to write
let thing = 5;
for example.
But if I write
thing = 5;
(while I haven’t already created a variable ‘thing’)
that works too!
is there a difference?
Hello,
If I create a new variable, I ‘m going to write
let thing = 5;
for example.
But if I write
thing = 5;
(while I haven’t already created a variable ‘thing’)
that works too!
is there a difference?
That behavior is nicknamed “sloppy mode”:
In order to activate “strict mode”, place "use strict";
as the 1st non-comment statement in a JS file.
We can also activate “strict mode” by loading a JS file as an “ECMA script module (ESM)”.
Thank you…
so, I answer my question (if I understood correctly!):
If I write in a method (or function)
let thing=3;
then thing is local to the method
but if I write
thing=3
then thing is global
it’s silly!
… so I absolutely have to (re)put ‘let’ everywhere!
Prior to ES6 variables in JS only had Global Scope or Function Scope. ES6 introduced the Block Scope with two new keywords let
and const
. A block is defined by curly braces { }
.
This code has three blocks -
function foo() { // Block 1
let a = 9;
if(a != a) { // Block 2
let b = 3;
}
else { // Block 3
let c = 5;
}
}
Variable b
is only visible in block 2
Variable c
is only visible in block 3
Variable ‘a’ is visible in all three blocks because blocks 2
and 3
are inside the scope of block 1
Whether you use let
and const
is up to you but I wouldn’t call it silly because their introduction is to help users create stable programs.
Using global variables should be avoided as it can introduce logic errors by accidentally changing values in global variables in some far distant part of the program simply due to a mistyped variable name. Logic errors are by far the hardest to find and fix.
Strict mode takes this a step further by requiring variables be declared before assignment
let x; // declaration
x = 999;` // assignment
These require more work from the programmer but if you are creating software of any significant size or longevity it is well worth the effort.
My advice is to always place a "use strict";
at the top of each .js non-module file and to prioritize keyword const
over let
or var
when declaring variables as much as possible.