Through fire and flames, I’ve learned quite a few JavaScript techniques that have assisted in improving productivity, code quality, and code maintainability. Although simple in nature, I’d like to share the five techniques that I’ve found most beneficial when writing JavaScript:

1. Closures

A closure, in its most basic form, looks like a function within a function. This is a powerful concept because all local variables inside of an inner function can be relatively accessed after that function has returned. I like to think of closures as a particular scope’s “save state”. Free variables contained within closures are remembered, even after that function is returned. Closures are great because they provide scope to your functions and help protect sensitive areas of code.

Closures are used all over the place in JavaScript frameworks — probably in many places you’re not even aware of. It’s important to know what a closure is, but even more important to know how to use it. One of the most frequently used closure patterns is the Immediately-Invoked Function Expression. You will often see this expression where protecting scope is imperative.

An object literal is a custom object defined in your code. Object literals are used in several ways, such as: containing multiple variables without polluting the global namespace, creating API objects, and passing neatly mapped data into a function. Here are examples of object literals in action:

Using object literals to pass data to a method is helpful when there are multiple arguments. Since object literals act as key-value stores, they can be passed in any order, allowing the API’s method to scale without updating each callee instance ( just be sure to validate object existence on required keys ).

3. Namespaced Application Objects

One of the great things about JavaScript is its ability to be written in many ways. However; this can also be a great pitfall if the author does not keep their code structured well. Globally namespacing an application object helps keep all system utilities and methods organized and easy to work with.

( function ( window, undefined ) {

var APP = {

init: function () {

console.log( APP.pets, APP.favorite.color, APP.favorite.number );

},

pets: [ “cat”, “dog”, “fish” ],

favorite: {

color: “blue”,

number: 55

}

}

// attaching this object to the global namespace allows attributes to be accessed

// outside the scope of this closure – some like to emulate the concept of “private” methods

// by not attaching those parts of the application object to the global scope

Problems are easily solved when enough data is provided regarding the issue. Browser development tools provide a console object and interface that can process data and browser information which is priceless when fixing JavaScript bugs. Logging data is a crucial tactic used in every programming language, so knowing how to use the console is necessary. I use the developer tools bundled in Google Chrome ( mostly because the V8 JavaScript engine is ridiculously fast ). Reading up on your dev tools’ abilities can drastically increase your productivity.

Test Driven Development is an essential part of our process at QuickLeft. Most developers have some experience in testing code, but are they actually test driving it? Test driving your JavaScript results in cleaner, more stable code. JavaScript can be hard to write in an organized manner. Frameworks like jQuery and Prototype make it very easy to develop code soup. Every large JavaScript project I’ve seen that isn’t test driven ends up in a big mess of bind events, meaningless closures, and random half-baked functions that don’t work in certain contexts. These inefficiencies often bloat the project budget and bug list significantly. Although the benefits of testing are sometimes argued against, there is no supportive defense that outweighs the amount of structure and stability test driving your JavaScript will enforce.

Not all tests are created equal. It is very important to make sure your tests cover the right functionality. Different project types call for different testing methodologies. In an event-driven application, any function that could be used from more than one context should be abstracted from it’s origin into a helper or API method. Test driving these methods help insure stability from an external context, but more importantly, it helps force the developer to write scalable and well structured code.

If you want to try TDD but don’t know where to get started, I would reccomend playing with Jasmine, QUnit, or PhantomJS:

Checking types in Javascript is well known as a pretty unreliable process.
Good old typeof operator is often useless when it comes to certain types of values:

typeof null; // "object"
typeof []; // "object"

People often expect to see something like “null” in the former check and something like “array” in the latter one.
Fortunately, checking for null is not that hard, despite useless typeof, and is usually accomplished by strict-comparing value to null:

value === null;

Checking for arrays, on the other hand, is a somewhat tricky business. There are usually two schools of thought – using instanceof operator (or checking object’s constructor property) and the-duck-typing way – checking for presence (or types) of certain set of properties (which are known to be present in array objects).

Obviously, both ways have their pros and cons.

1) `instanceof` operator / `constructor` property

instanceof operator essentially checks whether anything from left-hand object’s prototype chain is the same object as what’s referenced by prototype property of right-hand object. It sounds somewhat complicated but is easily understood from a simple example:

var arr = [];
arr instanceof Array; // true

This statement returns `true` because Array.prototype (being a prototype property of a right-hand object) references the same object as an internal [[Prototype]] of left-hand object ([[Prototype]] is “visible” via arr.__proto__ in clients that have __proto__ extension). An alternative constructor check, which I mentioned earlier, would usually look like:

var arr = [];
arr.constructor == Array; // true

Both instanceof and constructor look very innocent and seem like great ways to check if an object is an array. If I remember correctly, latest jQuery is using constructor:

The problems arise when it comes to scripting in multi-frame DOM environments. In a nutshell, Array objects created within one iframe do not share [[Prototype]]’s with arrays created within another iframe. Their constructors are different objects and so both instanceof and constructor checks fail:

By “fixing” multi-frame “problem”, this naive approach fails short in some of the trivial cases. If you were ever to have an object with splice and join properties, Object.isArray would obviously detect that object as being an Array:

var testee = { splice: 1, join: 2 };
Object.isArray(testee); // true

Back in June, I was reading ECMA-262 specs and noticed that there was an easy way to get value of an internal [[Class]] property that every native object has. Object.prototype.toString was defined like so:

Object.prototype.toString( )
When the toString method is called, the following steps are taken:
1. Get the [[Class]] property of this object.
2. Compute a string value by concatenating the three strings “[object “, Result (1), and “]“.
3. Return Result (2)

Contrary to Function.prototype.toString which is implementation dependent and is NOT recommended to be relied upon, Object.prototype.toString has a clearly defined behavior for all native objects.

15.3.4.2 Function.prototype.toString()
An implementation-dependent representation of the function is returned. This representation has the syntax of a FunctionDeclaration. Note in particular that the use and placement of white space, line terminators, and semicolons within the representation string is implementation-dependent.

A couple of weeks ago, though, someone created a ticket for Prototype.js – proposing an Object.isDate method. An implementation used constructor check and so was vulnerable to cross-frame issues. This is when I remembered about getClass and its possible usage in isArray, isDate and other similar methods.

Specs mention that:

15.4.2.1 new Array([ item0[, item1 [,…]]])
…
The [[Class]] property of the newly constructed object is set to “Array”.
…

The solution is not dependent on frames (since it checks internal [[Class]]) and is more robust than duck-typing approach. I have tested it on a handful of browsers (including some archaic and mobile ones) and was happy to find that all of them are indeed compliant in this regard.

Let’s hope this little “trick” serves as a remedy to cross-frame issues that authors struggle to find workarounds for : )

