7 ms·
The variable declaration is hoisted to the top, then is assigned a named function expression `func` so that `func.name === 'func'`. Useful for proper error me
by ShellfishMeme 13y ago
The variable declaration is hoisted to the top, then is assigned a named function expression `func` so that `func.name === 'func'`.
Useful for proper error messages and stack traces.
Something else I'm missing?
- thomaslangston 13y agoCould you go into more detail about why you would do A) var func = function func() { /* blah */ }; Instead of B) function func() { /* blah */ };
- yuchi 13y agovar func = _.memoize(function private_non_memoized_func() { func(); // "light" private_non_memoized_func(); // "heavy" });
- ShellfishMeme 13y agoLet's say you want to define a function to be used for a certain operation on two numbers dependent on some boolean. if (addition) { // operation = add } else { // operation = subtract } If you use function declarations you might run into bugs if (addition) { function operation (a, b) { return a + b; } } else { function operation (a, b) { return a - b; } } console.log(operation(1,2)); Here it might happen that you don't get the expected function. Additionally it's much less clear what's going on. Compare it to this: var operation; if (addition) { operation = function add (a, b) { return a + b; }; } else { operation = function subtract (a, b) { return a - b; }; } console.log(operation(1, 2)); Here it's very obvious what's going on and your operation function has a name that reflects what it does. Personally I prever never to rely on function hoisting and always declare functions using function expressions. It keeps the code style more consistent and it's clearer what is happening in your program.
- deleted 13y ago[deleted]
- solox3 13y agoYeah, the average applicant says something along those lines. The top applicants also mention the IE bug associated with named function expressions: http://kangax.github.io/nfe/ http://kangax.github.io/nfe/
- 3minus1 13y agoDon't forget that the second func is unnecessary, unless it's a function that calls itself. Also it will show up as func when debugging instead of anonymous function.