JavaScript basics¶
JavaScript is a programming language just like Ruby - in fact, they are quite similar, so having some knowledge of one will help a lot in understanding the other. There are a lot of differences, but the most basic principles are the same, as they are in many other programming languages.
Variables, types and assignment¶
Variables in JavaScript are assigned to using the var keyword:
1 var myString = "Hello World!";
Note: If you leave out the
varkeyword it will probably seem to work anyway, but this is not recommended as the variable will be made "global", which is a bad thing.
A variable can contain any type of object you throw at it. There are a number of basic object types in JavaScript:
Numbers¶
The "number" type in JavaScript includes both integers and decimals:
1 var meaningOfLife = 42;
2 var pi = 3.14159265359,
3 e = 2.71828;
4 meaningOfLife = pi+e;
Note: You can assign to more than one variable at once by separating the assignments with a comma. This is also possible when declaring variables using the
var keyword, like we do withpiandeabove.
Note: When re-assigning a variable that has already been declared using the
varkeyword, there's no need to declare it again, thus we leave out thevarwhen assigning tomeaningOfLifethe second time in the example above.
Strings¶
Strings are objects that contain text, you can create strings using either double or single quotes. There's no difference between the two.
1 var greeting = "Hello world";
2 var foo = 'bar';
Arrays¶
Arrays are lists that contain other objects such as strings, numbers and functions:
1 var listOfThings = [12, 45.234, "Search out the door of Namtara"];
Arrays are ordered, and to access a specific item in the array we refer to it by its index, which is the item's position in the list, starting at zero:
1 listOfThings[0]; //Gives us 12
2 listOfThings[2]; //"Search out the door of Namtara"
Note: You can add comments to your JavaScript code by prefixing it with two forward slashes (//). The web browser will ignore everything after that's on the same line. If you need to add a comment that spans multiple lines, put it between /* and */:1 /* This comment spans 2 multiple lines */
We can also assign an object to a specific position in the array using the index:
1 listOfThings[3] = "Bring a baked loaf into his presence";
And you can add or remove items at the beginning or end of the array using the methods shift, pop, unshift and push:
1 listOfThings.shift(); //Removes the first item
2 listOfThings.pop(); //Removes the last item
3 listOfThings.unshift("I'm the first item now");
4 listOfThings.push("And I'm the last item");
Objects¶
Objects in JavaScript are quite simple. An object is a "thing" which can have many attributes. Those attributes, much like variables, can contain other objects. Object properties have names just like variables, and to assign something to an object's property we use the dot notation:
1 var myObject = {};
2 myObject.myProperty = "Hello, I'm a string, and I'm the property of myObject";
As you can see, we don't use the var keyword when assigning properties on an object. You may have also noticed some new syntax on the first line where we're creating our object - this is called an object literal and we just created the simplest object possible which is one without any properties. The object literal is quite a useful construct, as we can create objects on the fly and add properties to them at the same time:
1 var deity = {firstName: "Ahura", lastName: "Mazda", title: "Uncreated creator of all"};
2
3 deity.lastName; // "Mazda"
4 deity.good = true; // We can keep adding properties
Note: Everything in a program can be said to be ("evaluate to") either true or false, yes or no. The special variables
trueandfalserepresent this concept at its most basic.
Functions and methods¶
Functions are bits of code that you can execute at a later point. They can also be executed as many times as you wish:
1 function greet(){
2 alert("Hello World!");
3 };
4
5 //Will display "Hello world" 3 times
6 greet();
7 greet();
8 greet();
Note: Functions are only executed when you add () to the end. Note: As you've probably noticed, we end every statement in JavaScript using a semicolon (;). This is also the case for function declarations.
Functions can also take parameters, which are objects that you can pass to it each time you execute it. The function can then use these objects:
1 function greet(name){
2 alert("Hello, " + name);
3 };
4
5 greet("Bob"); //Displays "Hello, Bob"
Functions are objects
Just like strings, arrays and object literals, functions are also objects and can be assigned to variables and other objects' properties:
1 //This is in fact the same as the first example above, where the
2 //name of the function was given in the function declaration itself
3 var greet = function(){
4 alert("Hello World!");
5 };
6
7 var myObject = {};
8 myObject.greet = function(){ alert("Greetings from myObject!"); };
9 myObject.greet();
10
11 //You can also add a function to an object directly in the object literal:
12 var myOtherObject = {
13 greet: function(){
14 alert("Greetings from myOtherObject!");
15 }
16 };
Functions can be methods
In the example above, we have two almost identical greet functions. In fact, when a function is attached to an object like that, we call it a method. A method has access to the object's other properties, a fact we can use to re-use the greet function on two different objects:
1 var person1 = {name: "Alice"},
2 person2 = {name: "Bob"};
3
4 person1.greet = function(){
5 alert("Hello, my name is " + this.name); //this.name will be both "Alice" and "Bob"
6 };
7
8 person2.greet = person1.greet
9
10 person1.greet(); // "Hello, my name is Alice"
11 person2.greet(); // "Hello, my name is Bob"
The this keyword inside a function refers to the object the method is attached to, so in the example above it first refers to person1, and then to person2.
Return values
Functions can return values that can in turn be used for other things. An example of this is a basic arithmetic function that adds two numbers:
1 function add(number1, number2){
2 return number1 + number2;
3 };
4
5 var twoPlusTwo = add(2, 2);
6 alert("2 plus 2 is " + twoPlusTwo + "and 4 + 4 is " + add(4, 4));
To return a value from a function, use the return keyword followed by the value.
Control structures¶
The original meaning of the word "script" leads us to believe that scripts on computers are something that starts at the top and the continues, line by line, to the bottom and then it's done. This is in fact how computer programs work, but sometimes we want our programs to be a little smarter than that and make decisions on where to go next, if it needs to repeat some lines or jump back to a different page. To help us with this, most programming languages provide something called control structures, and JavaScript has a few of these too. These structures usually take the form of a keyword with one of more conditions followed by a block of code that gets executed based on what the keyword and the conditions are:
1 keyword(conditions){
2 /* Code ... */
3 };
If and else¶
The most basic control structure is that of "execute this bit of code if this is true", which can be used to control the flow of the program based on the contents of variables and properties. As was noted above, everything in a program is or "evaluates to" either true or false. Let's say we had a function which prompted the user to enter their name called getName. We can use this to display a message based on the user's name:
1 var name = getName();
2
3 if (name == "Alice") {
4 alert("Hello Alice!");
5 }
Note: We don't end control structure statements with a semicolon.
If the user enters "Alice", the condition evaluates to true and the code block is run, displaying "Hello Alice". You can also add an else code block which gets run if the condition is not true - that is, if it's false:
1 var name = getName();
2
3 if (name == "Alice") {
4 alert("Hello Alice!");
5 } else {
6 alert("Hello, person who is not Alice");
7 }
There is a third keyword which can be used together with the if block which will run a code block if the first condition is not true, but the second is:
1 var name = getName();
2
3 if (name == "Alice") {
4 alert("Hello Alice!");
5 } else if (name == "Bob") {
6 alert("Hi there, Bob!");
7 } else {
8 alert("Hello, person who is not Alice or Bob");
9 }
Note: You can add more than one
else ifblock; they will be evaluated ("tested") in turn in the order they appear. Only one code block is ever run, so if two conditions were true, only the first would run.
While¶
The while statement will run a code block repeatedly until the condition is no longer true. Imagine you want to print all the numbers from 1 to 100; doing it manually would be boring, this is what we have computers for after all:
1 var currentNumber = 1;
2
3 while (currentNumber <= 100) {
4 print(currentNumber);
5 currentNumber = currentNumber + 1;
6 }
The above will start at number 1, then the block will execute for each number, adding 1 to currentNumber until it reaches 100 and then the program will continue. The condition is true as long as the currentNumber is less than or equal to 100, so when the number gets to 101 it won't execute the block any more.
