Posts

Showing posts with the label Undefined

Check If Object Exists In JavaScript

Answer : You can safely use the typeof operator on undefined variables. If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string. Therefore if (typeof maybeObject != "undefined") { alert("GOT THERE"); } There are a lot of half-truths here, so I thought I make some things clearer. Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block). The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined var a; alert(typeof a); // undefined (declared without a value) alert(typeof b); // undefined (not declared) So both a variable that exists and another one that doesn't can report you the undefined type. As for @Kevin's misconception, null == undefined . It is due to type c...

Can An Optional Parameter Be Null In TypeScript?

Answer : To answer my own question after trying... The types null and undefined are handled as separate types. The optional type is special, also allowing arguments to be left out of function calls. 1. Without a union or optional, nothing except the type itself is allowed. function foo(bar: string) { console.info(bar); } foo("Hello World!"); // OK foo(null); // Error foo(undefined); // Error foo() // Error 2. To additionally allow null , a union with null can be made. function foo(bar: string | null) { console.info(bar); } foo("Hello World!"); // OK foo(null); // OK foo(undefined); // Error foo() // Error 3. Allowing undefined works similarly. Note that the argument cannot be left out or null . function foo(bar: string | undefined) { console.info(bar); } foo("Hello World!"); // OK foo(null); // Error foo(undefined); // OK foo() // Error 4. You can also allow both, but the argument MUST still be given. function foo(b...