+ 2
Function Declaration vs. Function Expression...?
In Javascript we have a function declaration: function myFunction() { // stuff } and a function expression: var myFunction = function() { // stuff } AND function expression with identifier: var myFunction = function myFunction() { // stuff } What is different between them? Why use one over the other? Does it make any big difference?
2 ответов
+ 2
Hi dCook
As I understand it there are some subtle differences to them related to
1. Hoisting
2. Use inside Closures
3. Use inside IFFEs
all of which are classic interview questions.
Discussion of above is well documented in many articles eg:
https://medium.com/@mandeep1012/function-declarations-vs-function-expressions-b43646042052
I wanted to mention one lightbulb moment for me and that is that Functions are objects in JS (the term used is "first class" me thinks). So you can assign them like variables/consts.
//function declaration
function hi (s){
s="Hi "+s;
return s;
}
//function expression assigns above function"hi" to a const called greeting
const greeting=hi(s);
is the same as
const greeting =hi; // look no brackets.
+ 2
Thanks Mike!
There’s a bit more reading for me to do based on that. The article was nice! Cheers