Helium Scraper's Blog All kind of useful and useless stuff related to Helium Scraper

14May/110

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:

  1. 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:

  1. 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:

  1. 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:

  1.  
  2. var myVariable;
  3. 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:

  1.  
  2. var myVariable = "some text";

The information we store in a variable can be changed at any point such as on this code:

  1.  
  2. var myVariable = "some text";
  3. myVariable = "some other text";
  4. 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):

  1.  
  2. var myOtherVariable;
  3.  
  4. // Store numbers:
  5. myOtherVariable = 12;
  6. myOtherVariable = -12;
  7. myOtherVariable = 1.02;
  8.  
  9. // Store boolean values:
  10. myOtherVariable = true;
  11. 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:

  1.  
  2. var myVar1 = "value of myVar1";
  3. var myVar2 = "value of myVar2";
  4. myVar1 = myVar2;
  5. // the value of myVar1 is now "value of myVar2"
  6.  


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:

  1. var n1 = 10;
  2. var n2 = 20;
  3. var result = n1 + n2; // assigns the result of 'n1 + n2' to 'result'
  4. // result is 30!

We can also write literal numbers in the operations such as in this example:

  1. var n1 = 10;
  2. var n2 = 20;
  3. var result = (n1 + n2) / 2;
  4. // result is 15!

There are a few shorthands for simple operations that I'll summarize in the following table:

Shorthand Meaning
  1. x++;
  1. x = x + 1;
  1. x--;
  1. x = x - 1;
  1. x += y;
  1. x = x + y;
  1. x -= y;
  1. x = x - y;
  1. x *= y;
  1. x = x * y;
  1. x /= y;
  1. x = x / y;

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:

  1. var dividend = 20;
  2. var divisor = 5;
  3. var quotient = dividend / divisor;
  4. var text = dividend + " divided by " + divisor + " is " + quotient + ".";
  5. 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:

  1. var myVar = 10 == 11;
  2. 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":

  1. var myVar1 = 10 == 11;
  2. var myVar2 = false;
  3. 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":

  1. alert("Hello world");

Note that we could have used a variable as a parameter such as in this example:

  1. var someVar = "Hello world";
  2. alert(someVar); // Shows "Hello world";
  3. var someNumber = 32.5;
  4. 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:

  1. function MyFunction()
  2. {
  3. alert("Hello from inside a function!");
  4. }

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:

  1.  
  2. 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:

  1. function ShowTwoThings(sayFirst, sayLast)
  2. {
  3. alert(sayFirst);
  4. alert(sayLast);
  5. }
  6.  
  7. 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:

  1. function AreaOfSquare(sideSize)
  2. {
  3. return sideSize * sideSize;
  4. }
  5.  
  6. var area = AreaOfSquare(5);
  7. 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:

  1. function Person()
  2. {
  3. }

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:

  1. var mrBob = new Person();
  2. 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:

  1. function Person(firstName, lastName)
  2. {
  3. this.FirstName = firstName;
  4. this.LastName = lastName;
  5. }
  6.  
  7. var bob = new Person("Bob", "Smith");
  8. var tim = new Person("Tim", "Burton");
  9.  

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":

  1. alert(bob.FirstName); // "Bob"
  2. alert(tim.LastName); // "Burton"
  3.  

We can also change the object's properties any time such as in this code:

  1. alert(bob.FirstName); // "Bob"
  2. alert(tim.LastName); // "Burton"
  3. bob.FirstName = "Bobby";
  4. 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:

  1. 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:

  1. var myArray = new Array();
  2.  
  3. // We can assign text to some element in myArray
  4. myArray[0] = "This is the value of the 0th element of myArray";
  5. myArray[1] = "This is the value of the 1st element of myArray";
  6. myArray[10] = "This is the value of the 10th element of myArray";
  7.  
  8. // We can also assign numbers
  9. myArray[11] = 200;
  10.  
  11. // And we can asign a new array!
  12. myArray[12] = new Array();
  13.  
  14. // "myArray[12]" is itself an array, so we
  15. // can use square brackets to access items in it
  16. 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:

  1. var someArray = new Array();
  2. alert(someArray.length); // 0
  3. someArray[0] = "zero";
  4. alert(someArray.length); // 1
  5. someArray[1] = "one";
  6. alert(someArray.length); // 2
  7.  
  8. // This will expand our array to have 11 items (0 to 10)
  9. someArray[10] = "ten";
  10. 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:

  1. if(condition)
  2. {
  3. // if condition is true, all the code in here will be executed
  4. }

or

  1. if(condition)
  2. {
  3. // if condition is true, all the code in here will be executed
  4. }
  5. else
  6. {
  7. // if condition is false, all the code in here will be executed
  8. }

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:

  1. var myVar = false;
  2.  
  3. if(myVar)
  4. {
  5. alert("myVar is true"); // This won't be executed
  6. }
  7. else
  8. {
  9. alert("myVar is false"); // This will be executed
  10. }
  11.  
  12. if(-1) alert("-1 evaluates to true");
  13. else alert("-1 evaluates to false");
  14.  
  15. var var1 = false;
  16. var var2 = true;
  17.  
  18. if(var1 && var2) alert("Both var1 and var2 are true");
  19. else alert("Not both var1 and var2 are true");
  20.  


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:

  1. while(condition)
  2. {
  3. // Code to be executed
  4. }

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:

  1. var v = 0;
  2.  
  3. while(v < 3)
  4. {
  5. alert(v);
  6. v++; // Shorthand for: v = v + 1;
  7. }

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:

  1. for(initial-expression; condition; increment-expression)
  2. {
  3. // Code to be executed
  4. }

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:

  1. for(var v = 0; v < 3; v++)
  2. {
  3. alert(v);
  4. }

This kind of loop is often combined with arrays such as on this example:

  1. var fib = new Array();
  2.  
  3. fib[0] = 0;
  4. fib[1] = 1;
  5.  
  6. // Calculate the 10 first Fibonacci numbers
  7. // and store them in the 'fib' array
  8. for(var i = 2; i < 10; i++) fib[i] = fib[i - 1] + fib[i - 2];
  9.  
  10. // Show the Fibonacci numbers stored in the
  11. // 'fib' array. Note the use of 'fib.length'
  12. 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.


Share/Bookmark