Variable Assignment
In programming, 'assignment' simply means 'putting something into a box.'
Here, the 'box' is what we call a 'variable', and the 'something' can be various types of data like numbers, characters, etc.
How do we assign?
In JavaScript (and most programming languages), we use the =
symbol to assign values.
Example 1:
let fruit = 'apple';
In the code above, we put the string 'apple' into the box (variable) named fruit
.
We can use the =
symbol to assign the string value 'apple' to the variable fruit
.
Example 2:
let age = 20;
Here, we put the numeric value 20 into the box named age
. In other words, we assigned the number 20 to the variable age
.
Can we assign multiple times?
Variables declared with var and let can be reassigned.
let color = 'blue';
color = 'red';
Initially, we put the value 'blue' into the box named color
.
But in the next line, we put the value 'red' into the box. After this reassignment, the value of color
becomes 'red', and the old value 'blue' is discarded.
Points to Note
Once a value is assigned to a variable declared with const
, it cannot be changed. This means 'reassignment is not allowed.'
const birthYear = 2000;
birthYear = 2001; // Error occurs!
Summary
Think of 'assignment' as simply 'putting data into a box.'
Assignment allows you to store information in variables and use that information later on.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.