Javascript Guide - Variables
You can now also navigate the guide through the table of contents.
What are variables?
Simply put, variables are a way with which we store data.
Variable Assignment
The most basic way of doing this is:
var a = 1;
console.log(a);//1
There are 4 parts to this little piece of code, each very important:
- The
varkeyword lets the interpreter (the machine running our code) know that we are declaring a variable in thecurrent scope. The concept ofscopesis quite complex, and we are going to save this for the end. For now, we will always use the var keyword when creating a variable. - The variable name - in our case
a. - A single equal sign followed by a value: 1. The single-equal sign is the assignment operator.
- Another thing that isn't really related to assignment but still very important - notice that each line ends with a
;. This will let the interpreter know that we ended the current statement. Although the JS interpreter is usually very forgiving, and does not force you to use semicolons, always use them when ending a statement.
This has placed the value 1 inside of a. From now on, from every part of our program (at least in this case, as it is in the global scope. As mentioned before, we will address scopes later on in the series), we will have access to the variable a, that, at least for now, will hold the value of 1.
We can also change that value:
var a = 1;
a = 2;
console.log(a);//2
We can declare as many variables as we would like, separated by ,. For example:
var a=1, b=2, c=3;
console.log(a);//1
console.log(b);//2
console.log(c);//3
Variable types
There are many types of data we can put into a variable. The most common are:
- Boolean
-
The boolean type can hold only 2 types of values:
trueandfalse. Both of these are reserved keywords, that can also be represented as 1 (true) and 0 (false).var a=true, b= false; console.log(a);//true console.log(b);//falserun code - Number
Any numeric value, that is not surrounded by quotes (like the ones we used on our previous examples).
- String
-
A string is a "words variable". It contains a list of characters. The word
stringcomes for older, more basic programing languages, where this kind of type was not trivial, but for us, using strings will be so natural that we won't even notice it.Strings are recognizable through the quote signs, be it single-quote (') or double-quote (") from both sides of our "sentence".
var str1 = 'this is a single quoted string' , str2 = "this is a double quoted string"; console.log(str1);//this is a single quoted string console.log(str2);//this is a double quoted stringrun code - Array
-
The
Arrayis a list of other variables, indexed by their numeric location, starting with 0. OK, so this was maybe a bit confusing, so let's break it up.The Array is identified with the
[and]signs. Within them, we will find a comma-separated list of values. These values can be of any type we want.var arr = [true,12,'abc',false]; console.log(arr);//[true,12,'abc',false]run code In order to access the variables in the list, we use the [] signs, with the numeric location of the value we want to access. The first item in the array is indexed with 0. The best way to illustrate this is with this example:
var arr = [true,12,'abc',false]; console.log('index 0',arr[0]);//true console.log('index 1',arr[1]);//12 console.log('index 2',arr[2]);//'abc' console.log('index 3',arr[3]);//falserun this code A note - we can use this syntax to assign values to the array's items -
arr[2]='abc';.This is just the tip of the iceberg, but I will add 3 more operations we can perform on an array:
push,pop,shift:-
Push
This will push a value to the end of the array.
var arr = ['a','b']; arr.push('c'); console.log(arr);//['a','b','c']run code Now, here we see some other aspect of JS that we haven't met yet - notice how I use the dot-notation to call an operation on the Array. This is a hint to one of the most important aspects of JS - everything in javascript is an
object. This doesn't mean much to you, but as we go along I hope it will. -
Pop
This will take out the last item in the array, returning it. Both
popandshiftare ways for us to handle our array as though it as a stack.var arr = ['a','b','c']; arr.pop(); console.log(arr); //['a','b'] var item = arr.pop(); console.log('array',arr); //array ['a'] console.log('item',item);//item brun code Notice that each time we
popthe array, that item no longer exists in the array. -
Shift
This one has the same behavior as
pop, only it operates on the first item in the array.var arr = ['a','b'] , item = arr.shift(); console.log(arr); //['b'] console.log(item);//arun code
-
- Object Literal
-
This one behaves very much like an Array, and in fact, most array methods can be used with the object literal. The key difference between the 2 is that while the Array was using numeric indexes, the Object Literal can receive strings as it's key.
Another important aspect of the object literal is that although we can use
[ ]to access it's variables, we can also use the dot-notation. The way we declare Object Literals is by using curly-braces - { }. Within it, are comma-separated key-value pairs, joined with:. Now again - this was a bit confusing so lets use an example to simplify it:var obj = { 'a' : 'a' , 'b' : 'b' }; console.log(obj); //Object{a='a',b='b'} console.log(obj.a); //a console.log(obj.b); //brun code A few notes -
- Although we should always use strings for keys, we can also omit the quotes, and it will still be valid. so
var a = {a:'a'};will run just fine. - The values on the other hand, can be anything that we want, from numbers to other object literals.
- We can use the dot notation to assign values to our object's items -
obj.a='abc', or we can use the array syntax -obj['a']='abc';. The 2nd is very important for when we would like to create dynamic calls to our object. But more on that later.
Just a final note - why we call them Object literals and not simply Objects. Well, in short, as I said before, everything in JS is an Object. The main symptom you will notice is that all types (except boolean) can be used with the dot-notation to call special operations assigned to them (called methods). The name Literal means that we create an Object that is not a subset of another type family.
- Although we should always use strings for keys, we can also omit the quotes, and it will still be valid. so
- Undefined, null, NaN
-
These are special values in javascript, each with he's own behavior and rules:
-
undefinedThe default value of all our variables is
undefined. When we create a variable without assigning it any value, it will beundefined.var a; console.log(a);//undefinedrun code -
nullThis is a standard way in all programing languages for an empty value. As a rule of thumb, when we want to empty a variable without deleting it, or to define our variable as empty explicitly, we should use
null. There are a few reasons for this, but I won't go into them now.var a = null; console.log(a);//nullrun code -
NaN
This is by far the most annoying type in JS. Whenever an illegal arithmetic operation occurs, like, for example, trying to subtract a number from undefined,
NaNwill be returns.NaNstands for Not a Number. The reason it is so annoying, is that you can never check if a value is NaN, except by eliminating all other possibilities. The only way I can demonstrate this is by using an operator we haven't yet learned about - the comparison operator -==, which checks if 2 values are equal:var a , b = 1/ a , c = 1/ a; console.log(b);//NaN console.log(c);//NaN console.log(b==c);//falserun code
-
Now, there are a few other native types in javascript, and there are a few others that comes with the client side version. The most important of all is the Function, which we will talk about in detail in another post.
Next post - operators.