A variable is a “named storage” for data. We can use variables to store goodies, visitors and other data.
To create a variable in JavaScript, we need to use the let
keyword.
The statement below creates (in other words: declares or defines) a variable with the name “message”:
let message;
Now we can put some data into it by using the assignment operator =
:
let message; message = 'Hello'; // store the string
The string is now saved into the memory area associated with the variable. We can access it using the variable name:
let message; message = 'Hello!'; alert(message); // shows the variable contents
To be concise we can merge the variable declaration and assignment into a single line:
let message = 'Hello!'; // define the variable and assign the value alert(message); // Hello!
We 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:
var message = 'Hello';
The var
keyword is almost the same as let
. It also declares a variable, but in a slightly different, “old-school” fashion. Let's discuss the difference between var
and let
.
var
variables are either function-wide or global, they are visible through blocks. It means if you declare a variable inside a block using the keyword var
, the variable is accessible from outside of the block.
if (true) { var test = true; // use "var" instead of "let" } alert(test); // true, the variable lives after if
The same thing happens for the loop too -
for (var i = 0; i < 10; i++) { // ... } alert(i); // 10, "i" is visible after loop, it's a global variable
Another difference is that 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
...But if you declare a variable inside a function block (outside any other block within the function), it is also available outside of the function -
function sayHi(name1){ var name = name1; } sayHi("Santanu Bera"); name = "Hi"; console.log(name); // Hi
This mechanisam can be explained in a simple way. When Javascript starts executing file, first it looks for all the function definition and variables defined using var
. Then it starts executing the file. That's why no matter where you define your variable doesn't matter at all. All the var
declaration happens before execution of the file, and that's why var
variables are available before even the execution starts. Using this concept you can even define a variable even after using it -
function sayHi() { phrase = "Hello"; alert(phrase); var phrase; }
Even the following is not an error -
function sayHi() { phrase = "Hello"; // (*) if (false) { var phrase; } alert(phrase); }
People also call such behavior “hoisting” (raising), because all var are “hoisted” (raised) to the top of the function.
Declarations are hoisted, but assignments are not.
function sayHi() { alert(phrase); var phrase = "Hello"; } sayHi();
The line var phrase = "Hello"
has two actions in it:
var
=
.The declaration is processed at the start of function execution (“hoisted”), but the assignment always works at the place where it appears. So the code works essentially like this:
function sayHi() { var phrase; // declaration works at the start... alert(phrase); // undefined phrase = "Hello"; // ...assignment - when the execution reaches it. } sayHi();
Because all var
declarations are processed at the function start, we can reference them at any place. But variables are undefined
until the assignments. In both examples above alert
runs without an error, because the variable phrase exists. But its value is not yet assigned, so it shows undefined
.
There are two limitations for a variable name in JavaScript:
The following are valid -
let userName; let test123;
When the name contains multiple words, camelCase
is commonly used. That is: words go one after another, each word starts with a capital letter: myVeryLongName
.
What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.
The following variable names are valid -
let $ = 1; // declared a variable with the name "$" let _ = 2; // and now a variable with the name "_" alert($ + _); // 3
Examples of incorrect variable names:
let 1a; // cannot start with a digit let my-name; // a hyphen '-' is not allowed in the name
Variables named apple and AppLE – are two different variables.
There is a list of reserved words, which cannot be used as variable names, because they are used by the language itself. For example, words let
, class
, return
, function
are reserved.
let let = 5; // can't name a variable "let", error! let return = 5; // also can't name it "return", error!
use strict
Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value, without let
. This still works now if we don’t put use strict
. The behavior is kept for compatibility with old scripts.
// note: no "use strict" in this example num = 5; // the variable "num" is created if didn't exist alert(num); // 5
That’s a bad practice, it gives an error in the strict mode:
"use strict"; num = 5; // error: num is not defined
To declare a constant (unchanging) variable, one can use const
instead of let
:
const myBirthday = '18.04.1982';
Variables declared using const
are called “constants”. They cannot be changed. An attempt to do it would cause an error:
const myBirthday = '18.04.1982'; myBirthday = '01.01.2001'; // error, can't reassign the constant!
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