83

I am using this code to check undefined variable but it's not working.

var  uemail = localStorage.getItem("useremail");

if (typeof uemail === "undefined")
{
    alert('undefined');
}
else
{
    alert('defined');
}
Edward Brey
  • 35,877
  • 14
  • 173
  • 224
pushp
  • 1,144
  • 2
  • 13
  • 28

11 Answers11

78

In Typescript 2 you can use Undefined type to check for undefined values. So if you declare a variable as:

let uemail : string | undefined;

Then you can check if the variable z is undefined as:

if(uemail === undefined)
{

}
Edward Brey
  • 35,877
  • 14
  • 173
  • 224
ashish
  • 1,002
  • 6
  • 6
  • 3
    This is not helpful. The original poster wants to check if a specific value exists in `localStorage` or not. `localStorage.getItem()` returns `null` if the item has not been set before. This would not be assignable to `string | undefined`, as `null` is a different type. – opyh Jul 27 '19 at 22:57
  • 11
    It answers the question in the title, which is more helpful for most people. But yes, if your goal is to check `localStorage`, checking for `undefined` my be the wrong approach. – meustrus May 06 '20 at 21:41
43

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!

Community
  • 1
  • 1
Motonstron
  • 702
  • 4
  • 8
  • 64
    If uemail equals zero, that will equate to false, and it will evaluate incorrectly. – Todd Sjolander Jul 23 '18 at 12:59
  • 4
    Correct however in the question the op is using localStorage.getItem("useremail"); which will return null. – Motonstron Jul 30 '18 at 09:08
  • Can be misleading with the title of the post. I do second Todd on that one. – JulienCoo Oct 21 '19 at 13:37
  • if you really expect, the number 0 to be false; then by all means just use it. – Aizzat Suhardi Feb 18 '20 at 03:26
  • Todd is right. Simple "if" does not cover case with value = 0. – Viacheslav Dobromyslov Mar 06 '20 at 04:51
  • but it has to be a string, so it can't be 0. Why bother typing if you don't trust your types? – Kevin Gagnon Apr 07 '21 at 17:43
  • @KevinGagnon Because it simplifies coding. Every time there is a check for `undefined` you have to keep in mind: `[] == true => false`, but `if ([]) => true`. `({}) == true => false`, but `if ({}) => true`. Don't get confused. Also `if ("") => false`. Are you sure you do not need the empty string? And as menioned `if (0) => false`. Just use `undefined` and stop worrying. Eventually `if (value !== undefined && value !== "")` is easier to understand than `if (value)` – Toxiro May 08 '21 at 12:09
  • @Toxiro This is typescript. It can't be a number. so it's either an undefined string or a string. the simple if is the simplest way to check without any doubt. – Kevin Gagnon May 08 '21 at 14:54
  • @KevinGagnon No it is not, a simple `if` does not work if it is an empty string (`""`). It might work in this example, because it might never return an empty string, but generally speaking you waste time to always ask yourself if a function could return an empty string. Or if it is a number check, if it might return `0`. Furthermore it might not return it at the moment, but maybe in the future and then you have a problem. You can avoid all that by just writing `!== undefined` every time. – Toxiro May 08 '21 at 22:07
  • @Toxiro coding for the future is an anti pattern. And an empty string will also evaluate to false, which is the same for undefined. They might be 2 seperate states javascript-interpretation-wise, but in the real world and in the scenario, they're not. Also, if you really only want nullish operators then use ?? operator instead. – Kevin Gagnon May 10 '21 at 00:02
  • @KevinGagnon Coding for the future yes, coding readable not, reducing thinking time also not. As I said, I am not talking about the fact, that `undefined` is required in this special scenario. As you said, the empty string evaluates to false and if you want to avoid asking your self every time if you need the empty string or if you need the `0`, then you are wasting time. Also writing `!== undefined` is easy readable for other coders. That is also not an anti pattern. – Toxiro May 10 '21 at 16:57
34

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');
Paulus Potter
  • 453
  • 4
  • 6
11

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');
  }
WebDevBooster
  • 13,159
  • 8
  • 57
  • 66
Nabin Kumar Khatiwada
  • 1,270
  • 13
  • 15
  • 1
    This is only half correct: 1) `null` and `undefined` DO have types in TypeScript. 2) While using `==` comparison has a working logic in this case, the returned value of `localStorage.getItem()` is never `undefined`. – opyh Jul 27 '19 at 23:03
  • Yes, I agree bcoz null === undefined is false. But, most of the cases are solved by using == operator. – Nabin Kumar Khatiwada Jun 04 '20 at 06:46
9

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.

Lucas
  • 7,613
  • 5
  • 37
  • 45
6

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.

Community
  • 1
  • 1
Sam Segers
  • 1,811
  • 2
  • 21
  • 24
2

Late to the story but I think some details are overlooked?

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.

mtholen
  • 859
  • 6
  • 21
  • 4
    You can't redefine `undefined`. – Endrju Feb 06 '20 at 11:44
  • @mtholen have you tried to redefine undefined? I've tried and its impossible. – Viacheslav Dobromyslov Mar 06 '20 at 05:09
  • If you are in JavaScript, not TypeScript, you can *absolutely* redefine undefined. Please don't, though. – meustrus May 06 '20 at 21:42
  • 1
    undefined is its own type in Typescript, it is not an uninstantiated variable. Everything after your initial example is not accurate and you also list no sources. See https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined on top of this, undefined is a primitive type in javascript as well: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined – Chris Lang Jul 17 '20 at 21:19
  • 1
    'However, the global variable undefined is not a reserved word and therefore can be redefined. Luckily as of ECMA 5, undefined is not permitted to be redefined, but in previous versions and older browsers it was possible...' https://davidshariff.com/blog/javascripts-undefined-explored/ so although you are correct, in modern day browsers, using ecma5 it is not allowed. However in the past this certainly was possible... The post is also to illustrate how this works in JS. But, yes, strictly speaking, if ecma5 is the standard then no `undefined` cannot be redefined – mtholen Jul 19 '20 at 02:17
1

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.

Ezio
  • 2,367
  • 1
  • 21
  • 33
1

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
}
FDisk
  • 6,213
  • 1
  • 38
  • 45
0

You can check null or undefined as below,

if (!uemail) // it is null or undefined
{
    alert('null or undefined');
}
else
{
    alert('defined');
}
Furkan Öztürk
  • 663
  • 4
  • 12
-4

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');
}
  • 1
    While this looked as if it would work, it did not. `this.uemail` is always `undefined`, as it refers to a non-existing, different variable than `var uemail`. – opyh Jul 27 '19 at 22:46
  • You converting the `undefined` to a string and then compare the strings. You're wasting resources, since you can simply say `this.uemail == undefined`. – akop Mar 17 '21 at 18:29