A variable is a named storage for data. We can use variables to store goodies, visitors, and other data.
Naming Variables
- Variable names must start with a letter, an underscore (
_
) or a dollar sign ($
). - Variable names cannot contain spaces.
- Variables cannot be the same as reserved keywords such as
if
orconst
. - By convention, JavaScript variable names are written in camelCase.
- Variables should be given descriptive names that indicate their content and usage.
- As JavaScript variables do not have set types, it can be useful to include an indication of the type in the name.
Ex:
1 2 3 4 5 6 7 8 9 | // Valid variable var $_$ = "money eyes"; var _Hello_ = "what a nice greeting"; var I_AM_HUNGRY = true; //Invaild variable var 2fast2catch = "bold claim"; var function = false; var class = "easy"; |
Declaring Variable
JavaScript is a dynamically typed language so the type of variables is decided at runtime. Therefore there is no need to explicitly define the type of a variable. We can declare variables in JavaScript in 4 ways:
- Automatically
- Using
var
- Using
let
- Using
const
Automatically
Ex:
1 2 3 4 5 | x = "Wrapline.pro"; y = 6; console.log(x); console.log(y); |
Output:
1 2 | Wrapline.pro 6 |
Using var
var
statement is used to declare variables in JavaScript that are function-scoped. The var
statement is also used to declare global-scope variables.
Ex:
1 2 3 4 5 6 7 8 9 | var a = "Hello Wrapline" var b = 10; var c = 12; var d = b + c; console.log(a); console.log(b); console.log(c); console.log(d); |
Output:
1 2 3 4 | Hello Wrapline 10 12 22 |
Using let
let is a keyword used to declare variables that are block-scoped. Variables defined with the let keyword cannot be redeclared and must be declared before use.
Ex:
1 2 3 4 5 6 7 8 | { let num = 10; // calling the function inside block console.log(num) } // calling the function outside // block throws a Error console.log(num) |
Output:
1 2 | 10 Uncaught ReferenceError: num is not defined |
The num variable is block-scoped and it cannot be accessed outside the block. If we try to access the variable outside the block it throws a reference error.
Using const
Variables specified using const cannot be redeclared and have block-scope.
1 2 3 | const x = 12; x = 13; x += 1; |
Output:
1 | Uncaught TypeError: Assignment to constant variable. |
Comparison of properties of let, var, and const
Property | var | let | const |
---|---|---|---|
Scope | Function scoped | Block scoped | Block scoped |
Updation | Mutable | Mutable | Immutable |
Redeclaration | Can be redeclared | Cannot be redeclared | Cannot be redeclared |
Hoisting | Hoisted at top | Hoisted at top | Hoisted at top |