Table of contents
What is a variable?
You can use a variable to make several references to the same piece of data. Variables are defined in JavaScript using the var
keyword.
Variable declaration
var variableName = value;
EXAMPLE
var name = "Zoe";
var postLiked = "false";
Variables can be declared with no value and then with a value. Variables can also be assigned to more variables.
Variable scoping
Scope determines the usage of a variable. There are 3 types of scope:
- Global scope: This scope can be used throughout the whole code. The global scope uses
var
.
EXAMPLE
var myGlobalNumber = 6;
- Local scope: This scope can only be used in the declared location of the code. The local scope uses
let
.
EXAMPLE
let myLocalNumber = 12;
- Constant: This scope is similar to the local scope. It cannot be used outside the location. The constant uses
const
.
EXAMPLE
const myConstantNumber = 24;
DIFFERENCES
var | let | const |
Can be redeclared and updated | Can be redeclared, but not updated | Cannot be redeclared and updated |
Hoisted at the top and initialized | Hoisted at the top, but not initialized | Hoisted at the top, but not initialized |
Global scoped | Block scoped | Block scoped |
Summary
You can use a variable to make several references to the same piece of data. There are 3 types of scopes: global scope(var
), local scope(let
) and constant scope(const
).