News & UpdatesProgrammingWeb programming Store My Projects

JavaScript Tutorial – 06 – Conditionals

August 26th, 2009

The conditional statements execute different code blocks for different conditions.

If statement

The if statement will execute only if the condition inside the parenthesis is true.

if (x < 0.5) {     
  document.write(x + " < 0.5"); 

To test for other conditions any number of else if clauses can be added. For handling all other cases there can be one else clause at the end.

if (x < 0.5) {     
  document.write(x + " < 0.5"); 
else if (x > 0.5) {
  document.write(x + " > 0.5"); 
else {
  document.write(x + " == 0.5"); 

The curly brackets can be left out if only one statement needs to be executed conditionally.

if (x < 0.5)      document.write(x + " < 0.5"); 
else if (x > 0.5) document.write(x + " > 0.5"); 
else              document.write(x + " == 0.5");

Switch statement

The switch statement checks if a string or number is equal to a case label and then executes the matching case. It can contain any number of cases and it can end with a default label for handling all other cases.

switch (x) 
  case 0: document.write(x + " is 0"); break;
  case 1: document.write(x + " is 1"); break;
  default: document.write(x + " is something else");

Note that the statements after each case label are not surrounded by curly brackets. Instead, the break keyword is used to stop execution from continuing over to the next case.

Ternary operator

In addition to the if and switch statements there’s the ternary operator (?:) that can replace an if/else clause. This operator takes three expressions. If the first one is true the second expression is evaluated and returned, and if it’s false the third one is.

(x == 1) ? x = 0 : x = 1; // Ternary operator statement
x = (x == 1) ? 0 : 1;     // Ternary operator expression

JavaScript Tutorial – 05 – Arrays

August 26th, 2009

An array is a data structure used for storing a collection of values. In JavaScript, there are three kinds of arrays: numeric, associative, and multidimensional.

Numeric arrays

Numeric or indexed arrays are the most common type and use an index to refer to each of its elements. They can be created in four different ways. First, the array constructor can be used with the array elements specified as the parameters.

var a = new Array(0,1,2);

Second, the elements can be filled in using the array square brackets.

var b = [0,1,2];

The third way is to create an empty array and then use the square brackets to fill it one element at a time. Note that the array index starts with zero and that the capacity of the array is adjusted automatically as more elements are added.

var c = new Array();
c[0] = 0;   
c[1] = 1;   
c[2] = 2;

The fourth and last way of creating an array is by using the array constructor with a single parameter, which will be the initial size of the array. If the maximum number of values that the array needs to hold is known beforehand then this method can be used to slightly improve the performance.

var d = new Array(3);

When reading elements from an array the same square bracket notation is used as when writing to them.


Note that the elements inside of the array can store any data type, just as regular variables can.

var e = [0, 3.14, "string", true];

Associative arrays

The second kind of array is the associative array, which uses a key string instead of a numerical index. To create one, first declare an empty array and then assign values to the desired keys.

a = new Array();
a["name"] = "Peter";   
a["age"]  = 25;

When reading these elements it’s important to remember the key names, since these arrays cannot be accessed with an index.

document.write(a["name"] + " is " + a["age"]);

In JavaScript, associative arrays are also objects. Therefore, associative arrays can alternatively be accessed using the dot notation. = "Peter";
a.age  = 25;
document.write( + " is " + a.age);

Multidimensional arrays

Multidimensional arrays can be created by adding arrays as elements to another array. They can have any number of dimensions and for each new dimension there is another set of square brackets.

a = [[0,1,2], [3,4,5], [6,7,8]]; 
a[0][2] = "two";
document.write(a[2][2]); // 8

JavaScript Tutorial – 04 – Operators

August 26th, 2009

JavaScript basically has five kinds of numerical operators.

Arithmetic operators

First, there are the four basic arithmetic operations, together with modulus to gets the division remainder.

x = 4+2; // 6 // addition
x = 4-2; // 2 // subtraction
x = 4*2; // 8 // multiplication
x = 4/2; // 2 // division
x = 4%2; // 0 // modulus (division remainder)

Assignment operators

Second, there are the assignment operators. Most importantly, the equal sign itself which assigns a value to a variable.

Combined assignment operators

The combined assignment operators perform arithmetic operations on the same variable that they assign to.

x += 5; // add and assign
x -= 5; // subtract and assign
x *= 5; // multiply and assign
x /= 5; // divide and assign
x %= 5; // modulus and assign

Increment and decrement operators

The increment and decrement operators increase or decrease a variable by one.

x++; // x += 1;
x--; // x -= 1;

They can be used either before or after a variable.

++x; // pre-increment
--x; // pre-decrement     
x++; // post-increment
x--; // post-decrement

The post and pre versions of the operators have the same effect on the variable. The difference is that the post-operator returns the original value before it changes the variable, while the pre-operator changes the variable first and then returns it.

x = 5; y = x++; // y=5, x=6
x = 5; y = ++x; // y=6, x=6

Comparison operators

The third group is the comparison operators, which compares two values and return either true or false. They are mostly used for creating conditions in flow control statements. Notice the “identical” and “not identical” operators for comparing both type and value. These are necessary because with the regular “equal to” operator will automatically perform a type conversion before it compares.

x = (2==3);  // false // equal to
x = (2===3); // false // identical (same type and value)
x = (2!==3); // true  // not identical
x = (2!=3);  // true  // not equal to
x = (2>3);   // false // greater than
x = (2<3);   // true  // less than
x = (2>=3);  // false // greater than or equal to
x = (2<=3);  // true  // less than or equal to

Logical operators

The fourth group is the logical or boolean operators. These are usually used together with the comparison operators. Logical and returns true if the expressions on both sides are true. Logical or returns true if the left or right sides are true. Logical not simply inverts a boolean value. Note that logical and/or will not evaluate what is on the right side if the result is already decided by the left side.

x = (true && false);  // false // logical and
x = (true || false);  // true  // logical or
x = !(true);          // false // logical not

Bitwise operators

The fifth and last group is the bitwise operators which work on the binary representation of numbers. Notice that there are two right shift operators. The first one (>>) leaves the sign bit untouched, while the second one (>>>) shifts is to the right as with the other bits. Both operators evaluate the same for positive numbers.

x = 5 & 4;  // 4 (101 & 100 = 100) // and
x = 5 | 4;  // 5 (101 | 100 = 101) // or 
x = 5 ^ 4;  // 1 (101 ^ 100 = 001) // xor (exclusive or)
x = 4 << 1; // 8 (100 << 1  =1000) // shift left
x = 4 >> 1; // 2 (100 >> 1  = 010) // shift right (!sign)
x = 4 >>> 1;// 2 (100 >>> 1 = 010) // shift right     
x = ~4;     //-5 (~00000100 = 11111011) // invert

The bitwise operators also have their own combined assignment operators.

x  &= 5; // AND and assign
x  |= 5; // OR and assign
x  ^= 5; // XOR and assign
x <<= 5; // left shift and assign
x >>= 5; // right shift and assign (keeps sign bit)
x>>>= 5; // right shift and assign

String operators

There are only two operators that work on strings. First, the addition operator which can combine two strings together. Second, the combined assignment operator for addition can append one string to the end of a string variable.

x = "Hello";      // assignment
x = x + " World"; // concatenation
x += " World";    // concatenate and assign

Another usage for the addition operator is to convert strings into numbers. This is done by putting the addition sign just before the string.

document.write( "5" + 5); // 55
document.write(+"5" + 5); // 10

Operator precedence

In JavaScript, expressions are normally evaluated from left to right. However, different operators have different precedents. For example, multiplication binds harder than addition and is therefore evaluated first.

x = 2 + 1 * 2; // 4

To avoid ambiguous expressions, like the one above, parenthesis can be used to decide the order of evaluation. The parenthesis has the highest precedence of all operators.

x = (2 + 1) * 2; // 6

JavaScript Tutorial – 03 – Variables

August 26th, 2009

Declaring and Assigning variables

Variables are used to store values so that they can be accessed several times in a document. To create a variable the var keyword is used followed by the variable’s name. The variable can then be assigned a value with the assignment operator.

var myVar;
myVar = "Hello World";

The declaration and assignment of a variable can also be combined into one statement.

var myVar = "Hello World";

A variable’s name can include underscores characters and numbers, but it cannot start with a number. As for data types, JavaScript is an untyped language so any variable can hold any data type.


Integers can be represented with decimal, octal, or hexadecimal notation.

var a = 10;  // 10 with decimal notation
var b = 012; // 10 with octal notation (base 8)
var c = 0xA; // 10 with hexadecimal notation (base 16)


Floating-point numbers can be represented with either decimal or exponential notation. Note that all numbers in JavaScript are stored as floating-point numbers behind the scenes.

var d = 10.1;
var e = 0.1e2; // 10 with exponential notation (0.1*10^2)


Strings can be specified using either double or single quotes.

var a = "Hello World";
var b = 'Hello World';

To break a line within a string a backslash must be added. This character escapes the newline character which in JavaScript normally means the end of a statement.

var c = "Hello \

Escape characters

Backslash is used to add special characters to a string, such as newlines or quotes.

var a = "\' Single quote \
	    \" Double quote \
	    \\ Backslash \
	    \b Backspace \
	    \f Form feed \
	    \n New line \
	    \r Carriage return \
	    \t Tab \
	    \& Ampersand";


For storing boolean values the keywords true and false can be used.

var a = true; // Boolean (true or false)


For storing no value there is the null keyword, which is different from leaving out the assignment. When a variable is assigned to null it becomes undefined. This is equal to NotANumber for numbers, undefined for strings, and false when the variable is evaluated as a boolean.

var b = null; // No value
var c;        /* Undefined (NaN for numbers, "undefined" for strings, false for boolean) */

Variable scope

The scope of a variable depends on where it is declared. A variable that is declared outside of a function becomes a global variable and can be used anywhere on the page after where it’s been declared, even inside another script.

<script type="text/javascript">
  var a = 1; // global variable a
<script type="text/javascript">
  document.write(a); // 1

The lifetime of these variables starts when they are declared and ends when the web page is closed. On the other hand a variable declared inside a function becomes a local variable. It can only be used inside that function after where it has been declared and it will be destroyed when the function is finished. A local variable can use the same name as a global variable and thereby overshadow it for the duration of the function.

var a = 1; // global variable a   
function f()
  var a = 2; // local variable a (overshaddows global a)

There is also a second way of declaring variables by leaving out the var keyword and thereby declaring them implicitly. A variable declared like this will always become a global variable, even if it’s declared within a function.

function f()
  b = 5; // global variable b

JavaScript Tutorial – 02 – Using JavaScript

August 26th, 2009

To embed a JavaScript into a web page the HTML <script> element is used with the type attribute set to “text/javascript”.

<script type="text/javascript"> </script>

Printing output

The first script to learn is the document.write method for dynamically outputting HTML onto the page.

<script type="text/javascript">
  document.write("Hello World!");

Statements in JavaScript end with a semicolon, but a newline also functions as the end of a statement. Therefore, semicolons are not required unless there are several statements on the same line.

<script type="text/javascript">
  document.write("Hello World"); document.write("!")

Comments and whitespace

JavaScript uses the standard C++ comment notation, with both single-line and multi-line comments. As in HTML, whitespace is ignored in JavaScript, so extra spaces can be used to make the scripts more readable.

<script type="text/javascript"> 
 // single-line comment
 /* multi-line
    comment */

Hello World

The HTML document below contains a Hello World JavaScript.

<head><title>Learning JavaScript</title></head>
  <script type="text/javascript">document.write("Hello World");</script>

When this document is viewed in a browser the script is executed as soon as the page loads and the text is displayed. Note that the script runs on the client-side. Therefore, there is less load on the server compared to server-side scripts. However, this also means that it’s up to the client whether the script is executed or not. The client may have disabled JavaScript or use an old browser that doesn’t support it.


If the browser doesn’t support JavaScript the script will be displayed as normal HTML. To prevent this it can be surrounded with the HTML comment tag, which effectively hides the script.

<script type="text/javascript"> <!--
//--> </script>

There’s also the <noscript> HTML element. This element presents an alternative message that can only be seen by browsers that don’t support scripts. However, since JavaScript is the most popular scripting language it works with all major browsers today.

 Your browser doesn't support JavaScript.

External script file

Another way to include JavaScript is by saving the script in a file with a .js file extension. This external script can then be embedded in a page by pointing to the file with the src attribute of the script tag. This way several pages can use the same scripts without having to duplicate them on every page.

<script type="text/javascript" src="MyJS.js"></script>

JavaScript Tutorial – 01 – Introduction

August 26th, 2009

JavaScript is primarily used as a client-side scripting language used for creating dynamic web pages. The scripts are embedded into HTML pages you upload to your web host that are then executed on the client’s system when they view those web pages. Despite its name JavaScript is a completely different language than Java. JavaScript is an interpreted language, meaning that scripts execute without preliminary compilation.

  1. 1
  2. ...
  3. 30
  4. 31
  5. 32
  6. 33
  7. 34
  8. ...
  9. 37