6 secrets of JavaScript Jedis

Are you a competent JavaScript developer but have yet to hit Jedi-level secrets? No worries -- these steps will take you to the next level

To all my readers: Yep, I'm still in Brazil, but the intrepid Jonathan Freeman has returned to share his wisdom with you. Tune in to his tips, and I'll be back soon. --ACO

As a front-end developer, I meet a lot of people who write JavaScript. The majority of them do little more than include jQuery and a few plug-ins in order to add a fancy lightbox effect or an image slider. On the opposite end of the spectrum, you have Jedi-level developers who wave their hand over the keyboard and the code basically writes itself.

[ How much do you know about this stalwart developer tool? Find out in InfoWorld's JavaScript IQ test. | Work smarter, not harder -- InfoWorld has the tips and trends programmers need to know in the Developers' Survival Guide. Download the PDF today! | Keep up with the latest developer news with InfoWorld's Developer World newsletter. ]

When you're between those skill levels, it's not always clear how to progress. There are many paths to expertise, but if you're stuck in a rut and could use a push, here are a few concepts that every JavaScript expert should know.

JavaScript secret No. 1: Closures

A closure in JavaScript gives a function access to its parent's scope. It's a terribly confusing concept for developers. When I was learning JavaScript, I spent hours debugging code that had unintended closures. After I learned from those mistakes, I thought closures were pretty cool, so I spent hours more trying fruitlessly to use closures to solve my problems.

I eventually learned the deal: Closures become useful when you return inner functions (see higher-order functions below) that still have access to their parent scope. This creates a sort of private or protected environment to keep variables.

// **Closures**

function makeThreeTimer(){

var count = 0;

return function(){

if(count < 3){

console.log('doing work');

count++;

}

else {

throw new Error('No more work');

}

}

}

var threeTimer = makeThreeTimer();

threeTimer(); // logs 'doing work' (count gets incremented)

threeTimer(); // logs 'doing work' (count gets incremented)

threeTimer(); // logs 'doing work' (count gets incremented)

threeTimer(); // throws an error

threeTimer.count; // returns undefined

In the above example, count is accessed and incremented when threeTimer gets invoked and cannot be accessed directly via dot or bracket notation.

1 2 3 Page
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Join the discussion
Be the first to comment on this article. Our Commenting Policies