Asked : Nov 17
Viewed : 21 times
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 used 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?
Nov 17
The difference is that functionOne
is a function expression and so only defined when that line is reached, whereas functionTwo
is a function declaration and is defined as soon as its surrounding function or script is executed (due to hoisting).
For example, a function expression:
// TypeError: functionOne is not a function
functionOne();
var functionOne = function() {
console.log("Hello!");
};
And, a function declaration:
// Outputs: "Hello!"
functionTwo();
function functionTwo() {
console.log("Hello!");
}
Historically, function declarations defined within blocks were handled inconsistently between browsers. Strict mode (introduced in ES5) resolved this by scoping function declarations to their enclosing block.
'use strict';
{ // note this block!
function functionThree() {
console.log("Hello!");
}
}
functionThree(); // ReferenceError
answered Dec 31
Recently, I started to maintain a person's JavaScript code. I'm trying to fix bugs, add features, and organize my code to make it more consistent.
My predecessor developer uses two methods to declare a function, but I'm not sure if there's any reason for that.
What are the two methods?
var functionOne = function() {
// Some code
};
function functionTwo() {
// Some code
}
What are the reasons for using these two different methods and what are their strengths and weaknesses? Is there anything you can do with one method and not with the other?
answered Dec 31
functionDisplayOne is a function expression, however, functionDisplayTwo is a function declaration. It is defined as soon as its surrounding function is executed.
Both the ways are used to declare functions in JavaScript and functionDisplayOne is an anonymous function.
Here’s the function expression −
functionDisplayOne();
var functionDisplayOne = function() {
console.log("Hello!");
};
The following is the function declaration −
functionDisplayTwo();
function functionDisplayTwo() {
console.log("Hello!");
}
answered Dec 31