1

Possible Duplicate:
What is the difference between a function expression vs declaration in Javascript?

I am a web developer with prime experience in HTML, ASP.NET. I know very little javascript, enough to do simple tasks in web programming. Lately, while reading Jquery and other complex javascript files, I have been observing lot of javascript code as below:

var increment = function(x){
    return x + 1;
}

I want to know if this is conceptually same as below, which I have been more used to :

function increment(x){
    return x + 1;
}

And, if its same, why am I seeing lot of use of first notation rather than second ?

Community
  • 1
  • 1
Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124

3 Answers3

2

The difference is that
var increment = function(x){ return x + 1; } is defined at parse-time for a script block, whereas function increment(x){ return x + 1; } is defined at run-time.
see this:

<script>
increment();

var increment = function()
{
}
</script>

this will give you error.. .while

<script>

increment();

function increment()
{
}
</script>

will not give you error. .

Ket.
  • 764
  • 4
  • 12
-2

Both define functions, but first also stores functionobject in a variable, and thus makes it possible to pass it to some other method as parameter. Such constructs are extremely useful in various contexts, like processing collections - you can separate walking through collection and doing something while walking, Like this (simplified):

function doSomethingWhileIterating(collection, function) { 
       foreach(member in collection) {
            function(member);
       }
}

will call function on every element on collection doing comething useful

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
-2

Basically both are the same, the use of the first syntax gives a clear understanding of what is the variable and what is the value, bare in mind that in javascript functions are values that can be assigned to variables and be passed to functions.

please note that the second syntax actually create a var name increment and not a global variable named increment.

oz.lav
  • 1