Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare variables to undefined, if I don’t know whether they exist? [duplicate]

In JavaScript you can declare a variable and if it’s undefined, you can check variable == undefined; I know that, but how can you compare a value that you don’t know yet if it’s in memory?

For example, I have a class which is created when the user clicks a button. Before this, the class is undefined — it doesn’t exist anywhere; how can I compare it?

Is there a way without using trycatch?

like image 792
ncubica Avatar asked May 06 '10 06:05

ncubica


People also ask

How do you compare undefined variables?

The short answer In modern browsers you can safely compare the variable directly to undefined : if (name === undefined) {...} After that re-assignment, comparing with undefined directly would no longer correctly detect whether a variable was assigned a value.

How do you check if a variable is undefined or not?

Answer: Use the equality operator ( == )In JavaScript if a variable has been declared, but has not been assigned a value, is automatically assigned the value undefined . Therefore, if you try to display the value of such variable, the word "undefined" will be displayed.

Is null == undefined?

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.

Is there a way to check for both null and undefined `?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator.


1 Answers

The best way is to check the type, because undefined/null/false are a tricky thing in JS. So:

if(typeof obj !== "undefined") {     // obj is a valid variable, do something here. } 

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

like image 100
Makram Saleh Avatar answered Sep 20 '22 14:09

Makram Saleh