Working with JavaScript’s typeof operator is a bit like operating a clapped-out old car (or an early model Dell Inspiron). It gets the job done (mostly) and you learn to work around the quirks – but you probably aspire to something better.

In this article I’ll give a brief overview of typeof before introducing a tiny new function which is a fully-loaded, more reliable alternative that works directly with the language internals.

The typeOf Operator

How is it used?

Since typeof is a unary operator, the operand follows the operator. No additional punctuation is required.

typeof2 //"number"

typeof"belladonna"//"string"

But it works when I call it as a function?

The typeof operator is not a function. You can surround the operand with parentheses so that the expression looks like a function call, but the parentheses will simply act as a grouping operator (second only to the comma operator in the obscurity pecking order!). In fact you can decorate the operand with all manner of punctuation without derailing the operator.

typeof(2) //"number"

typeof(2) //"number"

typeof("a", 3) //"number"

typeof(1 + 1) //"number"

What does it return?

The returned value is a somewhat arbitrary representation of the operand’s type. The table below (based on the one in the ES5 spec) provides a summary:

Type of val

Result

Undefined

“undefined“

Null

“object“

Boolean

“boolean“

Number

“number“

String

“string“

Object (native and not callable)

“object“

Object (native or host and
callable)

“function“

Object (host and not
callable)

Implementation-defined

What’s wrong with typeof?

The most glaring issue is that typeof null returns “object”. It’s simply a mistake. There’s talk of fixing it in the next version of the ECMAScript specification, although this would undoubtedly introduce backwards compatibility issues.

1

vara;

2

typeofa; //"undefined"

3

typeofb; //"undefined"

4

alert(a); //undefined

5

alert(b); //ReferenceError

Other than that, typeof is just not very discriminating. When typeof is applied to any object type other than Function, it returns “object”. It does not distinguish between generic objects and the other built-in types (Array, Arguments, Date, JSON, RegExp, Math, Error, and the primitive wrapper objects Number, Boolean and String).

Oh and you’ll hear folks complaining about this…

