Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Syntax Differences

Tags:

javascript

What is the difference between these two?

collapse: function(fold)
{
...
...
}

and

function collapse(fold)
{
...
...
}
like image 900
sapiensgladio Avatar asked Dec 08 '25 12:12

sapiensgladio


2 Answers

The first one outside of the context of an object literal is a syntax error.

However, I believe you are asking about the difference between a function expression and a function declaration.

Your first one is a function expression. You assign an anonymous function to a variable. Its variable definition is hoisted to the top of its scope, but not the assignment of the function.

The second is the function declaration. Its entire body is hoisted to the top of the scope.

In general, a function expression is often used as it is more expressive. You can give it a name if you need to call it recursively (or for better detailed stack traces), but remember IE leaks this name to the outer scope.

Further Reading.

like image 101
alex Avatar answered Dec 10 '25 02:12

alex


The first code is only valid to produce a property inside an object definition, like so:

var obj = {
    collapse: function(fold)
    {
    ...
    ...
    }
};

That function would be called by calling obj.collapse(fold);

The second function is simply called using collapse(fold);

As for the difference between var name = function() { ... } and function name() { ... } see: var functionName = function() {} vs function functionName() {}

like image 29
Nicole Avatar answered Dec 10 '25 00:12

Nicole