JavaScript: Variables

Storing Single Values

1var a = 5
2console.log(a) // Prints: 5
3
4var b = 4.3
5console.log(b) // Prints: 4.3
6
7var c = "John"
8console.log(c) // Prints: "John"
9
10var d = true
11console.log(d) // Prints: true
12
13var e = false
14console.log(e) // Prints: false

Storing Expression Results

1var a = 5 + 3
2console.log(a)       // Prints: 8
3
4var b = 4.3 + 1.2
5console.log(b)       // Prints: 5.5
6
7var c = 4.3 + 1
8console.log(4.3 + 1) // Prints: 5.3
9
10var d = "John" + " " + "Doe"
11console.log(d)       // Prints: "John Doe"

One reason we might choose to store a value in a variable instead of just using it directly is that using a variable allows us to give the value a name and, in doing so, we get to explain what the value is, and why it matters for our program:

1var hoursPerWeek = 40
2var dollarsPerHour = 20
3
4var weeklyWage = (hoursPerWeek * dollarsPerHour)
5
6console.log(weeklyWage) // Prints: 800

Another reason we might choose to store a value in a variable instead of just using it directly, is that we might need to use the value in multiple places in our code. If we ever need to update the value to something else, we'll have to update it in multiple places instead of being able to just update the value in a single location within our code:

Version 1:

1console.log("I currently make $20 per hour.")
2console.log("It is nice making $20 per hour, but I would like to make more.")
3console.log("I can't wait to make way more than $20 per hour as a software developer!")

Version 2:

1var dollarsPerHour = "20"
2
3console.log("I currently make $" + dollarsPerHour + " per hour.")
4console.log("It is nice making $" + dollarsPerHour + " per hour, but I would like to make more.")
5console.log("I can't wait to make way more than $" + dollarsPerHour + " per hour as a software developer")

With Version 2, we can come back to this code and simply change the dollarsPerHour variable, and the behavior of the rest of the code will instantly update from that single change. Whereas, with Version 1, we have to change the value in 3 places