Variable Assignment
In programming, 'assignment' can be simply described as 'putting something into a box.'
Here, the box is called a 'variable', and the 'something' can be various types of data such as numbers or texts.
How to Assign?
In JavaScript (and most programming languages), you assign values using the =
symbol.
Example 1:
let fruit = 'Apple';
In the above code, we put the text (value) 'Apple' into a box (variable) called fruit
.
By using the =
symbol, we can assign the string value 'Apple' to the fruit
variable like this.
Example 2:
let age = 20;
Here, we put the numeric value 20 into the box called age
. In other words, we assigned the number 20 to the variable age
.
Is Multiple Assignment Possible?
Variables declared with var and let can be reassigned.
let color = 'Blue';
color = 'Red';
Initially, we put the value 'Blue' into the box called color
.
However, in the next line, we changed the value to 'Red'. As a result, the value of color
is now 'Red', and the previous 'Blue' value is discarded.
Points to Note
Variables created with const
cannot be changed once a value is assigned. This is referred to as 'non-reassignable'.
const birthYear = 2000;
birthYear = 2001; // Error occurs!
Summary
In summary, 'assignment' can be thought of as simply 'putting data into a box.'
Through assignment, you can store information in variables, and later use that information.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.