blog

  • Home
  • blog
  • Quick Tip: Function Expressions vs Function Declarations

Quick Tip: Function Expressions vs Function Declarations

JavaScript has two different ways of creating functions. Function declarations have been used for a long time, but function expressions have been gradually taking over.

function funcDeclaration() {
    return 'A function declaration';
}

var funcExpression = function () {
    return 'A function expression';
}

Differences between Declarations and Expressions

Similar to the var statement, function declarations are hoisted to the top of other code. Function expressions aren’t hoisted, which allows them to retain a copy of the local variables from the scope where they were defined.

Normally function declarations and function expressions can be used interchangably, but there are times when function expressions result in easiler to understand code without the need for a temporary function name.

Benefits of Function Expressions

There are several different ways that function expressions become more useful than function declarations.

  • As closures
  • As arguments to other functions
  • As Immediately Invoked Function Expressions (IIFE)

Creating Closures

Closures are used when you want to give parameters to a function, before that function is executed. A good example of how this can benefit you is when looping though a NodeList. A closure allows you to retain other information such as the index, in situations where that information will no longer be available when the function is executed.

function tabsHandler(index) {
    return function tabClickEvent(evt) {
        // Do stuff with tab.
        // The index variable can be accessed from within here.
    };
}

var tabs = document.querySelectorAll('.tab'),
    i;

for (i = 0; i < tabs.length; i += 1) {
    tabs[index].onclick = tabsHandler(i);
}

Continue reading %Quick Tip: Function Expressions vs Function Declarations%

LEAVE A REPLY