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() {};
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Dany BalianConnect With a Mentor CTOCommented:
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
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(){};
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Big MontyConnect With a Mentor Senior 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)
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

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.