Differences In declaring Functions!


#1

What Is The Differense Btw. This Code (below)

function timesTwo(num) {
    return num * 2;
};

And This function Code (below)

var timesTwo = function(num) {
   return num * 2;
};

THE ONLY DIFFERENCE I COULD FIND IS THAT THE SECOND FUNCTION CODE IS TOO LENGHTHY !

PLEASE GIVE THE ANSWER TO THIS ?


#2

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.

So if you try to call a function expression before it's loaded, you'll get an error! If you call a function declaration instead, it'll always work, because no code can be called until all declarations are loaded.

Example: Function Expression

alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }

Example: Function Declaration

alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
function foo() { return 5; }

from stackoverflow


#3

Sir , can use plese Help me the use Of this type of coding ?

alert(foo()); // ERROR! foo wasn't loaded yet
var foo = function() { return 5; }

where can we find the use of the above function declaration !


#4

this code just shows that if you use a Function Expression, the function Expression should come before your function call, otherwise you get an error. As for a Function Declaration the function call can be before the function Declaration, since function Declarations are loaded first.


#5

Sir, sorry i coudnt quite get the idea !
Can U Please Be more Clear . :smiley:


#6

check it here all about function


#7

please read my answer again, i edited. Make sure you know what is the function Declaration and function Expression, and you can read the source i linked to in my first answer


#8

Ohk..
Thank you Sir,
Now i Get It ! :smiley: :wink:


#9