JS Icon JavaScript Client-Side Scripting Language

JavaScript (JS) is a scripting language implemented in all major web browsers. JS was not designed as a stand-alone language, but instead for embedding in other products and applications such as web browsers. JS implements a prototype-based object model instead of the more common class-based object model. More details about its usage and history can be found on this page. A language reference and programming guide for JS is located at the Mozilla Developer Network.

Run Environments Browsers, Websites, and REPL

JavaScript can run in all the major web browsers using the <script> HTML tags:

<script>
   window.alert("Hello World!").
</script>

There are also websites that host interactive run environments for JavaScript, such as: jsbin.com and jsfiddle.net Additionally Read-Eval-Print Loop (REPL) programs exist that create a simple interactive command shell for JavaScript commands. One example is located at www.jsdb.org. Before is a screen capture from the JS BIN site.

Code Quality JSLint, JSHint, Strict Mode

There are online tools for evaluating the quality of JS code. Douglas Crockford has a tool he calls JSLint. Anton Kovalyov maintains a more lenient tool called JSHint. JS also supports a strict mode that can help find coding errors.

JS strict mode provides a way to opt-in to a restricted variant of JS. Strict mode catches common coding mistakes and "unsafe" actions and throws an exception. Strict mode can be invoked for an entire script, or just for particular functions.

Put the exact statement "use strict"; before any statements in the script to invoke strict mode for an entire script.

// Invoke strict mode for entire script
"use strict";
var a = "I am the first line in the script"; 

Put the "use strict"; line before any statements in a function to invoke strict mode for the function.

// Function that accepts a variable number of parameters
function add() {
   "use strict";
   var sum = 0;
   for (var i=0; i<arguments.length; i++) 
      sum += arguments[i];
   return sum;
}

Strict mode changes the language syntax and the runtime behavior. One aspect of the strict mode is to convert coding mistakes into errors. For example, without strict mode a mistyped variable name would simply create a new variable and continue execution. In strict mode this will cause a reference error.

// Reference error if strict mode used
   var total = 5;
   totals = 10;
   alert("total: " + total);  // 5 

Fundamentals Data Types, Variables, Objects
1. JavaScript is case-sensitive, therefore null is not equal to Null or NULL.

2. Comments are a common style, the same as in C, Java, and PHP:

   // Single Line Comment

/* Multiline
       comment */

3. Data Types

- There is no explicit distinction between integer and decimal values. The .toFixed(digitsToLeft) function can be used to round decimal values to a fixed precision:

var cost = 12.5789;
alert("cost is: " + cost.toFixed(2));  //12.58, it rounded   

- Values other than undefined, null, 0, and "" generally evaluate to true.

("" == 0) // True, because of data type coercion,
                     see === operator.
                     
  var value1 = null;
  if (!value1) {
     alert ("null evaluates to false"); // null = False
  }

  var value1 = 7;
  if (value1) {
     alert("value1 assigned a value");  // not null = True
  }                     

- Accessing undefined variables or properties returns the undefined type:

if (!window.var1) {
   alert ("a is undefined");  // undefined
}

var dog = {
   breed: "collie"
}
alert ("The weight property of the object is: " +
        dog.weight);         // undefined

- JS is weakly typed. Variables don't have a data type until a value is assigned. Then the data type is inferred from its current value.

var a = 3;
var b = "kevin";
alert("type of a is: " + typeof(a));  // a = number data type
alert("type of b is: " + typeof(b));  // b = string data type
b = 3;
alert("type of b is: " + typeof(b));  // b = number data type

4. Variables

Variables can be declared two different ways:
  1. With var statement - depending on where declared, variable will have either local or global scope.
  2. Without var statement - variable will always have global scope.
It is best to always define variables with the var keyword to avoid accidentally creating global variables.

5. Equality

JS has two comparison operators for equality:
  1. == - type coercion, does not consider data type
  2. === - does consider data type in the comparison
  ('3' == 3)  // True
  ('3' === 3) // False

It is best to use === and !== operators to avoid problems caused by type coercion.

6. Objects

