0

Currently we have some code that is littered with statements like

if typeof myVar != 'undefined' && myVar === 'somevalue'

I'd like to consolidate that into a single expression that checks for a value in a way that is safe against undefined variables. I realize I could write my own, but is it not part of any commonly used JS library? It seems everyone else is satisfied with the code above, but I am not!

Kevin Pauli
  • 8,577
  • 15
  • 49
  • 70
  • possible duplicate of [How to check for "undefined" in JavaScript?](http://stackoverflow.com/questions/3390396/how-to-check-for-undefined-in-javascript) – Bergi Apr 10 '14 at 15:54
  • 1
    No. An in-place `typeof`-check is the only way to cope with undeclared (which seems to be what you meant by "undefined") variables. But you really really should have such anyway? – Bergi Apr 10 '14 at 15:55

1 Answers1

0

This is all you need.

myVar === 'somevalue'

The === is strict for looking for a string.

var myVar = undefined; // or 27, null, false, 2.67, etc.
myVar === 'somevalue'; // evaluates to false
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • Does that protect against an `Uncaught reference` error, if `myVar` is undefined or null? – David Thomas Apr 10 '14 at 15:47
  • How to avoid "Uncaught ReferenceError: myVar is not defined"? – Kevin Pauli Apr 10 '14 at 15:47
  • 1
    you should use `"use strict"` and always defining variables. – Daniel A. White Apr 10 '14 at 15:49
  • 1
    @KevinPauli: Define the variable. There hardly is a good reason not to do this. Otherwise, you just have to use `typeof`. – Bergi Apr 10 '14 at 15:57
  • @Daniel This is still giving me the Uncaught ReferenceError http://jsfiddle.net/xqV2G/ – Kevin Pauli Apr 10 '14 at 15:58
  • @KevinPauli if you don't define the variable, it will potentially leak and lead to unintended consequences. – Daniel A. White Apr 10 '14 at 16:03
  • 1
    Okay, my example was oversimplified... in my case myVar is actually a function argument, so it is already defined. I updated the fiddle to include that fact, and indeed the === comparison is all that is required: http://jsfiddle.net/xqV2G/2/ . So I'm going to remove the superfluous checks for typeof 'undefined'. Thanks! – Kevin Pauli Apr 10 '14 at 16:14