Variables - buckets of fun
Imagine for a moment your program is a bit like a child on a beach making a sandcastle. The child is going to need lots of raw materials to make that castle, sand, little shiny rocks, pebbles, flags, water from the sea. The child is going to need somewhere to keep all of those raw materials. He's going to need some buckets.
var greeting = "Hi there!";alert(greeting);
We have put the string "Hi there!" inside a variable (bucket) called greeting.
Changing the value of a variable
We can also change the value of a variable any time, just by assigning a new value to it, so we could write:
var namename = "Dave";alert(name);name = "Susan";alert(name);
The variable called name contains first the string "Dave", and then the string "Susan". Dave is now renamed Susan.
Variables are containers
Imagine I have a basket full of kittens, now when I hand you that basket, I'm actually handing you a big stack of kittens. This is probably a pleasant experience for you.
We can write this like this:
var basket = "kittens";
Now the basket can stand in wherever we previously needed kittens. For example, I could write:
or I could write
Either way I would alert some kittens.
Don't worry about giving your variables long and descriptive names. This is encouraged as it makes your code easy to read.
We can call our variables anything we like but it makes our lives easier if we give them sensible English names or common abbreviations.
The Var Keyword
Please note that when we first create a variable we must always remember to use the var keyword. If we forget it, bad things will happen. More on this when we get to Scope. For now, just remember to put them in.
Exercise: Thanks for all the fish
Variables are like little buckets in which we can store any information we like. Let's pop a string in one, and then pop it out in an alert box.
- Pop your farewell variable up in an alert box.
To answer this question, first we create a variable, lets call it greeting, and assign a value of "Thanks for all the fish" to it. The variable greeting is a bucket that contains the string. We can now use it in place of the string, and alert it.
var greeting = "Thanks for all the fish";alert(greeting);
Exercise: What's for dinner…
- Create a variable called question. Give it a value of "What's for dinner?"
- Create a variable called answer. Give it a value of "Fish"
- Add the two variables together and put the result in an alert box.
Variables are buckets. We can use variables in place of the things they represent, so:
var question = "What's for dinner?";var answer = "Fish";alert(question + answer);
If we'd like to improve the output slightly we can separate the two with a space:
alert(question + " " + answer);