JavaScript Primer for jQuery


Like any other programming language, JavaScript manipulates values such as numbers or text.

The kinds of values a language can work with are its data types. JavaScript supports the basic data types of number and string. All numbers are 64-bit double-precision, and range from -5e-324 to 1.7976931348623157e308. In other words, there’s no difference between integers and floating­point numbers; they are both just numbers. The following example uses the typeof operator to demonstrate:

>typeof 1;


>typeof 1.5;


Code snippet is from typeof.txt

All JavaScript numbers are represented in binary as IEEE-754 Doubles. That also means you should apply some caution when doing arithmetic. For example, if you are summing two number values that, in your mind, represent a currency operation, you may get very unexpected results, as shown in the following code:

>.1 + .2


Code snippet is from unexpected-addition.txt 

Unfortunately, JavaScript has no built-in decimal type. The language does offer two methods on Number, toPrecision, and toFixed, which will format a number using a fixed number of decimal places. The following code shows both in action.

>var num = 1234.12345123;



var num2 = 1234.12345123 ;



Code snippet is from decimal.txt

If you use a number, or obtain a result, outside of the 64-bit range, JavaScript returns a special number called Infinity, or -Infinity. Division by zero returns Infinity. There is one more special value, NaN, meaning “Not a Number” which is a “toxic value” that is often the source of bugs.

NaNs occur when attempting to cast an invalid string object to a number. It has a viral nature; in other words, performing an operation between numbers and a NaN returns a NaN. You can test if a variable is a NaN by using the built-in isNaN() function.

> 10*1+100 – 1 – Nan
>var x = NaN;

Code snippet is from isNaN.txt

JavaScript supports Octal (base 8) and Hexadecimal (base 16) numbers as well. Octal literals are prefixed with a 0 (zero), and Hexadecimal numbers are prefixed with an x.

JavaScript has a built-in Math object for common math operations. For example, you can use the Math.round() method to get a two decimal point accuracy.


Code snippet is from math-round.txt

Making good use of the built-in objects can save time and effort.


Strings are a series of zero or more 16-bit unicode characters enclosed by either single quotes or double quotes. I emphasize unicode because of its importance in internationalization. There is no special data type for characters. Strings are also (immutable) objects, and hence have methods and properties as well.

>”Test String”.indexOf(“S”)


>”Test String”.charAt(“5”)


Code snippet is from stringMethods.txt

Later on, you’ll see how you can augment the built-in String object to your benefit.


The Boolean type represents true and false values. In the appropriate context, such as inside an if statement, any value is converted to Boolean to test for “truthiness.” Empty strings, NaNs, null, undefined, the number zero (0), and the keyword false evaluate as false in a test; any other values resolve to true.


