Declaring and Using Variables

Assigning Values To Variables

🙋 Need help? Ask an expert now!

Assigning values to variables is achieved by the = operator. The = operator has a variable identifier on the left and a value on the right (of any value type). Assigning is done from right to left, so a statement like var sum = 5 + 3; will assign 8 to the variable sum. As mentioned previously, variables declared with the const keyword cannot be reassigned after their initial assignment.

As shown in the sample program above, there are many different methods you can use to assign values to variables. The first example with firstValue is the most common method where you directly assign a value to the variable. A variable can be used as a value when initializing a different variable, as shown with secondValue. The thirdValue is assigned by chaining firstValue and the number 3, which is one way of assigning the same values to different variables. However, this method is not recommended as it may create unwanted errors in your program.

Edit Me on GitHub!

Application Question

Which of the following statements assigns the value of varOne to the value of varTwo?