What a variable is
A closer look at variables
x = coffee
I like x
x tastes good with sugar in!
An example on how variables in general works and which most hopefully remembers from the math classes in school, is that you take some placeholder and let it refer to a value. In the example above the variable "x" is assigned the word "coffee". When then the text "I like x" is written you understand that it actually means "I like coffee", and that the last statement says "coffee tastes good with sugar in!".
// Some different ways of declaring variables
name = 'Bob';
age = 23;
var x = 73;
var a = 5, b = 7;
Variables are something that's called case sensitive. That means if you name them with big letters, they can't later be referred to with small letters. For example the variable text is not the same as Text, they are two different variables.
Assign values to variables
The value can later be manipulated and changed at free will, meaning if 44 is later assigned to x its value will be 44. The statement "x = x + 1" will increment x with one so its value gets changed to 45.
var x = 76;
document.write(x); // 76
x = 44;
document.write(x); // 44
x = x + 1;
document.write(x); // 45
That was numbers. What about text?
var str = 'This is a string';
var str2 = "This is another string";
To use quotes inside strings is pretty easy. Double quotes can be used inside strings declared with single quotes, and single quotes inside strings with double quotes. Otherwise they must be escaped with a backslash, for example like this: var s = "Hello \"mr\" Bob";
Variables are not bound to any specific data types like in many other languages. Instead if you have a variable with the value 33 which is a number. It can later be changed to for example a string like "Hello" without any problems.
When working with strings you often want to combine more than one of them into a single big string, and perhaps add some variables into it. For this the addition operator (+) is used, and it's called to concatenate strings.
var city = 'Stockholm';
var city2 = 'Gothenburg';
var text = city + ' and ' city2 + ' are 2 cities';
// Stockholm and Gothenburg are 2 cities
var hour = 3;
var minute = 40;
document.write('The clock is ' + hour + ':' + minute + ' am');
// The clock is 3:40 am
Try it yourself
- Declare some different variables and assign strings, numbers or anything to them.
- Concatenate together some different strings.