Declare Variables
- You can also declare multiple variables in one line:
let user = 'John',
age = 25,
message = 'Hello';
- In older scripts, you may also find another keyword:
var
instead of let
.
- When the name contains multiple words, camelCase is commonly used.
- Number cannot be used as the first character.
- The dollar sign
'$'
and the underscore '_'
can also be used in names, even as the first character.
- Normally, we need to define a variable before using it.
- But traditionally, it was technically possible to create a variable by a mere assignment of the value without using let.
- This still works now if we don’t put
use strict
in our scripts to maintain compatibility with old scripts.
// Note: no "use strict" in this example
num = 5; // the variable "num" is created if it didn't exist
alert(num); // 5
- This is a bad practice and would cause an error in strict mode:
"use strict";
num = 5; // error: num is not defined
var
Differences
var
has no block scope and therefore, var
variables are either function-wide or global, they are visible through blocks.
var
basically ignores the code blocks, so we get a global variable.
if (true) {
var test = true; // use "var" instead of "let"
}
alert(test); // true
for (var i = 0; i < 10; i++) {
// ...
}
alert(i); // 10, "i" is visible after loop, it's a global variable
- If a code block is inside a function, then var becomes a function-level variable:
function sayHi() {
if (true) {
var phrase = "Hello";
}
alert(phrase); // works
}
sayHi();
alert(phrase); // Error: phrase is not defined
Hoisting
var
variables are defined from the beginning of the function, no matter where the definition is (assuming that the definition is not in the nested function).
- So this code:
function sayHi() {
phrase = "Hello";
alert(phrase);
var phrase;
}
- Is technically parses this way: