JavaScript undefined variable detection: typeof === "undefined" against double exclamation

A common practice when checking if a variable is undefined in JavaScript is as follows:

var isUndefined=(typeof variableName==="undefined");


I recently came across using two exclamation points to define the same logic:

var isUndefined=!!variableName;



Is it safe to use these methods interchangeably?
Both are equally compatible in different browsers?
Is there a reason why you cannot use "!!" method? (It seems more concise and easy to read)
+4
source share
1 answer

Is it safe to use these methods interchangeably?

. , , ! ( true undefined, , , ). .

?

. . . : .

, "!!" ?

, ! ( , !!) 0, NaN, null, "" false, undefined.

:

var isUndefined = typeof variableName==="undefined";

(() ), undefined. true undefined.

,

var isUndefined = !variableName;

undefined, . - , (0, NaN, null, "", false undefined). true .

, () null undefined, ! . , - undefined, , typeof.

, , ! ReferenceError, ( , undefined), . typeof , , , .

+7

Source: https://habr.com/ru/post/1540343/


All Articles