QWhich of the following variable types, if their names are identical, takes priority over the others?
Question Info
Choose the Best Option
Click any option to instantly check if you're correct.
Explanation
In JavaScript, if a local variable and a global variable have the same name, the local variable takes precedence over the global variable.
Here's an example of how this works:
let x = 5; // x is a global variable
function foo() {
let x = 10; // x is a local variable
console.log(x); // Output: 10
}
foo(); // Output: 10
console.log(x); // Output: 5
In this example, the local variable x is defined within the foo function, and it takes precedence over the global variable x.
When we log the value of x within the function, it prints 10, which is the value of the local variable.
When we log the value of x outside the function, it
prints 5, which is the value of the global variable.
This is known as variable shadowing,
and it occurs when a local variable with the same name as a global variable "shadows" the global variable, hiding it from view within the local scope.
Share This Question
Challenge a friend or share with your study group.