I am Hack Sparrow
Captain of the Internets.

Archive for JavaScript

JavaScript – Check Object Property is Defined

Probably you know how to check if a variable is defined in JavaScript or not (without crashing your app with a fatal ReferenceError). In case you didn't know already, here is a refresher. Wrong: [code] if (username == undefined) { console.log('username missing'); } else { console.log(username); } [/code] Right: [code] if (typeof username === 'undefined') { console.log('username missing'); ...

JavaScript – Convert arguments to Array

All JavaScript functions have a local variable called arguments, which is a list of arguments that were passed to the executing function. The first argument can be accessed as arguments[0], the second one as arguments[1] etc. To find out the numbers of arguments you can do arguments.length. You can see arguments is a lot like an array. I say it is a lot like a ...

JavaScript slice() with Examples

Are you familiar with the JavaScript array slice() method? As you are on this page, I will assume you are not. The slice() method of arrays is a useful function to 'chop off' items from an array. 'Chopping off' better describes the functionality than 'slicing', but probably they settled on slice() because it sound and looks more 'professional' than chopoff(). Array.slice() is a m ...

JavaScript – .apply and .call

Maybe you have heard about them, maybe you are new to them, but the apply and call JavaScript functions are one of the less encountered and less well understood aspects of JavaScript - primarily because of their unfamiliarity. Why are they unfamiliar? Most of the learning materials (tutorials and books) available for JavaScript tend to teach JavaScript in the C/Java mindset. Most JavaScript beginners endeavor to find out the c ...

JavaScript – Check Object Types

There are times when you want to know the object type of an instance in JavaScript, whether it is an Array, or a Function, or an Object, a String etc. There are two flavors to doing that, one involves the use of the instanceof operator, the other involves stringification of the object's prototype. Follow the examples below, I show both the techniques. First create these variables: [code] var a = []; var o = {}; var s = ''; var n = 42; var f = function() {}; ...