JS has prototype-based object model instead of the more common class-based object model. In the JS model, there is no class concept. Objects are just a collection of properties. Note. Properties must be assigned with the : and not the = operator.

JS has two ways for declaring objects. The new method (Object()) will allow you to create new properties outside of the initial declaration. The old method returns the unknown value when accessing properties that were not in the original declaration.

// OLD METHOD of creating objects
var emptyObj = {};
alert(emptyObj.toString());  // [object Object]

// NEW METHOD of creating objects
var myObj = new Object();
myObj.name = "Holly";
alert(myObj.name);          // Holly

Below is an example of how a function is used to help create objects:

function part(name, price) {
   return {
      name: name,
      price: price
   };
} 

var SN1234 = part("Water Pump", 89.99);
var SN6235 = part("Spark Plug",  3.99);

alert("SN1234 Name: " + SN1234.name + " Price: " + SN1234.price);
alert("SN6235 Name: " + SN6235.name + " Price: " + SN6235.price);

The next example shows how to define a toString function to return an object's values, instead of the value of [object Object] that the default toString method returns for objects.

// Define the object
var kevin = {
    name: "Kevin Harris",
    height: 70
};

// Original .toString
alert (kevin.toString());   // [object Object]

// Define new toString function
kevin.toString = function () {
   return "Name: " this.name + ", Height: " + this.height;
}

// Redefined toString 
alert (kevin.toString());  // Name: Kevin Harris, Height: 70


Functions Declarations
In JS functions are objects. JS functions have different behaviors that functions in most other languages. Particularly their anonymous naming capability and unusual scoping rule called Closure.

1. Traditional Function Declaration.

// Traditional declaration
function square(num) {             
   num = num * num;
   return num;
} 

// Primitive parameters passed by value
// (so original value is unchanged).
num = 8;
alert(num);                // 8
alert(square(num));        // 64     
alert(num);                // 8

2. Function Assigned to a Variable

// Function Assigned to a Variable
var squareFun = function square(num) {             
   return num * num;
}; 

// Called by the variable name.
// Can not call by the function name.
// Function name can also be omitted from declaration.
alert(squareFun(7));        // 49

3. Anonymous Function Immediately Invoked

// Anonymous Function Immediately Invoked
(function(num) { 
   alert("num parameter is: " + num);            
   return num * num;
})(7); 

// Function has no name and is not called.
// jQuery uses this method to avoid interaction with outer scope.
// Also used for call back functions such as Ajax async calls.

Functions Parameters
Primitive data types are passed to functions by value. Non-primitive data types (Arrays, Objects) are passed to functions by reference.

1. The original value of primitive data types are unchanged by functions.

function square(num) {             
   num = num * num;
   return num;
} 

// Primitive parameters passed by value
// (so original value is unchanged).
num = 8;
alert(num);                // 8
alert(square(num));        // 64     
alert(num);                // 8

2. The original value of non-primitive data types are changed by functions.

function personUpdate(person) {             
   person.name = "John";
} 

var personOfInterest = {name: "Bob", age: 29};

// Non-primitive parameters passed by reference
// (so original value is changed).
alert(personOfInterest.name);  // Bob
personUpdate(personOfInterest);     
alert(personOfInterest.name);  // John

Passing in too many or too few parameters in JS does not cause an error. JS assigns the unknown value to the missing parameters and ignores the extra parameters. Redefining the same function with a different number of parameters does not create a new function. Instead the new function overwrites the existing function. There is no function overloading in JS.

1. Mismatch on number of parameters does not generate a run-time error.

function add(num, num2) {
  return num + num2;
}

alert (add());         // NaN
alert (add(1));        // NaN
alert (add(1,2,99));   // 3   

2. Example of a function that can accept a variable number of parameters.

// Function that accepts a variable number of parameters
function add() {
   var sum = 0;
   for (var i=0; i<arguments.length; i++) 
      sum += arguments[i];
   return sum;
}

alert(add());      // 0
alert(add(2,4,6)); //12   

Functions The Arguments Object
The Arguments Object has local scope within a function. It contains all the function parameters. It is indexed like an array, but is actually an object.

