1

So, lets say I have a little program that gives the user an alert that says Hello, that is inside of a function. Everyone says that you should call functions like this:

var thefunct = awesomefunct();

Yet it still works perfectly fine like this:

awesomefunct();

What is the difference between the two, and why couldn't I just use the second one? I know that both methods work but all my programmer friends tell me to use the first one. Why?

Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42
  • 1
    I have no idea what you are asking here. – asawyer Apr 10 '14 at 12:20
  • What I am asking is this: there are two different methods to calling a function in JavaScript. (Both listed in my question.) which method is usually better to use, and if so, why? – Ethan Bierlein Apr 10 '14 at 12:22
  • Check this http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip – Vijay Singh Rana Apr 10 '14 at 12:22

5 Answers5

3

The difference is that the return statement of the function will be assigned to the variable thefunct in the first one, whereas the second just runs the function and doesn't store the return statement.

Say I have a function like this:

function doSomething(a, b) {
    return (a*b)
}

It would be a good idea to store the result in a variable, because the function returns the result, it doesn't assign it to a previously declared global variable.

Ilan Biala
  • 3,319
  • 5
  • 36
  • 45
3

If you run

awesomefunct()

You call the function. So when you type:

var thefunct = awesomefunct();

You run the function and assign the result to thefunct variable.

after that just typing

thefunct

Wont call the function. So there is not that much differencebetween the 2 other than that you catch the return value on the first 1.

JohanSellberg
  • 2,423
  • 1
  • 21
  • 28
2

Do you care about the return value? Use:

var thefunct = awesomefunct();

Don't care about the return value? Use:

awesomefunct();
A1rPun
  • 16,287
  • 7
  • 57
  • 90
2

You may be misunderstanding what your code is doing.

Writing thefunct is not calling the function awesomefunct, your function has already been called when you wrote var thefunct = awesomefunct(); in which case thefunct now contains the return value of awesomefunct

Isaac
  • 11,409
  • 5
  • 33
  • 45
1

The first type of function call:

awesomefunct();

runs the function, but the return value (if any) is not stored anywhere.

The second type of function call:

var thefunct = awesomefunct();

runs the function, and stores whatever the function returns (0, "I'm awesome", an object, whatever it may be) in the variable thefunct.

Kris
  • 143
  • 2
  • 8