Jeffrey van Binsbergen.nl

Awesome JavaScript Tricks

Just like C-Sharp, JavaScript has some unique tricks not known to everyone. In this article I'll share some of the tricks I know about JavaScript. Like everything with JavaScript, some tricks will require a recent version of your web browser but all tricks should work in all major browsers.

Object.defineProperty

This is a method available in all recent browsers (Firefox 4+, Chrome 5+, Safari 5.1+, Opera 11.6+, IE 9+) which allows you to do unique and awesome stuff with properties. For example you can use Getters and Setters:

var obj = {};

Object.defineProperty(obj, 'myprop', {
get: function() {
return myprop * 2;
},
set: function(value) {
alert('Setting value to '+value);
myprop = value;
}
});

obj.myprop = 5;
alert(obj.myprop); // 10

Another use is making a property read only and unchangeable (not even by another defineProperty call).

var obj = {};
obj.theAnswer = 42;

Object.defineProperty(obj, 'theAnswer', {
writable: false, // This makes the value read only
configurable: false // This makes this property undeletable
});

obj.theAnswer = 5;
alert(obj.theAnswer); // 42

The defineProperty method can be useful when making a custom elements, which can act just like a native element does (for example, directly updating the UI after you do: customElement.value = "123";).

Arguments as array

You can use the arguments keyword to get all parameters. Use this to make functions which accepts a unspecified range of arguments.

function printf(text) {
var i = 0, args = Array.prototype.slice.call(arguments); // Turn the arguments-object into a normal array

text = text.replace(/\%s/g, function(a) {
return args[++i];
});

return text;
}

alert(printf("Hello %s! Your score is %s", "Mr Anderson", 1337));
// Hello Mr Anderson! Your score is 1337

edit: Changed [].slice to Array.prototype.slice.call after someone pointed out it had some issues with Chrome

Override default methods

Like in every programming language, Objects in JavaScript have a few default methods you can override.

var TestObject =  function() {
this.valueOf = function() {
return 42;
};
this.toString = function() {
return "I am a test object";
};
};

var obj = new TestObject();
alert(obj == 42); // true
alert(obj); // I am a test object

This can be useful when making objects comparable to each other or making your code easier to debug (You can get a nice textual representation of your object instead of just a [object] text).

Function methods

In JavaScript, there are quite a few ways of working with functions. A more unknown feature are the methods available at functions. For example: By using the method apply you can call a function and give the parameters as an array, you can also change the 'this' scope of that function.

alert.apply(this, ["I am a message"]); // Shows 'I am a message'

The bind method can also be quite useful, especially when working with timeouts and intervals.

var TestObject = function() {
this.someValue = 100;
this.doSomething = function() {
alert(this.someValue);
};

setTimeout(this.doSomething, 1000); // undefined
setTimeout(this.doSomething.bind(this), 2000); // 100
}

new TestObject();

In Firefox, you can also retrieve the source code of a function:

function myFunction() {
return 1337;
}
alert(myFunction.toSource()); // Shows the function defined above including source

With keyword

Supported by pretty much every browser, but not recommended for use as it can causes a lot of confusion. Still for the sake of informing I'll include it in this overview. The With keyword allows you to use properties and functions from an object, without putting the object name in the front (As if all properties and functions are global).

with(document) {    
with(body) { // document.body
var textNode = createTextNode("Bla"); // document.createTextNode
appendChild(textNode); // document.body.appendChild
}
}

It also works when eval-ing code, Which can be useful if you want to support scripts with short function names. Note that it does not limit the script! Every other function will still be available. It can also be used to temporarily override global functions and properties:

var obj = {
alert: function() {}
};
with (obj) {
alert('This alert is not visible');
}

Comma operator

Next to all the more common operators, JavaScript has another operator: The Comma operator. The comma operator allows you to do some actions before returning a value. This can be useful in places where JavaScript only expects a single value. It can be compared to the && and || operators, but with the comma-operator all expresssions are always executed. Example:

function IsAlwaysFalse() {
return false;
}

function IsAlwaysTrue() {
return true;
}

// Continues when the value is not False/Null/0/Undefined
alert(IsAlwaysFalse() && 42); // False
alert(IsAlwaysTrue() && 42); // 42

// Continues when the value is False/Null/0/Undefined
alert(IsAlwaysFalse() || 42); // 42
alert(IsAlwaysTrue() || 42); // True

// Always continues
alert((IsAlwaysFalse(), 42)); // 42
alert((IsAlwaysTrue(), 42)); // 42

Scope labels

It is possible to put code in a specific scope and name the scope. By doing so it allows breaking out of a specific scope using the 'break' keyword.

myLabel: {
alert('I am shown :)');
break myLabel;
alert('I'm not :(');
}

Multiple lines

And a small trick to end this article with: Use the \ character to allow using multiple lines in your string definitions. Just put them on the end of the line like this:

var x = "abc\
def";

Note that it doesn't actually add a linebreak in the string. You still have to use \r\n for that to happen.

Conclusion

Like C-Sharp, JavaScript has a lot of hidden gems. This is just a small selection of the lesser known things I know about. Do you have some awesome tricks in JavaScript worth a mention? Let me know!

Show all articles