JavaScript: Variables
What are variables?
We use variables to store data values. For example, we can use variables to store a user’s email address or name. In JavaScript, a variable can contain any type of data, such as a string, a true or false boolean, an object, or a number.
Variable Declaration
The variable declaration means creating a variable.
There are 3 ways to declare a variable, using keywords:
// var (a.k.a. VARIABLE)
var name;
// let
let age;
// const (a.k.a. CONSTANT)
const isMale;
Variable Assignment
Variable assignment means assigning a value to the variable you declared.
We use the =
symbol to do a variable assignment.
// 1. Declaring variables.
var name;
let age;
// 2. Assign values to the variables we declared.
name = 'Yap';
age = 20;
Notice we didn't show an example of using const
. This is because const
has a
different way of using it. We will show this in the
next section.
Variable Initialization
Variable initialization means we declare and assign the value at the same time.
var name = 'Yap';
let age = 20;
const isMale = true; // this is how you use `const`
To understand more why we can't declare and assign separately with const
.
Continue on reading...
Variable Reassignment
Variable reassignment means we change the value of a variable to something else.
But, we can't reassign if the variable is declared by using const
. Because
const
means constant (a.k.a. value that doesn't change). Hence, we can only
initialize a const
variable because it cannot do an assignment.
var name = 'Yap';
console.log(name); // output: Yap
name = 'Kaiz';
console.log(name); // output: Kaiz (changed!)
let age = 20;
console.log(age); // output: 20
age = 30;
console.log(age); // output: 30 (changed!)
const isMale = true;
console.log(isMale); // output: true
isMale = false; // TypeError: Assignment to constant variable.
Did you find this article valuable?
Support Yap Yee Qiang by becoming a sponsor. Any amount is appreciated!