// Display information arguments   
function argumentsInfo() {
   alert("arguments length: "      + arguments.length);   // 3
   alert("first argument: "        + arguments[0]);       // 1
   alert("data type of argument: " + typeof(arguments));  // object
}   

argumentsInfo(1,'A',2);

Functions Closure
Closure is a powerful feature of JS. When functions are nested, closure allows the inner functions access to the variables and functions defined in the outer functions -- even after the outer functions have gone out of scope. This ability is useful for event listeners and when making asynchronous Ajax calls. In this case the inner function acts as a callback function to execute when the Ajax process finishes. It should be noted however that the outer functions do not have access to the variables and functions defined inside the inner functions.

// Test of closure scoping
   function outterFunction() {
      var outterName = "Jody";
      alert("Outter Name: " + outterName);             // Jody
      alert("Inner Name: " + typeof(innerName));       // undefined
      
      function innerFunction() {
         var innerName = "Kim";
         alert("Outter Name: " + outterName);         // Jody
         alert("Inner Name: " + innerName);           // Kim
      }   
     innerFunction();
     function outterFunction() {
       alert("Outer Function Redefined");   
     }                                  // Outer Function Redefined
     outterFunction();
     innerFunction();                                // Jody                                      
   }                                                 // Kim
   outterFunction();

Control Structures Conditionals, Iterators, Loops
JS does not use blocks ({}) to control scope.

var amount = 5;
  {
     var amount = 10.0;
  }
  alert("amount is: " + amount);     // amount is: 10 

JS has C-style syntax for IF, SWITCH, FOR, WHILE (pretest) and DO...WHILE (posttest) statements. JS has a break and a continue statement.

JS also has a ternary (three operands) conditional if/else statement syntax:

// result = (condition) ? true : false;
    
    var price = 51;
    var cost = (price > 50) ? "Expensive" : "Cheap";
    alert("Cost is: " + cost);     // Expensive

break - When break is used without a label it terminates the inner-most control structure. When it is used with a label, it breaks the labeled control structure (see label command).

continue - When continue is used without a label it skips the current iteration of the inner-most control structure. When it is used with a label, it skips the current iteration of the labeled control structure (see label command).

In addition JS as a FOR .. IN structure used only to iterate through the properties of objects.

// For..in structure for objects only
   var rose = {
      genus: "rosa",
      family: "rosaceae",
      kingdom: "plantae"
   };
     
   for (var x in rose) {
      alert("key is: " + x + " value is: " + rose[x]);
   }   

Error Handling Try...catch...finally, Error Object
JS allows exceptions to be thrown, and supports the common try...catch...finally structure for handling errors. JS also contains an error object.

Below is an example of throwing an exception during input from an HTML input:

<script>
function valAge() {
try { 
   var x=document.getElementById("age").value;
   if(x == "")     throw "empty";
   if(isNaN(x))    throw "not a number";
   if(x > 100)     throw "too old";
   if(x < 21)      throw "too young";
} catch(err) {
   var y=document.getElementById("eMsg");
   y.innerHTML="Error: " + err + ".";
  }
}
</script>

<p>Enter your age:</p>
   <input id="age" type="text">
   <button type="button" onclick="valAge()">Enter Age</button>
<p id="eMsg"></p> 

Below is an example of JS using the try...catch...finally exception handling structure. The finally clause always executes regardless of where an exception occurs or not.

try {
   undefinedFunction()
   alert("Will alert if function is defined");
}
catch(e) {
   alert("Error name: " + e.name)
   alert("Error message: " + e.message)
}
finally {
   alert("Finally executes regardless of outcome above");
}

// Output:
//  Error name: TypeError
//  Error message: The value of the property 'undefinedFunction'
//                 is null or undefined, not a Function object. 
//  Finally executes regardless of outcome above

Data Types Strings, Numbers

1. Strings.

JS has no string interpolation (embedding strings inside other strings). In JS anything can be converted to a string. JS has no character data type, so a character value is considered a string with a length of 1.

