JS. Проверка переменной на undefined или false
Я люблю экспериментировать с языками программирования. Недавно у меня появилась задача, часто проверять переменную JS на undefined, но при этом ещё проверить истина ли она. Стандартный код такой:
Я расскажу Вам как можно это написать в 2-3 символа. Интересно? Тогда под кат.
Вот пример посложнее, надо проверить переменную на лож или истину. Значит:
А теперь, что недавно обнаружил я, причём искал в интернете и не нашел ни в одной книге.
То-есть, «!!» — является проверкой как определена ли переменная и является истиной, а «. » — как определена переменная и является ложью.
При этом если переменная является Undefined, то всегда вернется false.
JavaScript Check if Undefined – How to Test for Undefined in JS
Joel Olawanle

An undefined variable or anything without a value will always return «undefined» in JavaScript. This is not the same as null, despite the fact that both imply an empty state.
You’ll typically assign a value to a variable after you declare it, but this is not always the case.
When a variable is declared or initialized but no value is assigned to it, JavaScript automatically displays «undefined». It looks like this:
Also, when you try accessing values in, for example, an array or object that doesn’t exist, it will throw undefined .
Here’s another example:
In this article, you will learn the various methods and approaches you can use to know if a variable is undefined in JavaScript. This is necessary if you want to avoid your code throwing errors when performing an operation with an undefined variable.
In case you are in a rush, here are the three standard methods that can help you check if a variable is undefined in JavaScript:
Let’s now explain each of these methods in more detail.
How to Check if a Variable is Undefined in JavaScript with Direct Comparison
One of the first methods that comes to mind is direct comparison. This is where you compare the output to see if it returns undefined . You can easily do this in the following way:
This also works for arrays as you can see below:
And it definitely also works for other variables:
How to Check if a Variable is Undefined in JavaScript with typeof
We can also use the type of the variable to check if it’s undefined . Luckily for us undefined is a datatype for an undefined value as you can see below:
With this we can now use the datatype to check undefined for all types of data as we saw above. Here is what the check will look like for all three scenarios we have considered:
How to Check if a Variable is Undefined in JavaScript with the Void Operator
The void operator is often used to obtain the undefined primitive value. You can do this using » void(0) » which is similar to » void 0 » as you can see below:
In the actual sense, this works like direct comparison (which we saw before). But we would replace undefined with void(0) or void 0 as seen below:
Conclusion
In this article, we learned how to check if a variable is undefined and what causes a variable to be undefined.
We also learned three methods we can use to check if a variable is undefined. All methods work perfectly. Choosing your preferred method is totally up to you.
undefined
Значение глобального свойства undefined представляет значение undefined . Это одно из примитивных значений JavaScript.
| Атрибуты свойства undefined | |
|---|---|
| Записываемое | нет |
| Перечисляемое | нет |
| Настраиваемое | нет |
Интерактивный пример
Синтаксис
Описание
undefined является свойством глобального объекта, то есть, это переменная в глобальной области видимости. Начальным значением undefined является примитивное значение undefined .
В современных браузерах (JavaScript 1.8.5 / Firefox 4+), undefined является ненастраиваемым и незаписываемым свойством, в соответствии со спецификацией ECMAScript 5. Даже когда это не так, избегайте его переопределения.
Переменная, не имеющая присвоенного значения, обладает типом undefined . Также undefined возвращают метод или инструкция, если переменная, участвующая в вычислениях, не имеет присвоенного значения. Функция возвращает undefined , если она не возвращает какого-либо значения.
Поскольку undefined не является зарезервированным словом (en-US), он может использоваться в качестве идентификатора (имени переменной) в любой области видимости, за исключением глобальной.
Примеры
Пример: строгое сравнение и undefined
Вы можете использовать undefined и операторы строгого равенства или неравенства для определения того, имеет ли переменная значение. В следующем коде переменная x не определена и инструкция if вычисляется в true .
Примечание: здесь используется оператор строгого равенства (идентичности) вместо простого оператора равенства, поскольку x == undefined также проверяет, является ли x равным null , в то время как оператор идентичности этого не делает. null не эквивалентен undefined . Для более подробной информации смотрите операторы сравнения (en-US).
Пример: оператор typeof и undefined
В качестве альтернативы можно использовать оператор typeof :
Одной из причин использования оператора typeof может быть та, что он не выбрасывает ошибку, если переменная не была определена.
Однако, уловки такого рода должны избегаться. JavaScript является языком со статической областью видимости, так что узнать, была ли переменная определена, можно путём просмотра, была ли она определена в охватывающем контексте. Единственным исключением являет глобальная область видимости, но глобальная область видимости привязана к глобальному объекту, так что проверка существования переменной в глобальном контексте может быть осуществлена путём проверки существования свойства глобального объекта (например, используя оператор in ).
How can I check for "undefined" in JavaScript? [duplicate]
What is the most appropriate way to test if a variable is undefined in JavaScript?
I’ve seen several possible ways:
![]()
16 Answers 16
If you are interested in finding out whether a variable has been declared regardless of its value, then using the in operator is the safest way to go. Consider this example:
But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the in operator for a more robust check.
If you are interested in knowing whether the variable hasn’t been declared or has the value undefined , then use the typeof operator, which is guaranteed to return a string:
Direct comparisons against undefined are troublesome as undefined can be overwritten.
As @CMS pointed out, this has been patched in ECMAScript 5th ed., and undefined is non-writable.
if (window.myVar) will also include these falsy values, so it’s not very robust:
Thanks to @CMS for pointing out that your third case — if (myVariable) can also throw an error in two cases. The first is when the variable hasn’t been defined which throws a ReferenceError .
The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example,
I personally use
Warning: Please note that === is used over == and that myVar has been previously declared (not defined).
I do not like typeof myVar === «undefined» . I think it is long winded and unnecessary. (I can get the same done in less code.)
Now some people will keel over in pain when they read this, screaming: «Wait! WAAITTT. undefined can be redefined!»
Cool. I know this. Then again, most variables in Javascript can be redefined. Should you never use any built-in identifier that can be redefined?
If you follow this rule, good for you: you aren’t a hypocrite.
The thing is, in order to do lots of real work in JS, developers need to rely on redefinable identifiers to be what they are. I don’t hear people telling me that I shouldn’t use setTimeout because someone can
Bottom line, the «it can be redefined» argument to not use a raw === undefined is bogus.
(If you are still scared of undefined being redefined, why are you blindly integrating untested library code into your code base? Or even simpler: a linting tool.)
Also, like the typeof approach, this technique can «detect» undeclared variables:
But both these techniques leak in their abstraction. I urge you not to use this or even
To catch whether or not that variable is declared or not, you may need to resort to the in operator. (In many cases, you can simply read the code O_o).
But wait! There’s more! What if some prototype chain magic is happening…? Now even the superior in operator does not suffice. (Okay, I’m done here about this part except to say that for 99% of the time, === undefined (and ****cough**** typeof ) works just fine. If you really care, you can read about this subject on its own.)