how to check if a variable is not defined in javascript

beginer
beginer
1544 Points
52 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?

 

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

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
4916 Points
27 Posts
         

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
2890 Points
78 Posts
         

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
 Log In to Chat