Truthy/Falsy

, , ,

In javascript (and some other languages for that matter) non-boolean values can behave as booleans under certain circumstances. This is often referred to as “truthy” or “falsy,” that is, it’s like a boolean true or false, but technically isn’t exactly the same, so it’s “kind of true” and “kind of false.” What am I talking about?

Read More »

JS Optimisation #3 – If Statement

, ,

This tip points out a shorthand way of implementing a simple if statement.

Sometimes all you want is a simple “if this, then do that” one-liner statement, but you end up using three lines of code when really it can be a lot more straightforward.

The ternary if else statement is a great shorthand for writing a simple if else on one line without it confusing other developers who read your code. But what if you don’t want the else part?

Read More »

JS Optimisation #2 – Assignment/Test Combo

, ,

This tip considers a cheeky shorthand to assign and test simultaneously within an if statement.

Okay, so this one’s controversial. Take this code:

if (myVar = document.getElementById("myNode")) {
    alert(myVar.id);
}

You’d be forgiven for thinking there was a typo (= instead of ==), and rightly so. But this is actually a cheeky shorthand for assigning a value and testing it at the same time.

Read More »

JS Optimisation #1 – For Loop

, ,

This tip shows how to maximise the efficiency of your for loops.

When writing for loops, the classic mistake novices make is not removing dereferences from the test condition. What am I talking about?! Okay, this might look like a pretty normal for loop to most people:

for (var i = 0; i < myArray.length; i++) {
    // ...do something
}

So what’s the problem?

Read More »