Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if typeof ='undefined' in try/catch space

I have code that is wrapped in try/catch block. I use typeof to find out if a variable is defined:

if (typeof (var) == 'string') { 
    //the string is defined
}

However, using this in a try/catch block, jumps to the catch part instead of doing what it is suppoed to do (do something with the string if its defined).

How can I check if a variable is defined without activating an exception?

like image 309
Nir Avatar asked Jun 30 '09 11:06

Nir


People also ask

How do you know if typeof is undefined?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

What is the value of typeof undefined == typeof null?

The typeof undefined is the string "undefined" — and undefined is a falsy value that is loosely equal to null but not to other falsy values.

Is undefined equal to null?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.


1 Answers

'var' is not a valid variable name - it's a keyword.

Apart from that, what you have should be correct.

like image 77
Greg Avatar answered Oct 30 '22 21:10

Greg