I am using this code to check undefined variable but it\'s not working.
It actually is working, but there is difference between null
and undefined
. You are actually assigning to uemail, which would return a value or null in case it does not exists. As per documentation.
For more information about the difference between the both of them, see this answer.
For a solution to this Garfty's answer may work, depending on what your requirement is. You may also want to have a look here.
From Typescript 3.7 on, you can also use nullish coalescing:
let x = foo ?? bar();
Which is the equivalent for checking for null or undefined:
let x = (foo !== null && foo !== undefined) ?
foo :
bar();
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
While not exactly the same, you could write your code as:
var uemail = localStorage.getItem("useremail") ?? alert('Undefined');
Adding this late answer to check for object.propertie that can help in some cases:
Using a juggling-check, you can test both null and undefined in one hit:
if (object.property == null) {
If you use a strict-check, it will only be true for values set to null and won't evaluate as true for undefined variables:
if (object.property === null) {
Typescript does NOT have a function to check if a variable is defined.
Update October 2020
You can now also use the nullish coallesing operator introduced in Typescript.
let neverNullOrUndefined = someValue ?? anotherValue;
Here, anotherValue
will only be returned if someValue
is null or undefined.