Guess the Output JavaScript Challenge | Variable Scope, Hoisting & ReferenceError



Guess the Output JavaScript Challenge | Variable Scope, Hoisting & ReferenceError

Guess the Output JavaScript Challenge | Variable Scope, Hoisting & ReferenceError

Can you guess the output in this JavaScript challenge question? This is one of common JavaScript interview questions. It’s a trick javascript question. If you know enough about variable scope, function scope, hoisting, variable declaration and variable assignment in JavaScript, then this question should be easy for you.

The code results in a reference error because the let keyword is used to declare the variable num
within the arrow function. This creates a new variable with the same name as the existing global variable, and the global variable is not accessible within the function’s scope.

JavaScript’s variable hoisting mechanism moves the variable declaration to the top of the function,
but the assignment remains in its original place. When the function is executed, this console log is trying to access the local variable num which has not been assigned yet, so it returns undefined and a ReferenceError is thrown.

A quick fix for this issue would be to either change the let keyword to var or to remove the let keyword entirely, so the global variable can be accessed.

So to avoid such reference error in javascript, make sure you keep these things in mind.

Our tutorials help you to improve your career growth, perform better in your job and make money online as a freelancer. Learn the skills to build and design professional websites, and create dynamic and interactive web applications using JavaScript, or WordPress. Our tutorials are tailored to help beginners and professionals alike. Whether you’re just starting in the field or you’re looking to expand your knowledge, we’ve got something for you. Join us on this journey to becoming a skilled web developer. Subscribe to our channel and let’s get started!

Thank You!
👍 LIKE VIDEO
👊 SUBSCRIBE
🔔 PRESS BELL ICON
✍️ COMMENT

⚡Channel: https://www.youtube.com/@webstylepress
⚡Website: https://www.webstylepress.com
⚡FaceBook: https://www.facebook.com/webstylepress
⚡Twitter: https://twitter.com/webstylepress
⚡GitHub: https://github.com/webstylepress
#js #javascript #challenge #WebStylePress #WebDevelopment #referenceerror #hoisting #javascriptinterviewquestions #javascripttutorial #computerscience #programming