tgvashworth

useful js: snippets

20 Dec 2012

Here’s some Javascript snippets I find myself using every day. You should be good to drop them into your page, but if you’ve not familiar with a particular technique then it’s always good idea to read up on it before using it. I’ve provided links where I can.

Note: Some snippets use parts of Javascript ES5. To get this stuff in older browsers (< IE9), use the ES5 Shim.

Log arguments

Need to check the all the arguments coming into a function? No probs: use call and apply.

console.log.apply(console, arguments);

Set ‘this’ in setTimeout

Want to make sure of the value of this is the same inside a setTimeout callback? Use bind.

setTimeout(function () {
  // Do yaw thang...
}.bind(this), 1000);

Call a function from setTimeout

Do you do this much?

setTimeout(function () {
  do_something_with(x, y);
}, 1000);

Try this (again with bind):

setTimeout(do_something_with.bind(this, x, y), 1000);

Filter items from an array

Need to make sure all items in an array pass certain criteria? Try filter. If you return true from the callback the item is kept, otherwise it’s scrapped.

var evens = [1,2,3,4].filter(function (val) {
  return (val % 2 === 0);
});

Operate on an array

Want to carry out an operation on every item in an array? Take a look at map.

var squares = [1,2,3,4].map(function (val) {
  return val * val;
});

Easy function defaults

You’ve got a function that can takes an optional argument, and you want to provide a default.

Use the or operator! (Also, get nerdy)

var say = function (word) {
  word = word || "Hello!";
  console.log(word);
};

say(); // logs "Hello!"
say("World!"); // logs "World!"

Further reading

The MDN Docs are great, as is Nicholas Zakas’ blog if you want to go into exra detail, and Paul Irish’s stuff.