When to use a function or a var

Hi,

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

I.e

var investment = function(){};
as opposed to
function investment() {};
LVL 1
SolugaAsked:
Who is Participating?
 
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

however
var disc=getproductdiscount();
if (disc>0) {
total = total + disc;
} else {
total = total - disc;
}
will run the function just once
0
 
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!
0
 
SolugaAuthor Commented:
Hi Danny,

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

var = investment();

function investement(){};
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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)
0
 
louisfrCommented:
I think this explains the difference between function declarations and function expressions : https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
0
 
louisfrCommented:
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

0
All Courses

From novice to tech pro — start learning today.