Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialVic Mercier
3,276 Pointsfunction expression and function
There's no specific goal to use a function expression or a function I think it's the same thing? Am i right
2 Answers
andren
28,558 PointsFunctions and Function Expressions act almost identically, so you can for the most part just use the form that suits you best.
The biggest difference is the fact that functions can be used before they are declared in the code. This is due to the way hoisting works, which is something JavaScript does as part of analyzing your script. For example this:
example() // call a function called "example"
function example() { // create a function called "example"
alert("This is an example")
}
Is valid code that will run correctly. This however:
example() // call a function called "example"
var example = function() { // create a function expression called "example"
alert("This is an example")
}
Is not valid code, and will lead to an error due to the fact that the example
variable has not been assigned any value at the point that it is called.
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsThey actually defers in the way function hoisting occurs .
In Javascript , both variable and function get hoisted
, which means Rather than being available after their declaration, they might actually be available beforehand .
Lets talk here about "function" specifically -
A function declaration hoist both the function's name and the actual function definition.
Lets understand with an example -
// Outputs: "Yes!"
isHoisted();
function isHoisted() {
console.log("Yes!");
}
So , we can see , you can use the function before the point at which it has been declared in the source code.
However , you result is totally different when using function expression
. Lets understand with an example-
// Outputs: "This function is hoisted!"
definitionHoisted();
// TypeError: undefined is not a function
definitionNotHoisted();
function definitionHoisted() {
console.log("This function is hoisted!");
}
var definitionNotHoisted = function () {
console.log("This function is not hoisted!");
};
So , in case of functin expression , we're getting TypeError: undefined is not a function . Hope it helps . :)