I am Hack Sparrow
Captain of the Internets.

Archive for February, 2010

JavaScript Array Splice – Syntax and Examples

The JavaScript splice method is a multi-purpose tool. The syntax of the Array method is as follows. Array.splice(startIndex[, endIndex, [item1[, item2, item3, ...]]]) The following examples demonstrate the way the splice method can be used. ...

Should you use “var” for initializing counter variables in For / For Each loops?

To var, or not to var, that is the question. - Bill Shakespeare What difference does the use of var in the loop constructs make? (more…) ...

Associative Arrays in JavaScript – There’s None!

That sounds strange, but it's true. JavaScript does not have associative arrays. An associative array is a kind of array which uses strings as indices, instead of numerical ones. Take a look at the code below. [code] var hero = new Array(); hero['name'] = 'batman'; hero['id'] = 'Bruce Wayne'; hero['city'] = 'Gotham City'; for (var p in hero) { console.log(p+': '+hero[p]); } console.log(hero['id']); console.log( ...

Truncating an Array in JavaScript

There are two ways of truncating an array in JavaScript. One takes advantage of the fact that the length property of the object. (mor ...

Check if a variable is defined in JavaScript

The following example shows how to check if a variable is defined or not in JavaScript. Using typeof Operator [js] if (typeof username == 'undefined') console.log('Variable is not defined'); else console.log('Variable is defined'); [/js] Note that undefined is quoted in the above code snippet. It won't work if it's not quoted. Try it. ...