typeofNaN //"number"

…but that’s not the fault of the typeof operator since the standard clearly states that NaN is indeed a number.

A Better Way?

[[Class]]

Every JavaScript object has an internal property known as [[Class]] (The ES5 spec uses the double square bracket notation to represent internal properties, i.e. abstract properties used to specify the behavior of JavaScript engines). According to ES5, [[Class]] is “a String value indicating a specification defined classification of objects”. To you and me, that means each built-in object type has a unique non-editable, standards-enforced value for its [[Class]] property. This could be really useful if only we could get at the [[Class]] property…

Object.prototype.toString

…and it turns out we can. Take a look at the ES 5 specification for Object.prototype.toString…

Let O be the result of calling ToObject passing the this value as the argument.

Let class be the value of the [[Class]] internal property of O.

Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

In short, the default toString function of Object returns a string with the following format…

…fortunately we can use the call function to force the generic toString function upon them…

1

Object.prototype.toString.call([1,2,3]); //"[object Array]"

2

3

Object.prototype.toString.call(newDate); //"[object Date]"

4

5

Object.prototype.toString.call(/a-z/); //"[object RegExp]"

Introducing the toType function

We can take this technique, add a drop of regEx, and create a tiny function – a new and improved version of the typeOf operator…

1

vartoType = function(obj) {

2

return({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()

3

}

(since an new, generic object will always use the toString function defined by Object.prototype we can safely use ({}).toString as an abbreviation for Object.prototype.toString)

Let’s try it out…

01

toType({a: 4}); //"object"

02

toType([1, 2, 3]); //"array"

03

(function() {console.log(toType(arguments))})(); //arguments

04

toType(newReferenceError); //"error"

05

toType(newDate); //"date"

06

toType(/a-z/); //"regexp"

07

toType(Math); //"math"

08

toType(JSON); //"json"

09

toType(newNumber(4)); //"number"

10

toType(newString("abc")); //"string"

11

toType(newBoolean(true)); //"boolean"

..and now we’ll run the same tests with the typeof operator (and try not to gloat) …

01

typeof{a: 4}; //"object"

02

typeof[1, 2, 3]; //"object"

03

(function() {console.log(typeofarguments)})(); //object

04

typeofnewReferenceError; //"object"

05

typeofnewDate; //"object"

06

typeof/a-z/; //"object"

07

typeofMath; //"object"

08

typeofJSON; //"object"

09

typeofnewNumber(4); //"object"

10

typeofnewString("abc"); //"object"

11

typeofnewBoolean(true); //"object"

Compare to duck-typing

Duck-typing checks the characteristics of an object against a list of known attributes for a given type (walks like a duck, talks like a duck…). Because of the limited usefulness of the typeof operator, duck-typing is popular in JavaScript. Its also error-prone. For example the arguments object of a Function has a length property and numerically indexed elements, but it is still not an Array.

Using toType is a reliable and easy alternative to duck-typing. Reliable because it talks directly to the internal property of the object, which is set by the browser engine and is not editable; easy because its a three-word check.

Here’s an illustrative example – a snippet which defines a non-compliant JSON object. The jsonParseIt function accepts a function as its argument, which it can use to test the veracity of the JSON object before using it to parse a JSON string….

Could toType reliably protect against the malevolent swapping of built-in JavaScript objects with impostors? Probably not, since the perpetrator could presumably also swap the toType function. A more secure test might call ({}).toString directly…

function() { return({}).toString.call(JSON).indexOf("json") > -1 }

..though even this would fail if Object.prototype.toString was itself maliciously re-written. Still each additional defense helps.

Compare to instanceof

The instanceof operator tests the prototype chain of the first operand for the presence of the prototype property of the second operand (the second operand is expected to be a constructor, and a TypeError will be thrown if it is not a Function):

1

newDate instanceofDate; //true

2

3

[1,2,3] instanceofArray; //true

4

5

functionCustomType() {};

6

newCustomType instanceofCustomType; //true

On the face of it this seems to hold promise of a nice type-checker for built-ins, however there are at least two snags with this approach:

1. Several built in objects (Math, JSON and arguments) do not have associated constructor objects – so they cannot be type-checked with the instanceof operator.

Math instanceofMath //TypeError

2. As @kangax and others have pointed out, a window can comprise multiple frames, which means multiple global contexts and therefore multiple constructors for each type. In such an environment, a given object type is not guaranteed to be an instanceof of a given constructor….

1

variFrame = document.createElement('IFRAME');

2

document.body.appendChild(iFrame);

3

4

varIFrameArray = window.frames[1].Array;

5

vararray = newIFrameArray();

6

7

array instanceofArray; //false

8

array instanceofIFrameArray; //true;

Type-checking host objects

Host objects are browser-created objects that are not specified by the ES5 standard. All DOM elements and global functions are host objects. ES5 declines to specify a return value for typeof when applied to host objects, neither does it suggest a value for the [[Class]] property of host objects. The upshot is that cross-browser type-checking of host objects is generally not reliable:

The most dependable cross-browser test for an element might be to check for the existence of a nodeType property…

functionisElement(obj) {

returnobj.nodeType;

}

…but that’s duck-typing so there are no guarantees

Where should a toType function live?

For brevity, my examples define toType as a global function. Extending Object.prototype will get you thrown to the dragons – my preference would be to extend Object directly, which mirrors the convention established by ES5 (and prototype.js before that).

More precisely it is the call to toType that throws the error, not the function itself. The only guard against that (as with calls to any function) is to practice good code hygiene…

window.fff && Object.toType(fff);

Wrap Up

OK I’ve babbled on for far longer than I intended to – so congratulations if you made it to here, I hope you found it useful. I covered a lot of ground and probably made some mistakes – please feel free to let me know about them. Also I’d love to hear about other people’s adventures in type-checking.

Part one, posted last week, explored a few different ways of de-cluttering your JavaScript, and, in the process, making it more readable.

Some developers don’t like the idea of using a language’s more idiosyncratic features because it does, potentially, make your code less readable in the eyes of those who haven’t learned the language properly. I think it’s still up for debate. While you’re pondering that, part II awaits…

Looping

It’s something we barely think about but JavaScript’s expressive diversity allows us to invent new patterns for looping. First, there’s the standard:

for (var i = 0; i < array.length; i++) {}

This is conventional and will be known to developers coming from any language. There’s nothing inherently wrong with it. That said, for me, it’s not ideal.

The first improvement I usually make is to cache the length property of the array:

for (var i = 0, l = array.length; i < l; i++) {}

This doesn’t make it shorter, but it does make it more efficient, although marginally so…

Another change we can make is to combine the iteration expression (i++) and the conditional expression (i < l), like so:

for (var i = -1, l = array.length; ++i < l;) {}

Notice that we’re starting with an index of -1, but won’t worry because before the loop’s body runs, the conditional expression is run, and in the above code, the conditional expression is iterating the index and testing it against the length all in one.

It’s important to note that the prefix increment/decrement operators (++i/--i) return the changed value, while the postfix increment/decrement operators (i++/i--) return the old value. To make this clearer:

Yesterday’s post on truthy & falsey bears some relevance here. The expression el=elements[++i] will return the value of elements[++i]. If this value is falsey the loop will not continue. An element list is full of truthy values (objects). We don’t need to be worried about falsey values. Note that in this approach, you may be sacrificing performance for terseness.

In many situations, we do want to iterate over falsey values too, e.g.

var myArray = [1, 2, 3, null, 8, 54, null, 0, 32];

With something like this it would be best to use the traditional i<length conditional expression, but if you’re so inclined feel free to mix the conditional and iteration expressions together like shown further up (++i<l).

If we were feeling a bit crazy, we could combine everything — iteration, conditional test, and assignment of indexed value — in a single expression:

Here we used the useful comma operator which always returns its right-hand operand. In this example we used it to make sure that i < l is what the condition expression returns. Before the comma we’re assigning the value at the iterated index within the array.

I don’t really suggest doing all of this in one line, and to be honest, there’s nothing wrong with conventional looping structures. What I am trying to put across is how much expressive diversity JavaScript provides.

Assignments

Assignments are expressions too, so you can slot them in wherever you want:

var a = 1;
alert(a = 2); // alerts 2
alert(a); // alerts 2

An assignment operator will always return whatever is on its right-hand side. Be careful with slotting in assignment expressions wherever you want though, because they can be misconstrued for equality operators. For example:

var match;
if (match = '1/2/3'.match(/\d/)) {
//...
}

To some, upon initial inspection, it may appear that we’re testing match for equality against '1/2/3'.match(/\d/) when in fact the latter is being assigned to the former, and the if statement will run if the assignment expression returns a truthy value (i.e. if its right-hand side operand is truthy).

Saving references

Property lookup can be verbose and inefficient. To save space and to benefit performance it’s common to save references and access those properties via the new reference instead of having to evaluate the entire expression every time you want the nested value:

IMPORTANT: It’s important to note that, when you assign a member function (that is, a function that is a property of an object) you are de-binding its this value, i.e. the context in which it runs. Here’s an example:

De-binding the fn method will make its context the global (window) object instead of the obj which we defined, so when our fn function looks for its `this.value` it won’t find it (because this is the window, which doesn’t have `value` defined).

End of part 2

Before we continue with the “Terse JavaScript 101″ series, we’re going to take a break and explore, in detail, truthy and falsey.

These are fundamental topics which I should have covered in more detail yesterday. There is copious information on this elsewhere online, so don’t feel limited to this post in your study.

Truthy: Something which evaluates to TRUE.Falsey: Something which evaluates to FALSE.

It’s mostly logical. One (1) is truthy, Zero (0) is falsey. An object of any kind (including functions, arrays, RegExp objects, etc.) is always truthy. The easiest way to determine if something is truthy is to determine that it’s not falsey. There are only five falsey values in JavaScript:

undefined, null, NaN, 0, "" (empty string), and false, of course.

Note: It is possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, which will make it truthy. For example, 0 (zero) is falsey, but new Number(0) is truthy. A scarier example is new Boolean(false) which is also truthy! Be careful. Only very rarely should you need to explicitly wrap primitives.

Why should you care what’s truthy and what’s falsey?

A value’s truthi’ness determines what it will evaluate to in logical expressions. For example:

if (0) {
alert('ALERT');
}

We know that the alert() call will never run, because 0, being a falsey value, doesn’t satisfy the if statement’s condition — i.e. to run only if the passed expression is NOT falsey.

The result is false if the argument is +0, -0, or NaN; otherwise the result is true.

String

The result is false if the argument is the empty string (its length is zero); otherwise the result is true.

Object

true

I hope this has made it clear enough.

Enough of the spec!

We now know what happens when we pass something as an if statement’s expression (if(..this bit..){}), but how much relevance does truthy and falsey have in other logical contexts? Well, a lot.

Let’s explore the basic if statement one last time though:

if (X) {
// If this code runs, what have we proven about X?
alert(123);
}

If 123 is alerted what can we say (for sure) about X? We can definitely say that it is NOT one of: undefined, null, NaN, 0, "" (empty string), or false. We can therefore say that X is truthy. It might be the literal value true, a number that’s not zero, an array, a function, etc.

Remember, everything in JavaScript that isn’t a primative value can be considered an object. Functions are objects. Arrays are objects. And all objects are truthy.

el is not a boolean, it’s just an object (in this case, a DOM Element object). The if block only executes if its expression is truthy. We could be more explicit though. The getElementById function returns null if it doesn’t find the element, so we could do:

There’s usually little advantage in explicitly stating the falsey value that you’re looking for. Sometimes, you might want to guard against a null or an undefined but allow false, for example. In such circumstances, obviously, use the explicit syntax (strict equality and strict inequality operators – ===/!==).

The ToBoolean thing that we referenced above happens in all logical contexts in JavaScript. For example, the && (logical AND) operator:

0 && alert(0);
1 && alert(1);

In this case, only 1 will be alerted, since zero is falsey and therefore does not satisfy the &&‘s desire for a left-hand truthy operand. The logical AND operator will only evaluate its right-hand operand if its left-hand operand is truthy.

Further up we checked that the return value of getElementById wasn’t null by simply checking if it was truthy. If el was truthy then we knew the element existed in the DOM and we could begin to interact with it programatically.

We use a similar concept with object access.

alert(foo.bar); // Alerting the value of the 'bar' property of 'foo'

The only values that will throw an error when you try to access a property are null and undefined. So, if foo is truthy then we can safely attempt to access it’s bar property without worrying about exceptions being thrown.

if (foo) {
alert(foo.bar);
}

Assume carefully

With our if statement we have only proven that foo is truthy. It still might not be the object we expect. This is something to consider. Normally though, it’s safe enough to suppose that if some obscurely named value is not falsey, it’ll be the truthy value you desire and not something you don’t want.

If element has a property addEventListener and its value is something truthy, it must be a function, so we’ll call it.

If it doesn’t exist then attachEvent must exist and must be a function.

The code above happens to be working around old IE versions that don’t have the W3C DOM Event method, addEventListener. The assumptions I’m making are considered safe in the environments that I intend my web app to operate in, but they may not be safe assumptions in other environments, so it’s important to be wary of the fact that: just because something is truthy doesn’t mean it’s the truthy value you happen to be looking for (the same goes for falsi’ness).

It’s common to attempt deep object access using the following structure:

a && a.b && a.b.c && a.b.c();

Make sure a is truthy.

Make sure a.b is truthy (and thus exists).

Make sure a.b.c is truthy (and thus exists).

Call a.b.c.

Again, we’re making assumptions, but we already knew that. This structure is very useful, although too much of it can make your code bloated, so maybe consider other options. For one: consider what you CAN safely assume. In some instances, you may be able to do this:

a && a.b.c();

Make sure a is truthy.

Call a.b.c.

In this example, we’ve determined that it is safe to assume that if a is truthy, it is the very object that we’re looking for, and therefore must have a minimum structure of: a={b:{c:function(){...}}}. We’re aware of our own data structure so can make this assumption.

Explicit booleans

You might be left wondering why we even bother having proper boolean values in JavaScript if we can get around quite easily with our other truthy and falsey values. And it’s true, we could manage without these booleans, and we rarely check for them explicitly. We usually just do something like:

if (foo.isAFoo()) {
// ...
}

foo.isAFoo() could return any truthy value (not necessarily the boolean of true) and it would make no difference to the code execution.

But, it is important, in many situations, to be explicit in our intentions. So we should insist on using real booleans when there is a binary decision to make (two possible values).

To cast a value to its boolean representation, we can just use ToBoolean. We can indirectly use this internal method by calling the Boolean constructor as a function:

Boolean(0); // => false

It will return a boolean value — either true or false, and is a really quick way of finding out whether a value is truthy of falsey:

[complete!]

While some folk will argue that verbose code aids readability, I think almost the opposite, and in this post I’m going to list some basic tips for minimising redundant clutter in your code. JavaScript is a fun language at its core — it’s worth learning the tiny details.

I hope this post is useful to someone. I wrote it not for beginners (although it will be helpful to them), but for all those people writing JavaScript on a daily basis yet haven’t been afforded the time/motivation to get to know the language properly.

new Object()

Array literal, object literal, regular expression literal. They rock. There’s usually no need to use the constructor functions when literals are available (please see the note below though).

Note: There are situations when calling Array or RegExp directly can be useful. In such situations, you needn’t bother with the new operator. Array(1,2,3) will produce the same as new Array(1,2,3). Calling RegExp directly can be useful for dynamically building a regular expression from various strings.

Calling a constructor

If you’re not passing any arguments then the parenthesis are not required. E.g.

var a = new Animal();

… and this becomes:

var a = new Animal;

Petty, perhaps. Still worth knowing though.

var;var;var

Quick and easy. Less of this:

var fun = 123;
var tun = 456;
var run = 789;

And more of this:

var fun = 123,
tun = 456,
run = 789;

This is why you should use a tab width of FOUR (or 4 spaces).

Undefined & Null

The following is universally true in JavaScript (assuming undefined hasn’t been mutilated):

undefined == null

“So what?”, you say? Well, it means you can replace this:

if (foo === undefined || foo === null) {
//...
}

… With this:

if (foo == null) {
//...
}

If something is == to null then it is either null or undefined. Those are the only possible values.

Returning undefined

Not returning something from a function is the same as returning undefined, so you may as well not bother explicitly returning undefined:

Note: you should be careful with the undefined value as it can be changed. E.g. You can do undefined = true beforehand. The universe would shatter if you did that though, so please don’t. Many libraries declare an empty (undefined) variable in an enclosed scope, which provides a real undefined:

No fussing with if statements and multiple returns. You can do everything within a single return statement.

Another example. We want to create a function that logs a name, specified by the arguments forename and surname, but if these arguments aren’t passed then the function should use the default values, “Bob” and “Smith”, respectively:

Here, we’re using the logical OR operator (||) to provide a default value (right hand side) if the left hand side evaluates to false. Values that evaluate to false (i.e. “falsey”) are: An empty string (""), null, undefined, 0 and false.

So, this:

forename = forename || 'Bob'

… is essentially saying: if forename is a truthy value, then assign forename to forename (in other words: don’t do anything), but if it is a falsey value (e.g. an empty string), then assign the string "Bob" to forename.