console.log(‘something happens’);

} else {

console.log(‘nothing happens’);


nothing happens

Code snippet is from basic-boolean.txt

There are also Boolean operations: the logical and (&&), or (II), and not (!). These are useful for validating required fields in inputs, a very common task.

function validate(){

var name_input = ‘Jimmy’;

var age_input;

return name_input && age_input;




} else {



// outputs fail

Code snippet is from boolean-operations.txt

NaN by definition means Not a Number. Try the following:

>typeof NaN


 Code snippet is from typeofNaN.txt

See any irony? This is just one of the many strange behaviors of the typeof operator.


JavaScript has the equality (==) and identity (===) operators. The == is dangerous, because it does type coercion to make comparisons. For example:

 > 1 == “1”;

Code snippet is from simple-comparison.txt

More than likely, this isn’t what you want. Hence, the === operator will return true if both the left- hand side and right-hand side really are identical.

> 1 === “1”;

Code snippet is from strict-comparison.txt

There’s also the equivalent != and !==. Always use === and !==.


The built-in Date object is created using the new operator and the Date() constructor function (more on prototypes and constructors later), and is used for date and time data, as you would suspect. Creating a new Date object without any parameters results in a Date object of the current date and time.

> var thisMoment = new Date();
> console.log(thisMoment);
Sun Jan 30 2011 21:37:19 GMT-0400 (AST)
> thisMoment.getFullYear();

Code snippet is from date.txt

Although Date is a convenient object, and it’s certainly useful to know it’s there, I highly recommend using the open source Date.js library for doing date/time arithmetic found at


Declaring a variable without giving it a value, or accessing a nonexistent object property, results in a type called undefined. Null is a built-in object, and indicates there is no value. Both convert to a false when doing comparison, but it’s best to avoid undefined. In many JavaScript interpreters, undefined is re-assignable, resulting in hackish code like the following:

undefined = true;


console.log(‘tricked you!’);


// output: tricked you!

Code snippet is from undefined-equals-true.txt

See 00 6/05/javascript-difference-between-null-and.html for a full explanation of the differences between null and undefined.

The following is a list of the different types found in JavaScript. Regular expressions, or RegEx, are beyond the scope of this tutorial.

  • Number
  • String
  • Boolean
  • Object
  • Function
  • Array
  • Date
  • RegEx
  • Null
  • Undefined

Some additional built-in error types are useful with try/catch statements. Creating an error object is usually done in conjunction with throw.


throw new Error(‘Something really bad happened’);

} catch(e){

console.log( + “: ” + e.message);


// Error: Something really bad happened

Code snippet is from try-catch.txt

The following list displays the different error types.

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError


Variables are declared by either assignment (implicit) or using the keyword var (explicit). If you declare a variable using var, it becomes permanent and cannot be deleted. You can declare a variable as many times as you desire without causing any errors. Uninitialized variables contain the special value undefined.

i = 0; // implicit declaration
var i = 0; // explicit declaration
var x; // undefined

Code snippet is from variable-declaration.txt

Scope refers to the visibility of a variable or object. Globals are visible anywhere in your application, whereas locals are visible only in the function in which they’re declared.

Implicitly declared variables always have global scope, even if declared inside a function body. To avoid problems, it’s suggested that you always use var when declaring variables. Douglas Crockford, the creator of JSLint, also suggests that you declare all your variables at the top of a given scope, to avoid redefinition problems. If you declare the same variable outside a function and inside, the local variable supersedes the outer variable, or hides it.

function where(){

var v1 = “local scope”;

v2 = “global scope”;



console.log( v2 );

console.log( v1 );

// result

global scope

ReferenceError: v1 is not defined

 Code snippet is from global-scope.txt

Variable names must start with a character letter, underscore, or dollar sign followed by zero or more alphanumeric characters, underscores, or dollar signs. Keywords cannot be used as a variable name.


Objects are collections of properties, each property having a name and value. Properties can contain any type except for undefined, and are assignable even after the object is created. Arrays, functions, and regular expressions are all objects. Numbers, strings, and Booleans are also objects, but they are immutable. You can instantiate objects in a couple ways. One is to use the new keyword:

var myObject = new Object();

Code snippet is from new-object.txt

The new keyword invokes a constructor function, or more commonly constructor. The constructor initializes the newly created object. The following code snippet shows a constructor for an object called Zombie, which initializes its property name and then instantiates a Zombie object using new. The this keyword refers to the current object, and it cannot be assigned a value, although you can save its value in another variable.

// constructor

function Zombie( name ){ = name;


var smallZombie = new Zombie(

Code snippet is from this.txt

A more convenient way to instantiate a new object is to use object literals; in this manner objects are more like hashes or associative arrays from other languages.

var myObject = {};

Sox var objectWithProperties = {

“propertyl”: “a string value”,

“myObjectAsProperty”: myObject


Code snippet is from object-literal.txt

Avoid using a trailing comma on the last value of your list of properties. It’s interpreted inconsistently across browsers. You can access an object’s properties by using either square brackets or the dot operator. The following code snippet shows both cases:


“a string value”


“a string value”

Code snippet is from property-lookups.txt

Using the former case allows you to use keywords for properties (not that I recommend that); the latter doesn’t. On the other hand, using the dot method is shorter. JSLint will encourage you to use the dot syntax when appropriate. Because properties can be objects, you can nest objects at an arbitrary level.

var species = {

‘mammals’ :   {

‘biped’: {

‘monkey’ :  ‘George’ ,

‘human’ :  ‘Tim’





Code snippet is from nested-objects.txt

JavaScript is a dynamic language, so to update a property just reassign its value. To remove a property from an object, use the delete operator. There’s no danger in deleting a nonexistent property. To access the properties of an object you can use the for…in loop as shown in the following code snippet:

var obj = {

‘propertyl’ : 1,

‘property2’ : 2


var i;

for( i in obj ){

console.log( i );




Code snippet is from for-in.txt

JavaScript uses prototypal inheritance; in other words, objects inherit directly from objects, and they create other objects. More concisely, an object inherits the properties of another object. There are no classes, a big difference as compared to languages like Java or C#. The prototype is a model for other objects.

This may sound difficult, but in practice, it’s much simpler than class/object-based inheritance. A built-in object, Object.prototype, is inherited by all other objects, and is at the top of the inheritance hierarchy. Each object in an inheritance tree is linked by the prototype property.

Property retrieval occurs through delegation. Upon attempting to retrieve a nonexistent property, JavaScript looks for the property from the prototype object. If it still fails to find the property, it runs up the prototype tree looking for the property, until it reaches the primordial Object .prototype. After that, if it still can’t find the property in question, the interpreter just gives up and returns an undefined.

Functions that are properties of objects are called methods, which are either added to an object by assignment to the prototype object, or directly. Methods always receive a free argument, bound in the function scope as this, which refers to the object the method was invoked from. The following code snippet shows an example of prototype-based inheritance. Behind the scenes, a Monster .prototype object is created.

function Monster( type ){

this.type = type;


Monster.prototype.getType = function(){

return this.type;


function Zombie( name ){ = name;


Zombie.prototype = new Monster();

Zombie.prototype.eatPeople = function(){

console.log( ‘tastes like chicken’ );


Code snippet is from prototype.txt

A reference is a pointer to the location of an object instance. Objects are reference types and because all objects are passed by reference, changing a property bound to a prototype changes the prototypes of all other objects based on that prototype, as demonstrated in the following code:

> smallZombie.eatPeople();

Tastes like chicken

> delete Zombie.prototype.eatPeople;


> smallZombie.eatPeople();

TypeError: Object #<a Zombie> has no method ‘eatPeople’

Code snippet is from prototype-demo.txt

When creating new objects, watch out for how you initialize them. The following code shows two variables that refer to the same object, although you might think you’re taking a shortcut:

// objl and obj2 reference the same object

var objl = obj2= {};

// objl and obj2 refer to different objects

var objl = {},

obj2 = {};

Code snippet is from object-trap.txt

Objects are self-aware, or in other words, know their own properties. To test for the existence of a property, use the hasOwnProperty() method, which returns a boolean value.

Global variables, as any programmer will tell you, should be avoided. There are a few ways to avoid cluttering the global namespace; one way is to use a single global variable that serves as the top-level object for all the methods and properties of your program or framework. By convention, namespaces use all capital letters, but beware that constants are usually written in caps as well. You learn much more about using objects for code organization in Chapter 10.



smallZombie : ‘Booger’,

largeZombie : ‘Bruce’


Code snippet is from simple-namespace.txt

Now your Zombies won’t clash with any other variables in the global namespace. The other way to minimize clutter is using closures, which you’ll explore in a bit.


Douglas Crockford, in his book JavaScript: the Good Parts calls, functions the “best thing about JavaScript.” He’s right. Once you truly understand them you’ll be certain to agree. The flexibility and power of JavaScript functions can’t be understated.

This is especially true when working with jQuery, a library that fully leverages the expressive power of JavaScript functions.

Basically defined, a function is a block that encapsulates a series of JavaScript statements. Functions can accept and return values. The following code sample shows a simple function statement that explicitly returns the value of a calculation.

function calc( x ){

return x*2;

console.log( calc( 10 ) )


Code snippet is from simple-function.txt

If a function doesn’t return a specific value, it returns undefined. The following code sample shows a function statement that omits a return value. It still performs its operations, adjusting the value of the variable x, but returns undefined when the return value is examined in the console.

var x = 2;

function calc( ){

x = x*2;


console.log( x )


console.log ( calc() );


Code snippet is from undefined-value.txt

This is where things get interesting. Unlike languages like C# and Java, however, JavaScript functions first-class objects. This means that JavaScript functions can be handled like any other JavaScript object. Functions can be assigned to a variable or stored in another data structure (such as an array or object); they can be passed as an argument to another function; they can be the return value of another function and can take the form of an anonymous function: a function not bound to an identifier at all. The following code shows a function expression assigned to a variable.

var calc = function(x){

return x*2;

calc( 5 );


Code snippet is from function-variable-assignment.txt

Using parentheses with the function name will pass the result of the executed function rather than the reference to the function.

var calc = function(x){

return x*2;

var calcValue = calc( 5 );

console.log( calcValue );


Code snippet is from function-variable-result.txt

For a jQuery developer, two other features of first-class functions are especially important. The first is the ability to pass functions as arguments to other functions. The second is the anonymous function. Combine these and you have one of the hallmarks of fluent jQuery code. jQuery wouldn’t be jQuery without the ability to pass function expressions into other functions on the fly. This will become especially clear when you learn about event handling in Chapter 5. Beyond events, jQuery is full of methods that accept function arguments.

The following code shows example of both of these important features. The function reporter accepts a function as an argument and logs the return value of the executed function argument. Additionally, two of the examples feature anonymous functions. The first is an anonymous function that contains no statements at all, but, as you’ve just learned, still returns undefined. The second is an anonymous function that returns the string “a simple string.”

function reporter( fn ){

console.log( “the return value of your function is “+ fn() );

reporter( function(){} );

the return value of your function is undefined

reporter( function(){ return “a simple string” } );

the return value of your function is a simple string

function calc() {

return 4 * 2


reporter( calc );

the return value of your function is 8

Code snippet is from function-arguments.txt

One especially important variation on the anonymous function is the “immediately-invoked function expression” (IIFE) or “Self-executing anonymous function.” Why two names? Read Ben Alman’s blog post for a well-thought out discussion of the name for this very common pattern: Whatever you decide to call it, this pattern is defined as a function expression wrapped in parentheses, and then immediately invoked. The simple trick of wrapping the function expression in parentheses forces the JavaScript engine to recognize the function(){} block as a function expression and not the beginning of a function statement. The following code sample illustrates this pattern with a simple example that accepts two values and simply adds them together.

(function( x,y ){

console.log( x+y );

})( 5,6 );


Code snippet is from iife.txt

Because it’s immediately invoked, this pattern is used to ensure that the execution context of the code block is as expected. This is best illustrated in one of the most important uses of this pattern. By passing in arguments to the function at execution you can “trap” variables in the closure created by the function. A closure is a function that “closes over” variables from the current execution context inside the body of a function. This is extremely powerful and you’ll see several real-world uses of this in Chapter 12, when you learn about some advanced jQuery plugin patterns. For now, the following code sample will illustrate a basic usage of this pattern. It will also introduce another interesting feature of JavaScript functions, the ability for a function to return another function.

In the sample, the IIFE is set to a variable, message. message returns another function that simply logs a message about the value of x. The interesting part is that when we pass in an initial value of x as an argument to the function, we capture that value within the closure created at the time of function execution. No matter what happens to x in the outer scope, the closure remembers the value of x from the time of the function’s execution.

var x = 42;

console.log( x );

Avwiabe fon var message = (function( x ){

return function() {

console.log( “x is ” + x );


})( x );


Code snippet is from captured-variables.txt

Even with just this simple introduction you should begin to see the power of JavaScript functions. In the sections that follow in this chapter and the chapters that follow you’ll learn even more about the power of functions.


Execution context is the object within which your code is executing. Access to context occurs through the this keyword, which refers to the object it resides within. In the current version of the language, if your code doesn’t reside in a custom object or function, it will then belong to the global context.

As a note, in future versions of the language, including “strict mode” a special subset of the language defined the 5th edition of the JavaScript standard available in a small subset of browsers, functions defined without specific context are bound to undefined as their this value.

The eval and setTimeout functions also have their own separate execution context.

> console.log(this);

[object DOMWindow]

 Code snippet is from this-value.txt

When execution of a function or method begins, JavaScript creates a new execution context and enters into that function’s execution context. When a function finishes executing and returns, control is relinquished back to the original execution context, and the current context is set up for garbage collection except in the case of a closure where the context persists.


When discussing scope it’s important to consider where a variable is defined as well as its lifetime. Where is the variable accessible? In the case of JavaScript, scope is maintained at the function level, not the block level. Hence, variables defined with the keyword var and parameters are visible only inside the function in question.

A nested function has access to its outer function’s variables, except for this and arguments. The mechanism through which a nested function continues to keep the references of its outer function even after the outer function finishes execution is called closure. Closures also help to reduce namespace pollution.

Each time an enclosed function is called, a new scope is created, although the code doesn’t change. The following code shows this behavior.

function getFunction(value){

return function(value){

return value;


var a = getFunction(),

b = getFunction(),
c = getFunction();

console.log(a === b);

Code snippet is from more-closures.txt

When defining a standalone function (not bound to any object), this is bound to the global namespace. As a direct result, when creating an inner function within a method, the inner function’s this variable is bound to the global namespace, not the method. To circumvent this situation, the enclosing method’s this variable is assigned to an intermediate variable called that, by convention.

obj = {};
obj.method = function(){

var that = this;
this.counter = 0;
var count = function(){

that.counter += 1;






Code snippet is from this-that.txt


There’s no official syntax for access levels in JavaScript, like the private or protected keywords provided in Java. By default, all members in an object are publicly accessible. But it’s possible to get the same effect of private and privileged properties. To achieve the effect of private methods and properties, use closures.

function TimeMachine(){

// private members

var destination = ‘October 5, 1955’;

// public members

this.getDestination= function(){

return destination;



var delorean = new TimeMachine();


// October 5, 1955

> console.log(deloreon.destination);

// undefined

Code snippet is from access-levels.txt

The method getDestination is a privileged method because it has access to private members of the TimeMachine. Meanwhile, the variable, destination, is “private” and its value is only accessible through the privileged method.


Just like the private and privileged access levels, JavaScript has no built-in syntax for packages. The module pattern is an easy and popular way to create self-contained, modularized code. To create a module, declare a namespace, bind an immediate function to it, and define any private and privileged members. Let’s rewrite the TimeMachine object.

// create namespace object


TIMEMACHINE. createDelorean = (function(){

// private

var destination = ”;

var model = ”;

var fuel = ”;

// public access methods

return {

// setters

setDestination: function(dest){

this.destination = dest;


setModel: function(model){

this.model = model;


setFuel: function(fuel){

this.fuel = fuel;

}, // getters

getDestination: function(){

return this.destination;


getModel: function(){

return this.model;


getFuel: function(){

return this.fuel;


// misc members toString : function(){

console.log( this.getModel() this.getFuel() + ‘

this.getFuel() + ’ – Headed: ’ + this.getDestination());


// init procedures go here



var myTimeMachine = TIMEMACHINE. createDelorean;

myTimeMachine.setModel(‘1985 Delorean’);


myTimeMachine.setDestination(‘October 5, 1955’);


1985 Delorean – Fuel Type: plutonium – Headed: October 5, 1955

Code snippet is from module.txt

This module has a factory function that returns an object with your public/private API. You’ll learn more about modules and using them with jQuery in Chapter 10.


Arrays are a special kind of object that works as an ordered collection of values, called elements. Each element has an index, or numeric position, within the array. You can mix and match different kinds of elements in an array. They don’t all have to be of the same type. Arrays, just like objects and functions, can also be nested arbitrarily.

As with regular objects, there are two ways to create an array. The first is using the Array() constructor:

var array1 = new Array(); // empty array
array1[0] = 1; // add a number to index 0
array1[1] = ‘a string’; // add a string to index 1

Code snippet is from array-constructor.txt

The second and much more common method for creating an array is using an array literal, which consists of brackets enclosing zero or more comma-separated values.

var niceArray = [1,2,3];

                                                                                                                                                                                          Code snippet is from array-literal.txt

Mixing array literals with object literals provides very powerful construct, and forms the basis for JavaScript Object Notation (JSON,) a popular data exchange format with implementations across many languages beyond JavaScript.

var myData = {

‘root’ : { 

: [1, 2, 3],

:  [‘a’, ‘b’, ‘c’],

:  [‘tomatoes’, ‘carrots’, ‘potatoes’]



Code snippet is from json.txt

Arrays contain a length property, which is always equal to the number of elements in the array minus one. Adding new elements to an array changes its length property as well. To remove elements from an array use the delete operator.

>var list = [1,  ‘2’, ‘blah’, {}];

>delete list[0]


,2,blah,[object Object]



Code snippet is from delete-operator.txt

Deleting an element does not change the length of the array, it just leaves a hole in the array.


JavaScript allows the facility for binding methods and other properties to built-in types, such as strings, numbers, and arrays. Strings, just like any other object, have prototypes. You can also augment String with convenience methods. For example, String has no method for converting the string “false” or “true” to a Boolean. You can add this capability as the following code demonstrates:

String.prototype.boolean = function() {

return “true” == this;


var t = ‘true’.boolean();

var f = ’false’.boolean();





Code snippet is from string-boolean.txt

Admittedly, it’s annoying to have to redundantly type prototype every time you want to add a method. Douglas Crockford has a neat bit of code for getting around this, which augments the Function.prototype with a method called, method (please pardon the redundancy.) This is shown in the following code sample.

Function.prototype.method = function(name, func){

this.prototype[name] = func;

return this;


Code snippet is from method-method.txt

Now you can rewrite the boolean method for strings:

String.method(‘boolean’, function(){

return “true” == this;


> “true”.boolean();


Code snippet is from newBoolean.txt

This technique is useful for writing a library of utility methods and including it in your projects.


This is a short list of things to do, and not to do, when developing JavaScript:

  •  Use parselnt() to convert a string to an integer, but make sure to always give the base. Better yet, use the unary + operator to convert a string to a number.

Good: parseInt(“010”, 10); // we know it’s base ten and not octal

Better: + “010” // simple and efficient

  Code snippet is from cool-conversions.txt

  •  Use the identity === operator to compare two values. This avoids unwanted type coercion.
  •  Don’t leave a trailing comma in an object definition literal, for example:

 var o = {

p1” : 1,

“p2” : 2, // very bad!


Code snippet is from trailing-comma.txt

  • The eval() function allows you to take a string and execute it as JavaScript code. Limit use of eval(); it opens up your code to all kinds of nasty security issues.
  • End your statements with a semicolon. This is particularly pertinent when minifying code.
  • Avoid global variables! Always declare variables using the keyword var. Wrap pieces of code inside anonymous functions to avoid name clashes, and use modules.
  • Use capital letters with a function meant to be used as a constructor with new, but don’t capitalize the first letter of any other function.
  • Don’t use the with statement. I didn’t explain what the with statement is, because you shouldn’t use it.
  • Create functions inside of loops sparingly. It’s extremely inefficient.


With the background you now possess on JavaScript, you can grasp a good deal about jQuery without even reading the docs. For example:





‘success’: function(){

// code here




Code snippet is from put-it-all-together.txt

Here you see many of the topics mentioned in this chapter: an object literal used to send a list of parameters, anonymous functions, or the single dollar sign ($) as a valid identifier. If you didn’t already know, $ is an alias for the jQuery core object. It’s safe to assume, without looking at a line of code, that internally jQuery is using closures to hide data.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *