JavaScript tutorial:
The building blocks of JavaScript

Variables

Variables allow you to refer to stored data by name, for example:

firstname = "Bill";
age = 23;
city = "Adelaide";
document.write (firstname + " (" + age + ") is from " + city + ".");
 

To run the code above, copy it and paste it into JavaScript Editor, and click the Execute button (or select Build / Execute from the menu).

Observe how the document.write() function puts the strings and variables together to construct an output string. When you run your scripts, JavaScript Editor captures all the output and displays it in the Output tab.

To assign a value to a variable use the = sign:

firstname = "Bill";

To test for eqality, use the == sign:

age = window.prompt ("Enter your age", 20);

if(age==20) document.write("You are 20 years old!");

  To run the code above, copy it and paste it into JavaScript Editor, and click the Execute button.

Statements

Variables and other items on a line form a statement. JavaScript does not require that you terminate a statement, but other programming languages like C, C++, C# or Java do, and use the semicolon for this purpose. It is a good practise to do the same in JavaScript:

str = "This is a semicolon-terminated statement";

Expressions

An expression is a combination of variables, operators and values.

Boolean expressions evaluate to true or false.

myAge = 20;
result = (myAge==20); // This is a boolean expression

Numeric expression evaluate to a number.

result = 365 / 12; // This is a numeric expression

What happens when you run the code above in JavaScript Editor? Observe the Status line at the bottom of the Editor. In this case, the code has no write(), alert() or other display functions.
To speed up your testing, JavaScript Editor always displays the script return value in the Status line. In this case, the status line shows: Script returned: 30.416666 (which is the average number of days in a month).

Functions

You can group statements together into functions. Functions execute the statements one after another and can also return a value.

  function addTwoNumbers(a, b)
  {
    var c=a+b;
return(c); }
num = addTwoNumbers (2, 3); document.write ("The result is: " + num);

To run the code above, paste it into JavaScript Editor, and click the Execute button.

a and b in the example above are the parameters you specify when you call the function. The return value of the function is assigned to the new variable, num.

Function parameters are enclosed in () parantheses, and where the function starts and ends is denoted by the {} curly braces.

Comments

JavaScript supports 2 types of comments (same as C++, C#, or Java):

// Everything that comes after // is a coment (until the end of the line)
/* Everything between /* and */ is a comment (useful for multi-line comments) */ // You can also use // for every line // for a multi-line comment.

Next