Functions with variable


Why functions are made with variable

var name = function ()

I have seen code on other sites made without using "var" and what goes inside the brackets after function i.e. function()


The following is known as a function expression,

function () {}

whereas the following is a function declaration,

function foo() {}

Their differences are slight. Both behave in the exact same manner with one exception, the latter is hoisted to the top of its scope at run time, the former is not.

JavaScript is parsed into the namespace in two passes. The first pass is when hoisting takes place. All declared objects are hoisted, but not their values or expressions. This means a function expression statement such as in the OP will have only the name hoisted, but not the function.

Expressions and values are parsed on the second pass. For this reason we must always write the function above where it is first called in the source listing, else it will be undefined.

One could say more regarding advantages and disadvanages but I will forego this and let you read up on declaration vs expression in your own time.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.