Why we create function using a var (variable)? why we cant make function without using var tag?


#1

this is silly but really bothering me

i have seen some tutorials online they create function directly and here we use var tag ....why??

why we cant make function without using var tag??


#2

This article discusses the meaning of the two ways to write a function:


as far as I know you could use both here it's just that the exercise recommends the one with var probably because then you need to keep a causality (not call the function before you declare it aso).


#3

that was helpful thanks!!


#4

Is there a reason why Codeacademy are using

var divideByThree = function () {…

rather than

function divideByThree() {…

? I tried reading the StackOverflow article but it didn't make much sense to me! Was wondering if there is a beginner's simple explanation? thanks :slightly_smiling:


#5

As far as I've understood it the difference is that this is possible:

helloWorld();
function helloWorld(){
    console.log("Hello World");
}

while this is not:

helloWorld();
var helloWorld = function (){
    console.log("Hello World");
}

I can only guess the reasoning of the author but maybe it seemed more intuitive for beginners that you can only use stuff after you've declared it and the other one might also lead to trouble in the progress but in the end the difference is not that big and you could even use the mixture:

var helloWorld = function helloWorld(){
    console.log("Hello World");
}

#6

Hello everyone,

I am studying JS at this wonderful site..and I have a problem.. I have this algorithm

var nameString = function(name) {
	return "Hi, I am" + " " + name;
	};

nameString("Peter");
console.log (nameString);

The site says it is okay ("way to go"), but it doesn't show the correct sentence..it should be "Hi, I am Peter", but instead "[Function]" appears..Please help..what is the problem...This task is from chapter 11 "Function recap" ("Introduction to functions in JS"). Thank you in advance


#7

Seems to be a similar problem to this one:


#8

Thank you, that makes more sense!


#9

Thank you very much!