Thursday 24 February 2011

The "in" operator

Did you know that there is a in operator in JavaScript? 
This operator checks if a key exists in an object and it can be used very simple like below:
var o = { 8:2008, 9:2009, 10:2010 };
8 in o; // true, key 8 exists with a value of 2008
1 in o; // false, the key 1 does not exist in o

Thursday 10 February 2011

Extending the JavaScript language

Something useful i found searching the internet is that you can extend existing JavaScript functions by using Extension methods. In this example an array class is extended with a contains-method:
Array.prototype.contains = function(value) {
for (var i = 0; i < this.length; i++)
if (this[i] == value) return true;
return false;
}
We can then use the extension method as follows
var myArray = ["a", "b", "c"];
myArray.contains("c"); // true