Variables
- A variable is a “named storage” for data.
-
letkeyword-
let message; message = 'Hello!'; alert(message); // shows the variable content - To be concise, we can combine the variable declaration and assignment into a single line:
let message = 'Hello!'; // define the variable and assign the value alert(message); // Hello!
-
-
constkeyword- We use the
constkeyword to declare a constant (unchanging) variable. - They cannot be reassigned, and attempting to do so causes an error.
const myBirthday = '18.04.1982'; myBirthday = '01.01.2001'; // error, can't reassign the constant! -
Uppercase constants
- There is a widespread practice to use constants as aliases for difficult-to-remember values that are known prior to execution.
- Such constants are named using capital letters and underscores.
const COLOR_RED = "#F00"; const COLOR_GREEN = "#0F0"; const COLOR_BLUE = "#00F"; const COLOR_ORANGE = "#FF7F00"; // ...when we need to pick a color let color = COLOR_ORANGE; alert(color); // #FF7F00 - Capital-named constants are only used as aliases for “hard-coded” values (when the value is known prior to execution and directly written into the code).
- We use the
-
varkeyword- The
varkeyword is almost the same aslet. It also declares a variable, but in a slightly different, “old-school” way.
- The
-
Keyword summary
let– is a modern variable declaration.var– is an old-school variable declaration. It is rarely used.const– is likelet, but the value of the variable can’t be changed.
-
Some rules
- We can declare multiple variables in one line.
let user = 'John', age = 25, message = 'Hello'; - When a value of a variable is changed, the old data is removed from the variable.
- Copying data in variables:
let hello = 'Hello world!'; let message; // copy 'Hello world' from hello into message message = hello; // now two variables hold the same data alert(hello); // Hello world! alert(message); // Hello world! - Declaring a variable twice triggers an error. So, to change the data in a given variable, we should declare a variable once and then refer to it without
let.let message = "This"; // repeated 'let' leads to an error message = "That"; // That
- We can declare multiple variables in one line.
-
Variable Naming
- The name must contain only letters, digits, or the symbols
$and_. - The first character must not be a digit.
- Reserved words cannot be used as variable names.
- The name must contain only letters, digits, or the symbols
-
An assignment without
use strict- It is possible to create a variable by a mere assignment of the value without using
letif we putuse strictin the script, although it is not recommended.// note: no "use strict" in this example num = 5; // the variable "num" is created if it didn't exist alert(num); // 5"use strict"; num = 5; // error: num is not defined
- It is possible to create a variable by a mere assignment of the value without using