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.
Set ‘this’ in setTimeout
Want to make sure of the value of this
is the same inside a setTimeout
callback? Use bind.
Call a function from setTimeout
Do you do this much?
Try this (again with bind):
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.
Operate on an array
Want to carry out an operation on every item in an array? Take a look at map.
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)
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.