Variable declaration
Variables in JavaScript can be declared in two ways. By using the keywords of “var” or “let”.
var syntax:
var monkey;
Let syntax:
let vendingMachine;
Var is the older way to declare a variable, while let is a newer way. It is recommended to utilize let in modern JavaScript programming, but you will still run into var in various programs. It is important to understand what it does.
Why is let considered to be better than var? The answer is in scope and encapsulation. We will get into scope and how it is used in JavaScript later, but a rudimentary look is prudent here. When the var keyword is used, depending on how and where it is used, the variable and its contents could be available to parts of the program that should not be accessing it. If var is used to declare a variable inside a function, it is available to that function. If it is declared outside the function, it is global. Var is considered to be function-scoped.
By using let, the variable is scoped properly to protect any adverse effects occurring in your program. Let limits access to the variable within the block where it is defined. In JavaScript, a block is defined by curly braces {}. Let is block-scoped.
There is a third way to define a container in JavaScript…const. The const keyword stands for constant. Const is also block-scoped. The difference between const and let is that const variable values cannot be reassigned. Note that they can be mutated. NEED PAGE discussing mutability
Const syntax:
const dingo;
We will cover scoping (function and block) later. The bottom-line is that you should use “let” and “const” as much as possible.
Note: Multiple variables can be declared in a single statement. Instead of…
let oneLet;
let twoLet;
let threeLet;
The following can be written…
let oneLet, twoLet, threeLet;
Happy Coding!
Clay Hess