JS has both a primitive string and an object String. JS automatically converts the primitive string to an object String so the object methods can be performed. A String object can be converted to its primitive counterpart with the valueOf method.

   var foo = "foo";
   var bar = new String("bar");
   
   alert(typeof foo);     // string
   alert(typeof bar);     // object  
   alert(typeof bar.valueOf());     // string (converted)  

Both quotes and apostrophes can be used as string delimiters. You can use the backslash for escaping either delimiter.

      var string1 = '"This is string one"';
      var string2 = "This isn't string one";
      var string3 = 'This isn\'t string one';
      
      alert(string1);  // "This is string one"
      alert(string2);  // This isn't string one
      alert(string3);  // This isn't string one                  

The \n is a new line and \u[hexValue] is for unicode:

     alert("First line\nTrade mark is \u2122"); 
     
     // Output:
     // First line
     // Trade mark is ™ 

JS temporarily converts the primitive string to an object String so the object methods can be performed:

var foo = "foo";
     var bar = new String("bar");
   
     alert(foo.length);     //  3
     alert(bar.length);     //  3

     alert(foo.charAt(0));     // f
     alert(bar.charAt(0));     // b

     alert(foo.indexOf("o"));     // 1
     alert(foo.indexOf("O"));     // -1

     alert(foo.toUpperCase());     // FOO 

There are string methods for both searching and modifying strings.

     var sentence = "This is a short sentence.";
   
     alert(sentence.search(/is/));     // 2
     alert(sentence.search(/that/));   // -1

     alert(sentence.replace("is","xx"));     
           //Thxx is a short sentence  
     
     alert(sentence.replace("is","xx"));     
           //Thxx is a short sentence  

     alert(sentence.replace(/is/g,"xx"));     
           //Thxx xx a short sentence
     
     alert(sentence.slice(1,3));     // hi (second parm unusual)      

Other common string methods include:

2. Numbers.

All numbers in JavaScript are 64-bit floating point numbers. JavaScript does not distinguish between integers and floating point numbers. Integers can be specified in octal (052), hexadecimal (0x2a), and exponential notation (5.85e+15).

var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
alert(biggestNum);     // 1.79e+308
alert(smallestNum);    // 5e-324

JS has both a primitive number and an object Number. JS temporarily converts the primitive to an object so the object methods can be performed. A Number object can be programmatically converted a primitive number data type with the valueOf method, or to a primitive string data type with the toString method.

   var foo = 123;
   var bar = new Number("123");
   
   alert(typeof foo);     // number
   alert(typeof bar);     // object  
   alert(typeof bar.valueOf());      // number (converted)  
   alert(typeof bar.toString());     // string (converted) 

A value can be converted to a number with the Number(), parseFloat() and parseInt() functions. If the conversion is not possible, the functions returns the special value NaN (Not-a-Number).

alert(Number("123"));   // 123
alert(Number("123A"));  // NaN

alert(parseFloat("2.345"));   // 2.345
alert(parseFloat("A2.345"));  // NaN

alert(parseInt("11"));      // 11
alert(parseInt("11", 2));   //  3
alert(parseInt("11", 8));   //  9 
alert(parseInt("11", 16));  // 17
alert(parseInt("G1", 16));  // NaN

There is a function called isNaN() which tests a value to determine if it is a number.

alert(isNaN(23));          // false
alert(isNaN("23"));        // false
alert(isNaN("G23"));       // true

The numbers in JS are approximations, so mathematical operations do not always give the expected results (example below). When dealing with dollar amounts in JS it is common to multiply and divide by 10 to get the precise results.

alert(0.1 + 0.2);                //0.30000000000000000000004
alert((0.1*10 + 0.2*10) / 10);   //0.3

3. Arrays.

Arrays are used frequently in JS because it only has two built-in data structures (object, array). JS arrays are list-like objects. Anything can be stored in an array and the array elements do not have to have the same data type. Also the size of a JS array is not fixed.

var myArray = [9,'K',{},/4/];

for (var x=0; x<myArray.length; x++) {
  alert("myArray " + x + " : " + myArray[x]);
}
// Output is: 9, K, object Object, /4/

