Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent.

The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not.

The two ways are:

var functionOne = function() {

// Some code 

};

function functionTwo() {

 // Some code 

}

What are the reasons for using these two different methods and what are the pros and cons of each? Is there anything that can be done with one method that can't be done with the other?

1 Answer

0 votes
by (106k points)
edited by

The first function which is functionOne is called as function expression so it is only defined when that line is reached, whereas the second function which is functionTwo is a function declaration and is defined as soon as its surrounding function is executed.

Are you interested in learning Angularjs from scratch! Have a look at this interesting video on Angularjs provided by Intellipaat:

Example of a function expression:-

functionOne(); 

var functionOne = function() { 

console.log("Hello!"); 

};

If we run this code it will return type error. Because we have called the function at the top before defining it.

Example of a function declaration:-

functionTwo(); 

function functionTwo() { 

console.log("Hello!"); 

}

It won’t give any error because we have defined the function at the top before declaring it.

So this also means you can't define functions using function declarations:

Related questions

0 votes
1 answer
+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...