Rethinking JavaScript for-loops

(versión abreviada en español)

If you think the introduction of Array.prototype.forEach and friends will send the for-loop the way of the dodo, think again. There’s life in the old dog yet.

The for-loop is often seen as something of a one trick pony, most suited to the classic form of list iteration:

for (var i=0; i<arr.length; i++) {
    //do something to each member
}

but with the wealth of higher order functions now available both natively and in frameworks we can just do this (or variants thereof)

arr.forEach(function(each)) {
    //do something to each
});

Ironically as high-order functions gradually render the traditional pattern obsolete, so might we become liberated from our old habits and branch out to explore more interesting patterns of for-looping.

To whet your appetite – here’s an ultra-compact way to generate and alert the first n members of the Fibonacci series:

for (
    var i=2, r=[0,1];
    i<15 || alert(r);
    r.push(r[i-1] + r[i-2]), i++
);
//alerts "0,1,1,2,3,5,8,13,21,34,55,89,144,233,377"

 
Continue reading “Rethinking JavaScript for-loops”

The Secret Life of JavaScript Primitives

You may not know it but, in JavaScript, whenever you interact with string, number or boolean primitives you enter a hidden world of object shadows and coercion. So dust off your Sherlock Holmes outfit and read on…

Continue reading “The Secret Life of JavaScript Primitives”

Understanding JavaScript’s this keyword

(In Portugese)

The JavaScript this keyword is ubiquitous yet misconceptions abound.

What you need to know
Every execution context has an associated ThisBinding whose lifespan is equal to that of the execution context and whose value is constant. There are three types of execution context: global, function and evaluation. Here’s a tabular summary followed by a little more detail, and some examples:

Execution Context Syntax of function call Value of this
Global n/a global object (e.g. window)
Function Method call:
myObject.foo();
myObject
Function Baseless function call:
foo();
global object (e.g. window)
(undefined in strict mode)
Function Using call:
foo.call(context, myArg);
context
Function Using apply:
foo.apply(context, [myArgs]);
context
Function Constructor with new:
var newFoo = new Foo();
the new instance
(e.g. newFoo)
Evaluation n/a value of this in parent context

1. Global context
this is bound to the global object (window in a browser)

alert(this); //window

Continue reading “Understanding JavaScript’s this keyword”

A JS1K Byte-Saver Quiz!

Here’s a little javascript quiz to help you limber up for JS1K. Each problem is solvable with one statement. Answer with the shortest possible solution.

This is not about writing the most readable or production-ready code. Its a fun test of versatility and language knowledge.

Answers should work on all major browsers except where denoted with “ECMA 5” (in which case they should work on all browsers except IE<9) . The number in parentheses indicates how many characters were in my solution, including semicolons but omitting returns and extra spaces.

I’ll post my solutions on Monday. Good luck! (Spoiler alert – some solutions in comments)

Continue reading “A JS1K Byte-Saver Quiz!”

Understanding JavaScript’s ‘undefined’

Compared to other languages, JavaScript’s concept of undefined is a little confusing. In particular, trying to understand ReferenceErrors (“x is not defined”) and how best to code against them can be frustrating.

This is my attempt to straighten things out a little. If you’re not already familiar with the difference between variables and properties in JavaScript (including the internal VariableObject) now might be a good time to check out my previous posting.

What is undefined?

In JavaScript there is Undefined (type), undefined (value) and undefined (variable).
Continue reading “Understanding JavaScript’s ‘undefined’”

Variables vs. Properties in JavaScript

( 한국어 )

What is a property? What is a variable? In what ways, if any, do they differ?

Basic questions. Fundamental to understanding the language, but mostly overlooked in the literature of JavaScript. (That said, I know of two excellent articles on the topic. I’ve cited them at the end of this text)

Anyway, here’s my take on it:
Continue reading “Variables vs. Properties in JavaScript”

No ifs…alternatives to statement branching in JavaScript

You could do this..

//Example 1
function getEventTarget(evt) {
    if (!evt) {
    	evt = window.event;
    }
    if (!evt) {
    	return;
    }
    var target;
    if (evt.target) {
        target = evt.target;
    } else {
        target = evt.srcElement;
    }
    return target;
}

or you could do this…

//Example 2
function getEventTarget(evt) {
    evt = evt || window.event;
    return evt && (evt.target || evt.srcElement);
}

Continue reading “No ifs…alternatives to statement branching in JavaScript”

Understanding JavaScript Arrays

(Russian Version is here)

What is an Array in JavaScript?

A numerically indexed map of values.

Traditionally an array reserves a continuous allocation of memory of predefined length. In JavaScript this is not the case. A JavaScript array is simply a glorified object with a unique constructor and literal syntax and an additional set of properties and methods inherited from Array.prototype. If this means we make a small sacrifice in performance, it is more than compensated for by its ease of use and the power of its utilities. Unlike its counterparts in certain other languages, JavaScript arrays are a joy to use – this is something they definitely got right.

Continue reading “Understanding JavaScript Arrays”