0

I want to check that a value is not declared or a value is not initialized in JavaScript. It is confused that typeof operator returns undefined in two above situations.

// age is not declared
console.log(typeof someUndeclaredVariable); // undefined

let otherVariable; // age is declared but not initialized

console.log(typeof otherVariable); // undefined

THANKS

trigold
  • 51
  • 7
  • 3
    the first `typeof age` throws an error, it doesn't print `undefined` – Nick Parsons Aug 05 '21 at 06:29
  • 1
    Seems like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You shouldn't have code that works with a variable that *might* not be there. You should write code that only uses what is going to definitely exist. – VLAZ Aug 05 '21 at 06:29
  • 1
    From [MDN:](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#errors) _"with the addition of block-scoped let and const, using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a ReferenceError"_ – Yousaf Aug 05 '21 at 06:30
  • you might be interested to read info about the TDZ: https://stackoverflow.com/questions/33198849/what-is-the-temporal-dead-zone – Nick Parsons Aug 05 '21 at 06:30
  • If you use `var` instead of `let` the declaration will implicitly be moved to the top of the function, causing this behavior – mousetail Aug 05 '21 at 06:31
  • @mousetail technically, declaration will not be moved at the top - it will stay where it is. Hoisting simply means that `var` declarations are _processed_ before the step-by-step execution of the code. Even `let` and `const` are hoisted BUT they can't be accessed _before_ their declaration has actually executed. – Yousaf Aug 05 '21 at 06:32
  • @Yousaf True, but it will still cause the behavior described here – mousetail Aug 05 '21 at 06:33
  • Sorry! I make you confused! "let" causes temporal dead zone. But what I want to talk is different from it. I simply want to demonstrate the effects of typeof operator. – trigold Aug 05 '21 at 12:39

2 Answers2

1

According to the MDN,

let variables cannot be read/written until they have been fully initialized, which happens when they are declared (if no initial value is specified on declaration, the variable is initialized with a value of undefined). Accessing the variable before the initialization results in a ReferenceError.

Ripal Barot
  • 687
  • 8
  • 16
  • Sorry! I make you confused! "let" causes temporal dead zone. But what I want to talk is different from it. I simply want to demonstrate the effects of typeof operator. – trigold Aug 05 '21 at 12:39
0
if(typeof someVariable == "undefined"){
    try{
        console.log(someVariable); // declared but not initialized
    } catch(error){
        console.log("not declared!");
    }
}

I am considering this approach.

trigold
  • 51
  • 7