Reputation: 2516
I am using this code to check whether a variable is undefined, but it's not working.
var uemail = localStorage.getItem("useremail");
if (typeof uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
Upvotes: 218
Views: 647163
Reputation: 49680
this worked for me:
if (typeof window !== "undefined") {
// do your thing
}
Upvotes: 0
Reputation: 2368
In TypeScript 2, you can use the undefined
type to check for undefined values.
If you declare a variable as:
let uemail : string | undefined;
Then you can check if the variable uemail
is undefined like this:
if(uemail === undefined)
{
}
Upvotes: 213
Reputation: 1693
Edit: 07/2021
As many have pointed out, in TypeScript it is not possible anymore to redefine undefined
and therefore you will be less likely to have this risk. But in older browsers and if using pre ECMA 5 JS then there is still this risk.
if you use
if (uemail !== undefined) {
//some function
}
You are, technically, comparing variable uemail
with variable undefined
and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true.
But it overlooks the potential that a variable by the name of undefined
may actually exist -however unlikely- and would therefore then not be of type undefined.
In that case, the comparison will return false.
To be correct one would have to declare a constant of type undefined for example:
const _undefined: undefined
and then test by:
if (uemail === _undefined) {
//some function
}
This test will return true
as uemail
now equals both value & type of _undefined
as _undefined
is now properly declared to be of type undefined.
Another way would be
if (typeof(uemail) === 'undefined') {
//some function
}
In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.
Upvotes: 7
Reputation: 151
I had the following piece of code (state is a json object):
const value: string = state[identifier].description; // undefined
const severity: string = state[identifier].level; // undefined
That gave the following error:
Uncaught TypeError: (intermediate value)[identifier] is undefined
I solved it by using the Nullish Coalescing Operator in combination with Optional chaining.
const value: string = state[identifier]?.description ?? "Undefined"; // "Undefined"
const severity: string = state[identifier]?.level ?? "Undefined"; // "Undefined"
No need for if-checks or typeof equations.
Upvotes: 1
Reputation: 915
const uemail = undefined;
if (uemail ?? false)
{
alert('defined');
}
else
{
alert('undefined');
}
Protect from null & undefined
const uemail = null;
if (uemail && (uemail ?? false))
{
alert('defined or not null');
}
else
{
alert('undefined or null');
}
Upvotes: 3
Reputation: 9446
I know that this is not optimal and strange example, but good to know that there is yet another way to check if some value is defined using JSON.stringify
const foo = '';
const buzz = null;
const fooBuzz = 0;
const array = [];
let declared;
const asUndefined = undefined;
if (JSON.stringify(foo)) {
console.log(foo); // empty string
} else {
console.log('undefined');
}
if (JSON.stringify(buzz)) {
console.log(buzz); // null
} else {
console.log('undefined');
}
if (JSON.stringify(fooBuzz)) {
console.log(fooBuzz); // 0
} else {
console.log('undefined');
}
if (JSON.stringify(array)) {
console.log(array); // []
} else {
console.log('undefined');
}
if (JSON.stringify(asUndefined)) {
console.log(asUndefined);
} else {
console.log('undefined'); // undefined
}
if (JSON.stringify(declared)) {
console.log(declared);
} else {
console.log('undefined'); // undefined
}
Upvotes: 1
Reputation: 10313
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.
Upvotes: 17
Reputation: 983
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');
Upvotes: 87
Reputation: 2985
NOT STRICTLY RELATED TO TYPESCRIPT
Just to add to all the above answers, we can also use the shorthand syntax
var result = uemail || '';
This will give you the email if uemail
variable has some value and it will simply return an empty string if uemail
variable is undefined.
This gives a nice syntax for handling undefined variables and also provide a way to use a default value in case the variable is undefined.
Upvotes: 4
Reputation: 1
Use 'this' keyword to access variable. This worked for me
var uemail = localStorage.getItem("useremail");
if (typeof this.uemail === "undefined")
{
alert('undefined');
}
else
{
alert('defined');
}
Upvotes: -7
Reputation: 1646
It's because it's already null or undefined. Null or undefined does not have any type. You can check if it's is undefined first. In typescript (null == undefined)
is true.
if (uemail == undefined) {
alert('undefined');
} else {
alert('defined');
}
or
if (uemail == null) {
alert('undefined');
} else {
alert('defined');
}
Upvotes: 14
Reputation: 1951
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.
Upvotes: 6
Reputation: 932
You can just check for truthy on this:
if(uemail) {
console.log("I have something");
} else {
console.log("Nothing here...");
}
Go and check out the answer from here: Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Hope this helps!
Upvotes: 54