JavaScript JavaScript Basics Introducing JavaScript The Console Challenge Answer

Ross Horak
Ross Horak
19,224 Points

Why doesn't console.log('begin program'); on line 1 execute if there is an error after it in the program?

I added console.log('begin program'); to the first line of my javascript program. Before correcting the syntax errors further down in the program I reloaded the page and expected to see 'begin program' output in the console followed by error messages. However this is not the case. Only the error message is output in the console. Only once I fixed the errors did the console.log output work. Why is this? My thinking was that if the program executes line by line the console.log output on line 1 should output regardless of errors on subsequent lines of the program.

Related post: this only occurs when the error is in the string formatting, not if the error is in the function name:

https://teamtreehouse.com/community/error-in-function-name-allows-code-to-run-until-error-error-in-string-causes-everything-to-block-why

Ross Horak
Ross Horak
19,224 Points

Thanks for posting that answer Kenny - makes perfect sense!

1 Answer

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

My first guess would be because of function hoisting. You say "line by line" but JavaScript doesn't always run that way. It's possible to use a function before you even declare it because of this. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function