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 try
–catch
?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With