Interview Question - JavaScript Scope and const keyword

This is an interview question on JavaScript Scope and const keyword

Code

const a;
console.log(a)

Full Transcript

In this question, we are making use of const, which was defined in ES6 version of JavaScript. We are declaring a variable called a and in the next line, we are printing it on the console. Let's work together to find the right answer.

We're declaring the variable, a using a const keyword. By definition, the value of constant cannot be changed through reassignment, and it can't be re-declared either. But an initializer for a constant is required. You must specify its value in the same line where it has been declared. This makes sense, given that it can't be changed later. Failure to do so will result in the SyntaxError, which is the correct answer. Let's run the code in the IDE to prove that. As I go ahead and run the code in vs code, we can confirm that the SyntaxError is the right answer.