Answer Detail

how to check if a variable is not defined in javascript

beginer
beginer
50 Points
20 Posts

I am getting javascript error

ReferenceError: requestedCode is not defined

requestedCode is a javascript variable of type string. I want to check if this variable is defined or not but I unable to do that.

if(requestedCode){
   console.log('not defined')
}

//Or

if(requestedCode == null){
   console.log('not defined')
}

//Or

if(requestedCode == undefinded){
   console.log('not defined')
}

But in above all cases I am getting the same error

ReferenceError: requestedCode is not defined

How I can check if a variable is not defined?

 

Total Answered: 2
Total Marked As Answer: 2
Posted On: 16-Jan-2018 03:45

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Moderator
1152 Points
211 Posts
Marked as answer      

There are two way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
  console.log('Your variable is undefined')
}

//OR

if (window['someVar'] === undefined) {
  // Your variable is undefined
  console.log('Your variable is undefined')
}

You can check your own in browser console. see below

Posted On: 17-Jan-2018 02:35
Smith
Smith
Participant
348 Points
104 Posts
Marked as answer      

The typeof operator checks if the variable is really undefined.

if (typeof variable === 'undefined') {
    // variable is undefined
}

The typeof operator, unlike the other operators, doesn't throw a ReferenceError exception when used with an undeclared variable.

However, we should note that typeof null will return "object". We have to be careful to avoid the mistake of initializing a variable to null. To be safe, this is what we could use instead:

if (typeof variable === 'undefined' || variable === null) {
    // variable is undefined or null
}
Posted On: 17-Jan-2018 03:34
banner

Blog

Active User (0)

No Active User!
 Log In to Chat