I declared a variable in my JavaScript code, but when I try to use it, I’m getting “undefined.” What’s wrong?
Here are some potential causes:
Variable declaration after usage: Make sure the variable is declared before you try to access it.
// Incorrect
if (true) {
let myVar = "Hello";
}
console.log(myVar); // Error: myVar is not defined
// Correct
let myVar;
if (true) {
myVar = "Hello";
}
console.log(myVar); // Output: Hello