marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.01k stars 793 forks source link

Consider mentioning advantages of function declaration stack trace debugging #445

Closed gareys closed 6 years ago

gareys commented 6 years ago

While reading Chapter 3 on Declaration Notation you mention hoisting as a subtlety of function declarations, but I think it is also very important to point out that naming functions provides for a much better stack trace when debugging as it will reference the function declaration in the trace. Whereas with an unnamed function expression there will only be line reporting, which can be difficult to debug.

Consider this contrived example:

With a function declaration (error is located by function name and line number)

(function foo () {
throw new Error('ERROR');
})()

Uncaught Error: ERROR
    at foo (<anonymous>:2:7)
    at <anonymous>:3:3

With a function expression (error is only located by line number)

(function () {
throw new Error('ERROR');
})()

Uncaught Error: ERROR
    at <anonymous>:2:7
    at <anonymous>:3:3

I understand this is more of a best practice, but it could be a valuable point to reinforce.

marijnh commented 6 years ago

Modern engines will 'guess' a name for functions that are immediately assigned to variables, so this isn't really an important advantage.

For example, this will still yield a stack trace mentioning foo and bar.

let foo = function() { throw new Error("!") }
let bar = () => foo()
bar()