Arrays can be used as a stack data structure by using the .push() and .pop() methods.

var myArray = ["A","B","C"];

myArray.push("D");
myArray.push("E");
alert("last in: " + myArray[myArray.length-1]);   // last in: E
alert("popped: " + myArray.pop());                // popped: E

Two other commonly used array methods include .slice(), for reading a range of elements and .splice() for removing a range of elements.

var myArray = ["A","B","C","D","E","F"];

// Slice(startPos,endPos-1)
alert(myArray.slice(2,4));    // C,D 
alert("Remaining elements: " + myArray);            // A,B,C,D,E,F

// Splice(startPos,length)
alert("Removed elements: " + myArray.splice(2,2));  // C,D
alert("Remaining elements: " + myArray);            // A,B,E,F

JS has a .sort() method for arrays which will alphabetically sort an array by default.

var myArray = ["F","E","D","C","A","B"];

// Sorts alphabetically by default
alert(myArray.sort());    // A,B,C,D,E,F   

The .sort() method takes a Compare Function parameter that can be used to change the sorting order. The compare function takes two input parameters (a,b). The function returns one of three values based on comparisons of the two input values: Below are examples showing how to perform an alphabetical sort and a numeric sort on an array.

var myArray = [101, 1, 12, 20, 30, 201];

function compareNumbers(first, second) {
  return first - second;
}

// Sorts alphabetically (lexicographical) by default
alert(myArray.sort());               // 1, 101, 12, 20, 201, 30 

// Compare function parameter used for numeric sort
alert(myArray.sort(compareNumbers)); // 1, 12, 20, 30, 101, 201  

Additional common array methods include:
Regular Expressions Matching Character Combinations
Regular expressions (RE) are patterns for matching character combinations in strings. RE are commonly used in scripting language processes to: Good JS RE reference sites include: Programmer's Guide to Regular Expressions and JavaScript Kit - Regular Expressions .

JS has a regular expression object that can be used with the following methods:
  1. search() - test for a match. Returns index of match or -1 if search fails.
  2. test() - test for a match. Return true/false.
  3. replace() - replaces matched set of characters with a replacement set.
  4. exec() - search for a match. Returns an array of information.
  5. match() - search for a match. Returns an array of information or null on a mismatch.
  6. split() - used to break a string into an array of substrings.
For the examples below, a short list of RE pattern rules:

1. The pattern goes in between two forward slashes.
2. All characters match themselves.
3. /w is a word match.
4. /d is a character match.
5. \s matches white space.
6. [] is a set of characters.
7. + indicates one or more times.
8. . matches any character.
9.{} are quantifiers.
10.() is a capturing group.
11. \ is an escape character.
12. Ending flags: g = global and i = ignore case.

1. search()

// search() returns position of first match.

var myString = "The sun is shining today.";
var regex = /s/;
alert(myString.search(regex));  // 4

2. test()

// test() returns true or false.

var myString = "The phone is 4 you.";
var regex = /\d/;
if (regex.test(myString)) {
  alert("Digit exists in string");
}

3. replace()

// replace(reg expr, replacement function)

var oldString = "George Washington";
regex = /(\w+) (\w+)/g;
var newString = oldString.replace(regex,function(match, capture1, capture2) {
  return capture2.toUpperCase() + ", " + capture1;
});

alert(newString);    // WASHINGTON, George

4. exec()

// exec() returns matched and captured values.

var street = "Street: 1123 E. Elm City: Chicago";
var regex = /Street:(.*)City:/;
var results = regex.exec(street);
alert("Matched = " + results[0]);     
alert("Captured = " + results[1]);

// Output:
// Matched = Street: 1123 E. Elm City:
// Captured = 1123 E. Elm 

5. match()

// match() returns matched values.

var myString = "Saturday was a better day than Monday";
var result = myString.match(/day/g);
alert(result);             //day,day,day

6. split()

// split() cuts a string into an array at matches.

var myString = "Saturday was a good day";
var result = myString.split(/\s/g);
alert(result[3]);          //good

