Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial38 var
vs
let
In modern JavaScript, variables are typically declared with
let
. Using the previous example, all of the var
declarations can be replaced with let and the example would run exactly
the same:
function add() {
let result = opr1 + opr2;
return result;
}
let opr1 = 2;
let opr2 = 3;
let sum = add(); // sum = 5
The reason for var
vs. let
in modern
JavaScript is because var
does not have block scope.
Variables declared with var
are not visible outside of
functions, but they are visible inside if-then
blocks,
switch
blocks, etc. Declaring variables with let ensures
they are not visible outside of their own scope. However, Scripter’s
Javascript ignores this convention of modern JavaScript. Both
var
and let
create block-scoped variables.
There are a couple more key differences between the two declarations that Scripter does not ignore. These are more a matter of style than anything, but they would be considered bad practice in most cases.
A variable declared with var
can be redeclared multiple
times in the same scope.
var pitch = 60;
var pitch = 72;
Trace(pitch); // 72
Scripter has no problem with pitch being re-declared in line 2.
let pitch = 60;
let pitch = 72;
Trace(pitch); // Cannot declare a let variable twice: 'pitch'.
Scripter highlights line 2 as an error and will not run the script.
A variable declared with var
can be declared before its
first use.
= 60;
pitch Trace(pitch); // 60
var pitch;
Scripter has no problem with the variable being declared in line 3.
= 60;
pitch Trace(pitch); // Cannot access uninitialized variable. line:1
let pitch;
Scripter will not run the script with let declaring the variable, but it does not highlight the line as an error; the error will only be revealed during runtime.
Any variable first declared without var
or
let
is handled as being declared with var
.
Both of these examples work:
= 60;
pitch = 72;
pitch Trace(pitch); // 72
= 60;
pitch = 72;
pitch Trace(pitch); // 72
The variable pitch
was never explicitly declared with
var
or let
, but because the variable was
successfully assigned a new value the variable is being handled as
var
.
= 60;
pitch let pitch = 72;
Trace(pitch); // Cannot access uninitialized variable. line:1
This example does not work because of the let
declaration, which cannot be accessed after the variable’s initial
use.