var whatIWant = null || new ShinyObject(); // is a new shiny objectvar whatIWant = undefined || "well defined"; // is "well defined"var whatIWant = 0 || 42; // is 42var whatIWant = "" || "a million bucks"; // is "a million bucks"var whatIWant = "false" || "no way"; // is "false"
var myEmptyValue = 1;myEmptyValue = null;if ( myEmptyValue === null ) { window.alert('it is null'); }// alerts
在这种情况下,变量的类型实际上是Object。测试它。
window.alert(typeof myEmptyValue); // prints Object
未定义:当一个变量在代码中之前没有定义,并且如预期的那样,它不包含任何值。像这样:
if ( myUndefinedValue === undefined ) { window.alert('it is undefined'); }// alerts
if such case, the type of your variable is 'undefined'.
notice that if you use the type-converting comparison operator (==), JavaScript will act equally for both of these empty-values. to distinguish between them, always use the type-strict comparison operator (===).
// note: this will work only if you're running latest versions of aforementioned browsersconst var1 = undefined;const var2 = "fallback value";
const result = var1 ?? var2;console.log(`Nullish coalescing results in: ${result}`);
// note: this will work only if you're running latest versions of aforementioned browsersconst var1 = ""; // empty stringconst var2 = "fallback value";
const result = var1 ?? var2;console.log(`Nullish coalescing results in: ${result}`);