Dates Date Strings and Objects
Calling Date() as a function returns a string. You must use the "new" operator to create a date object:

// String Date    
var stringDate = Date();
alert(stringDate.getMonth);   // Undefined


//Object Date
var objDate = new Date();
alert(objDate.getMonth());   // 2 = March (Zero Based)  

Parameters and methods for the Date object can be found at MDN - Dates. Note the month parameter is zero-based (1=February) while the day parameter starts with 1.

var currentDate = new Date();
alert(currentDate);    
       // Wed Mar 20 01:26:12 CDT 2013

var theDate = new Date(2000,0,1);
alert(theDate);
      // Sat Jan 1 00:00:00 CST 2000

Dates can be used in arithmetic as show by the elapsed time example below:

// Elapsed Time
var fromDate = new Date();

for (var x=0; x<100000000; x++) {
  var result = Math.sqrt(x);
}

var toDate = new Date();
var elapsed = toDate - fromDate;
alert ("Milliseconds: " + elapsed);   
    // Milliseconds 3476

There are JS libraries that provide additional date functionality, such as Moment.js, Datejs, and XDate.

JSON JavaScript Object Notation
JSON is a data format frequently used for serializing and transmitting structured data over a network. JSON is a more terse and human-readable format than XML. JSON was originally based on a subset of JavaScript (Object Notation) but is now a language-independent data format.

Douglas Crockford has a number of JS libraries for JSON at the GitHub website. JSON specifications can also be referenced at www.json.org. Some sources indicate that using these libraries is a more secure, more robust, and faster way of converting the JSON format than using the native JS eval() function.

A short example of JSON encoded data:

{
 "members": [
  { "firstName":"John" , "lastName":"Doe" }, 
  { "firstName":"Jane" , "lastName":"Doe" }, 
  { "firstName":"William" , "lastName":"Smith" }
 ]
}

HTML Manipulation JS and the DOM
JS is powerful at making dynamic changes to web pages. JS has methods that can modify the properties of the DOM nodes to:
  1. Change Content
  2. Change CSS Style
  3. Change Attributes
  4. Create New Elements
  5. Remove Existing Elements
  6. Change Event Handlers
Some of the common node properties used in JS include: Some of the common JS methods for manipulating DOM nodes include: Some examples of JS DOM manipulate are:

1. Change the text contents of a node:

  document.getElementById("msgTxt").innerHTML="New text!";

2. Change the styling of a node:

 document.getElementById("outDiv").style.color="blue";

3. Create a new node:

   var newHeader=document.createElement("h1");
   var node=document.createTextNode("New header text.");
   para.appendChild(node);
   var element=document.getElementById("outDiv");
   element.appendChild(newHeader);

More information about using scripts to change the DOM can be found on the jQuery page.


Event Listeners Triggering JS

The first browsers had a simple way to capture events and run associated scripts. When an element was defined, an event and script could be specified. This was coded as:

<script>
   function function1() {
      alert("Function 1 Executed.");
   }
</script>

<input type="button" value="Button 1"
       onClick="function1();"></input>

This simple method of capturing events lacks the flexibility required of more complex web pages. Inconsistences can appear across browsers when trying to have more than one HTML element detect the same event. DOM 2 created "event listeners" to handle multiple events for a single event. The syntax for adding an event listener is:

 elementReference.addEventListener("eventName", functionCall, phase);    

The third parameter (phase) indicates the order in which multiple nested events should be detected.1Phases are defined as:
1. Bubbling Phase (phase parameter = false, so capture is off.)
The process by which an event can be handled by one of the target's ancestors after being handled by the event target.
2. Capture Phase (phase parameter = true, so capture is on.)
The process by which an event can be handled by one of the target's ancestors before being handled by the event target.
An example of the newer event listening code is:

// The function to trigger.        
function switchMusic() {  
}

// Event listener to trigger function.      
var playbutton = document.getElementById("playButton");
playbutton.addEventListener("click", switchMusic, false);

More information about using scripts to capture events can be found on the jQuery page.


Top | Fundamentals | Functions | RegEx | Date | JSON | HTML Manipulation | Closure | Event Listeners