Now that we've learned about variables, let's see why they are so important in our prgrammers' life:
Consider this simple program wich prints a story:
println("My name is John and I am 40 years old")
println("Coding at age 40 is really fun")
println("My son is named after me, John")
println("I'd love him to be as cool as me at age 40")
println("It's so funny when my wife calls John we both respond")
Changing the story:
This is a perfectly working program. But what if I come back to it and want to change the character's name to Andy and his age to 32?
Well, I'm going to have to go through the entire program and manually change the name John to the name Andy and the age 40 to the age 32:
println("My name is Andy and I am 32 years old")
println("Coding at age 32 is really fun")
println("My son is named after me, Andy")
println("I'd love him to be as cool as me at age 32")
println("It's so funny when my wife calls Andy, we both respond")
This is not horrible as I had to go through only 5 lines of code. But what if my code consisted of hundreds of lines?
It's a disaster. Going through the whole code and manually changing the name and age is boring but more importantly it's super easy to make mistakes.
The story with variables:
This is where variables shine. If I used a variable to store the name of the character and another variable to store his age when I first wrote this code, it would have looked like this:
var name = "John"
var age = 40
println("My name is " + name + " and I am " + age + " years old")
println("Coding at age " + age + " is really fun")
println("My son is named after me, " + name)
println("I'd love him to be as cool as me at age " + age)
println("It's so funny when my wife calls " + name + " we both respond")
Changing the story with variables:
Now whenever I want to change the character's name and age, I only have to change two lines of code, instead of possibly hundreds.
If I want my character to be named Andy and aged 32, I initialize the variables name with Andy and age with 32 and leave the rest of the code untouched:
var name = "Andy"
var age = 32
println("My name is " + name + " and I am " + age + " years old")
println("Coding at age " + age + " is really fun")
println("My son is named after me, " + name)
println("I'd love him to be as cool as me at age " + age)
println("It's so funny when my wife calls " + name + " we both respond")
Assignment
Follow the Coding Tutorial and let's witness the power of variables!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.