JavaScript, the unnecessary part : Defining Variables inside Block Scope

Variable scope in JavaScript

JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function. Douglas Crockford

Defining all (local) variables at the top of the function makes a lot sense to me

Let's compare two different coding patterns, for function foo() and bar().

Though either way works, I'd prefer to define variables at the top of a function (the code pattern of bar()), which make code easier to maintain for me.

Defining Variables inside Block Scope

But I'm not here to propose a better coding pattern for which you should judge by your self. What I'd like to do here is introduce a way to implement block scope for JavaScript.

To begin with, let's begin with the with statement

Note that an anonymous { x:0 } is declared right after the with statement to define a local member named x. When we try to access the variable x inside the with statement, x will refer to a number variable intead of a Date variable defined at the top of the function.

Performance test

Before we're going too far, we need to be more carreful about the cost of this approach.

This the quick summary of some stats I collected from my browsers

Browser milliseconds spent for function m1() milliseconds spent for function m2()
with with statement
IE 6 100 110
Firefox 2.0.0.4 (Mac OS 10.4) 257 294
Safari version 3.1.1 (4525.18) 33 29
opera 9.27 335 363

In general, the with block approach consumes more resources and the code pattern may not be as understandable as people we might expect, which means, don't try this for your procution work.

Hedger Wang