Minimal JavaScript tutorial for non programmers
This is a quick javascript tutorial for total non programmers. I won’t focus on javascript as applied to webpages, which is the case for most tutorials, because I’m mainly considering Helium Scraper users. So this tutorial comes handy if you want to learn javascript without necessarily caring about how to design web pages.
First off, you’ll need a place to test your code. If you don’t have Helium Scraper installed, go to this page and place your test code in the box that says “JavaScript” and press “Run” to run it. If you do have Helium Scraper go to any actions tree, add a “Execute JS” action and the JavaScript editor will appear. Erase the default line of code and press play to run your code. Let’s do a simple test to make sure everything is ready for further coding. Paste this code in your editor:
alert("Hello world!");
Run it, and a message box that says “Hello world!” should appear. If it did, then we are ready to start coding. I’ll be giving you a bunch of code examples. I encourage you to play and experiment with them. As a quick tip, to see the value of a variable called, say, myVariable, just add the following line at the end of your code:
alert(myVariable);
Contents:
Variables
Variables are symbols we use to store information. We can name a variable anything we want as long as:
- They start with a letter or the underscore (“_”) symbol.
- They are not composed by any other than letters, numbers and underscore characters.
JavaScript is case sensitive, which means a variable named myVariable is a different variable than a variable named myvariable. Even though you can create a variables on more than one way, I’ll show you the way that I consider the most intuitive one. To use a variable you need to first create it like this:
var myVariable;
This line of code is creating a variable called myVariable. The semicolon at the end is a way to tell the engine (the “engine” or “javascript engine” is what interprets our javascript code and executes it) that this is the end of our statement. Is optional, but will prevent ambiguities later on when writing more complex code.
To assign a value to our variable we need to add a line that uses the assignment (“=”) operator such as on this code:
var myVariable;
myVariable = "some text";
The assignment operator assigns whatever is on the right to whatever is on the left (note that is not the same as the equality symbol in math). So in the code above, the second line assigns the text “some text” to the variable myVariable. Now, this code could have been written a little bit differently, even though it means the very same thing:
var myVariable = "some text";
The information we store in a variable can be changed at any point such as on this code:
var myVariable = "some text";
myVariable = "some other text";
myVariable = "and some other text";
On these examples we are storing strings (text) in the variable, but strings are not the only kind of data or data type we can store in them. We can also store numbers, boolean values (true and false), and objects (I’ll talk about these later on):
var myOtherVariable;
// Store numbers:
myOtherVariable = 12;
myOtherVariable = -12;
myOtherVariable = 1.02;
// Store boolean values:
myOtherVariable = true;
myOtherVariable = false;
The lines that start with “//” are comments. Whenever you put a “//” before a line, the engine will ignore that line so you can write there whatever you want.
You can also store the value of another variable into a variable such as on this code:
var myVar1 = "value of myVar1";
var myVar2 = "value of myVar2";
myVar1 = myVar2;
// the value of myVar1 is now "value of myVar2"
Operators
Assignment operator
The most important operator is by far the assignment operator (“=”). We’ve been using it throughout the whole tutorial and all it does is to assign whatever you put on its right side to whatever you put on its left side. You cannot put literals on the left of an assignment operator because they cannot receive a value. Literals are what I have been assigning to my variables (by putting them on the right side) in the whole Variables section above, such as “Hello world”, 32.5 and false.
Mathematical operators
We can use mathematical operators among literals and variables as long as they store numbers. These operators are +, –, * (multiplication) and /. We can also use parenthesis as we would in a mathematical equation. An operation behaves in javascript just like a variable, except that it cannot receive a value (it cannot be on the left side of an assignment operator). So just like we can assign the value of myVar2 to myVar1 by writing myVar1 = myVar2, we can assign an operation to a variable such as in the following code:
var n1 = 10;
var n2 = 20;
var result = n1 + n2; // assigns the result of 'n1 + n2' to 'result'
// result is 30!
We can also write literal numbers in the operations such as in this example:
var n1 = 10;
var n2 = 20;
var result = (n1 + n2) / 2;
// result is 15!
There are a few shorthands for simple operations that I’ll summarize in the following table:
Shorthand | Meaning |
|
|
|
|
|
|
|
|
|
|
|
|
There is a special use for the addition operator when combined with strings: it joins the operands together and turn them into a longer string. The following example will illustrate this:
var dividend = 20;
var divisor = 5;
var quotient = dividend / divisor;
var text = dividend + " divided by " + divisor + " is " + quotient + ".";
alert(text); // Shows "20 divided by 5 is 4".
Comparison operators
A comparison operator compares its operands a returns a boolean value that indicates whether the operation is true or false. Here is the table of all logical comparison operators and their meanings:
Operator | Description | Example |
Equal (= =) | Returns true if the operands are equal. | x == y returns true if x equals y. |
Not equal (!=) | Returns true if the operands are not equal. | x != y returns true if x is not equal to y. |
Greater than (>) | Returns true if left operand is greater than right operand. | x > y returns true if x is greater than y. |
Greater than or equal (>=) | Returns true if left operand is greater than or equal to right operand. | x >= y returns true if x is greater than or equal to y. |
Less than (<) | Returns true if left operand is less than right operand. | x < y returns true if x is less than y. |
Less than or equal (<=) | Returns true if left operand is less than or equal to right operand. | x <= y returns true if x is less than or equal to y. |
For instance, the following code:
var myVar = 10 == 11;
alert(myVar);
will show a message that says “false”. These operators and the logical operators bellow will be very useful when combined with if/else statements and loops.
Logical operators
Logical operators use boolean values as operands and return a boolean value. Here is a list of them:
Operator | Usage | Description |
and (&&) | expr1 && expr2 | True if both logical expressions expr1 and expr2 are true. False otherwise. |
or (||) | expr1 || expr2 | True if either logical expression expr1 or expr2 is true. False if both expr1 and expr2 are false. |
not (!) | !expr | False if expr is true; true if expr is false. |
So, for instance, the following code will show a message that says “true”:
var myVar1 = 10 == 11;
var myVar2 = false;
alert((!myVar1) && (!myVar2));
Functions
Functions are pieces of code that perform a specific task. Later on, I’ll show you how to write your own functions, but first let’s see how to call or invoke them. JavaScript provides many useful built-in functions. To call a function, all you need to do is write the function name, followed by open an closing parenthesis, and if the function receives parameters, put them inside these parenthesis separated by commas. For instance, the function alert receives an object, usually a string as a parameter and shows the value of the given object in a message box. This is how we would show a message that says “Hello world”:
alert("Hello world");
Note that we could have used a variable as a parameter such as in this example:
var someVar = "Hello world";
alert(someVar); // Shows "Hello world";
var someNumber = 32.5;
alert(someNumber); // Shows 32.5
Now let’s see how to write our own functions. To write a function you use the function keyword, followed by the function name, then open and closing parenthesis and optional parameters in between them, and then open and closing brackets with the code to be executed when the function is called in between them. Here is an example:
function MyFunction()
{
alert("Hello from inside a function!");
}
When this function is called, it will show a message that says “Hello from inside a function!”. You would call this function in the same fashion we called the alert function:
MyFunction();
Note that we are not passing any parameter to the function because this function doesn’t receive any parameter. To write a function that receives a parameter, you would put it in between the parenthesis such as on this function:
function ShowTwoThings(sayFirst, sayLast)
{
alert(sayFirst);
alert(sayLast);
}
ShowTwoThings("say this", "and then this");
The code above defines a function called ShowTwoThings that receives two parameters. Not particularly useful, but illustrative enough. A concept to take into consideration here, is the concept of a variable’s scope. The scope is the section of code in which a variable exists. If I would declare a variable inside a function, everything that is outside the function doesn’t know that the variable has exists at all. Also, parameters, such as sayFirst in the function above, are only accessible from within the function’s body.
Another important thing to know about functions is that they can return values by using the return keyword. The return keyword will cause the code in the function to terminate (this is why is usually, but not always, at the end of the function), and it will assign the value at the right of the return keyword to the function call. The following is a simple example of this:
function AreaOfSquare(sideSize)
{
return sideSize * sideSize;
}
var area = AreaOfSquare(5);
alert(area); // 25
Objects
The object is the main concept in object oriented programming. The goal of OOP is to make code more intuitive and easier to work with by organizing a program into objects that behave a lot like real life objects because they have properties and perform certain actions. So, for instance, a programmer writing a desktop application would write the code for an object that represents a button, name it something intuitive like “Button”, put it in another file and forget about all the messy code inside it and just think of it as a button that has properties such as size and color, and performs actions such as changing its appearance from non pushed to pushed.
Before start coding, I want you to keep in mind the difference between two concepts: a class and an object (also called an instance of a class). An object is a particular case of a class. For instance, “car” is class. But my black car parked downstairs is an instance of the class “car”: an object. We well use this distinction when dealing with objects in javascript.
Instances or objects can be assigned to variables just like we assign numbers or strings to them, but instead of representing a value, they contain other variables (called properties) and functions (called methods). In order to access a property or a method in an object, we use the accessor operator (“.”). So if we have an object called myObject that contains a property called myProperty we would write myObject.myProperty to access the myProperty property of the myObject instance. If the value of myProperty would be also an object that contains a property called myDeeperProperty we could access it this way: myObject.myProperty.myDeeperProperty.
To define a class, you write it just like you would write a function:
function Person()
{
}
The difference between this and a function will be in the way we use it. The following code creates two instances of the class Person:
var mrBob = new Person();
var mrTim = new Person();
We use the new keyword to tell the engine we want to use Person as a class and create an instance of it. The code inside Person will be still called, just like if we would be calling it as a function, and we can pass parameters to it, but it cannot have a return value. The code inside Person, if used as a class, is what we would call the constructor of the class, because is where we set the initial values of the properties of the object and do any other start-up stuff that needs to be done every time an instance of our class is created. Here is an improved version of the class Person:
function Person(firstName, lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
var bob = new Person("Bob", "Smith");
var tim = new Person("Tim", "Burton");
This Person now has a FirstName and a LastName. As you can see, when I create my two objects, I’m passing a name and a last name to each of them. I use the this keyword in the constructor to define two properties (FirstName and LastName) and assign the values passed as parameters to them. The this keyword represents the object itself from inside
the object’s code, and in this case, from the object’s constructor. If we add the following code after the code above and run it, it will show us “Bob” and then “Burton”:
alert(bob.FirstName); // "Bob"
alert(tim.LastName); // "Burton"
We can also change the object’s properties any time such as in this code:
alert(bob.FirstName); // "Bob"
alert(tim.LastName); // "Burton"
bob.FirstName = "Bobby";
alert(bob.FirstName); // "Bobby"
Arrays
Arrays are a special kind of object that can contain more than one value. You cannot define arrays as you would define a class. You just create and use them. This is how to create an array:
var myArray = new Array();
An array contains a numbered list of virtually infinite storage spots and, as such, we can store in them numbers, string, boolean values and objects. To access the elements in an array you use the square brackets operators (“[” and “]”) such as in this example:
var myArray = new Array();
// We can assign text to some element in myArray
myArray[0] = "This is the value of the 0th element of myArray";
myArray[1] = "This is the value of the 1st element of myArray";
myArray[10] = "This is the value of the 10th element of myArray";
// We can also assign numbers
myArray[11] = 200;
// And we can asign a new array!
myArray[12] = new Array();
// "myArray[12]" is itself an array, so we
// can use square brackets to access items in it
myArray[12][1] = "This is the value of the 1st element of an array that is in the 12th element of myArray";
The array object has a property called length that tell us how many items are in the array. The following example illustrates how to use this property:
var someArray = new Array();
alert(someArray.length); // 0
someArray[0] = "zero";
alert(someArray.length); // 1
someArray[1] = "one";
alert(someArray.length); // 2
// This will expand our array to have 11 items (0 to 10)
someArray[10] = "ten";
alert(someArray.length); // 11
If/Else statements
If/Else statements execute a piece of code if a given condition is true, not 0, or not an empty string (every one of these conditions evaluate to true when used as conditions). If the condition is false, 0 or an empty string (evaluates to false), another optional statement is executed. This is the syntax:
if(condition)
{
// if condition is true, all the code in here will be executed
}
or
if(condition)
{
// if condition is true, all the code in here will be executed
}
else
{
// if condition is false, all the code in here will be executed
}
This condition will normally be a boolean value such as the result of a logical operation. The brackets are optional if the code to be executed consist of a single statement. The following example will help illustrate this:
var myVar = false;
if(myVar)
{
alert("myVar is true"); // This won't be executed
}
else
{
alert("myVar is false"); // This will be executed
}
if(-1) alert("-1 evaluates to true");
else alert("-1 evaluates to false");
var var1 = false;
var var2 = true;
if(var1 && var2) alert("Both var1 and var2 are true");
else alert("Not both var1 and var2 are true");
Loops
Loops are pieces of code that are repeated until a certain condition is met.
While loops
A while loop executes a piece of code repeatedly while a certain condition evaluates to true. This is the syntax:
while(condition)
{
// Code to be executed
}
Brackets are optionals if the code to be execute consists of a single statement. The condition works exactly as the condition in an if/else statement. We normally want this condition to change inside the code between brackets (otherwise you would loop forever!). This example will illustrate this:
var v = 0;
while(v < 3)
{
alert(v);
v++; // Shorthand for: v = v + 1;
}
This code will show us the value of v and increment it as long as it is less than 3. Therefore, it will show us 0, 1 and 2.
For loops
A for loop is a fancier way to write a while loop. Every while loop can be translated to a for loop and vice versa. In many circumstances, particularly when using it with an incrementing variable, becomes more easily readable than a while loop. Here is the syntax:
for(initial-expression; condition; increment-expression)
{
// Code to be executed
}
Again, brackets are optional as long as the code to be executed consists of a single statement. This is how it works. First, initial-expression is executed no matter what. Then, while condition is true, two things happen repeatedly: the code in between brackets is executed and then the increment-expression is executed. The following code has the exact same meaning and therefore produces the same result as the while loop above:
for(var v = 0; v < 3; v++)
{
alert(v);
}
This kind of loop is often combined with arrays such as on this example:
var fib = new Array();
fib[0] = 0;
fib[1] = 1;
// Calculate the 10 first Fibonacci numbers
// and store them in the 'fib' array
for(var i = 2; i < 10; i++) fib[i] = fib[i - 1] + fib[i - 2];
// Show the Fibonacci numbers stored in the
// 'fib' array. Note the use of 'fib.length'
for(var i = 0; i < fib.length; i++) alert(fib[i]);
I made this tutorial as summarized as I could. If you would like to read further about javascript, here is a good guide you might want to take a look at.