Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 73
  • Last Modified:

When to use a function or a var


In JavaScript when would you use a var over a function or vice versa?
Or is it just personal preference?


var investment = function(){};
as opposed to
function investment() {};
2 Solutions
Dany BalianCTOCommented:
Well it has to do with reusability! If u want to use the function al over again then use functions! If it's a one time thing then just type it!
SolugaAuthor Commented:
Hi Danny,

So would you then use a var to create an instance of the function?
Such as ..

var = investment();

function investement(){};
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
if you expect a value to be returned from the function, then it would be better to put it a variable. if not, then just calling the function by name would be the best way to go (purely for readability purposes)
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Dany BalianCTOCommented:
if you need to use the var many times.. then yes you do that..
instead of doing

if (getproductdiscount()>0) {
total = total + getproductdiscount();
} else {
total = total - getproductdiscount();
in this case getproductdiscount() will be executed and calculated 3 times

var disc=getproductdiscount();
if (disc>0) {
total = total + disc;
} else {
total = total - disc;
will run the function just once
I think this explains the difference between function declarations and function expressions : https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
It's interesting that you accepted those two comments even though they answer a completely different question.
What they answer is why put the result of a function call in a variable
result = myfunction();
if (result > 0)
    total = total + result;

Open in new window

vs. using directly the result of the function.
if (myfunction() > 0)
    total = total + myfunction();

Open in new window

Your question was about the difference between a function declaration
function investment() {}

Open in new window

and a function expression
var investment = function(){};

Open in new window


Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now