Find the output of given code snippet
Let’s take a look at the following JavaScript code:
let x = 10;
function foo() {
console.log(x);
let x = 20;
}
foo();
What do you think the output of this code snippet will be?
Now, let’s analyze the code:
When the foo
function is called, it tries to log the value of x
to the console. However, within the function, a new variable x
is declared and assigned the value 20. This means that the value of x
within the function is undefined at the time of the console log, as it is declared after the console.log(x)
statement.
As a result, the output of the code will be undefined
.
So, if you were asked this question in a JavaScript interview, now you know how to answer it!
Follow this channel for more interesting JavaScript interview questions. Thanks!😊