this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
There are 3 ways to check for "not null". My recommendation is to use the Strict Not Version.
1. Strict Not Version
if (val !== null) { ... }
The Strict Not Version uses the Strict Equality Comparison Algorithm. The !== operator has faster performance than the != operator, because the Strict Equality Comparison Algorithm doesn't typecast values.
2. Non-strict Not Version
if (val != null) { ... }
The Non-strict Not Version uses the Abstract Equality Comparison Algorithm. The != operator has slower performance than the !== operator, because the Abstract Equality Comparison Algorithm typecasts values.
3. Double Not Version
if (!!val) { ... }
The Double Not Version has faster performance than both the Strict Not Version and the Non-Strict Not Version. However, the !! operator will typecast "falsey" values like 0, '', undefined and NaN into false, which may lead to unexpected results, and it has worse readability because null isn't explicitly stated.
Videos
Is null false in JavaScript?
What is a strict null check?
What is a null check?
Update
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null or undefined, and otherwise returns its left-hand-side operand.
Old Answer
Please check compatibility before using it.
The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):
var whatIWant = someString || "Cookies!";
There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
Clarification
Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
This means:
var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
function coalesce() {
var len = arguments.length;
for (var i=0; i<len; i++) {
if (arguments[i] !== null && arguments[i] !== undefined) {
return arguments[i];
}
}
return null;
}
var xyz = {};
xyz.val = coalesce(null, undefined, xyz.val, 5);
// xyz.val now contains 5
this solution works like the SQL coalesce function, it accepts any number of arguments, and returns null if none of them have a value. It behaves like the C# ?? operator in the sense that "", false, and 0 are considered NOT NULL and therefore count as actual values. If you come from a .net background, this will be the most natural feeling solution.
To my knowledge, there is no such operator and also no proposal to add one. Instead you can rely on the standard way to check for nullish values: b == null
a = b == null ? b : func(b)
This will not answer the question since it was already answered by @str, I'm just posting this here because I don't have enough rep to comment on @Dalou's answer and don't want people to trip on that answer.
a = (b ?? false) && other
Is not the opposite of ??, since a will take the value of b if b is a falsy value other than undefined/null, like '' or 0 for example.
The opposite of ?? should set a to the value of other even if b is '' or 0.
It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null.
It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says:
A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.
// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
// Throw exception if e is null or invalid entity
}
function processEntity(e?: Entity) {
validateEntity(e);
let s = e!.name; // Assert that e is non-null and access name
}
Edit
There's an issue for documenting this feature: Document non-null assertion operator (!)
Non-null assertion operator: !
- You tells the TS compiler that the value of a variable is not
null | undefined - Use it when you are in possession of knowledge that the TS compiler lacks.
Here is a trivial example of what it does:
let nullable1: null | number;
let nullable2: undefined | string;
let foo = nullable1! // type foo: number
let fooz = nullable2! // type fooz: string
It basically removes null | undefined from the type
When do I use this?
Typescript is already pretty good at inferring types for example using typeguards:
let nullable: null | number | undefined;
if (nullable) {
const foo = nullable; // ts can infer that foo: number, since if statements checks this
}
However sometimes we are in a scenario which looks like the following:
type Nullable = null | number | undefined;
let nullable: Nullable;
validate(nullable);
// Here we say to ts compiler:
// I, the programmer have checked this and foo is not null or undefined
const foo = nullable!; // foo: number
function validate(arg: Nullable) {
// normally usually more complex validation logic
// but now for an example
if (!arg) {
throw Error('validation failed')
}
}
My personal advice is to try to avoid this operator whenever possible. Let the compiler do the job of statically checking your code. However there are scenarios especially with vendor code where using this operator is unavoidable.
2020 Answer, It Exists!!!
You can now directly use ?. inline to test for existence. It is called the Optional Chaining Operator, supported by all modern browsers.
If a property exists, it proceeds to the next check, or returns the value. Any failure will immediately short-circuit and return undefined.
const example = {a: ["first", {b:3}, false]}
example?.a // ["first", {b:3}, false]
example?.b // undefined
example?.a?.[0] // "first"
example?.a?.[1]?.a // undefined
example?.a?.[1]?.b // 3
domElement?.parentElement?.children?.[3]?.nextElementSibling
To ensure a default defined value, you can use ??. If you require the first truthy value, you can use ||.
example?.c ?? "c" // "c"
example?.c || "c" // "c"
example?.a?.[2] ?? 2 // false
example?.a?.[2] || 2 // 2
If you do not check a case, the left-side property must exist. If not, it will throw an exception.
example?.First // undefined
example?.First.Second // Uncaught TypeError: Cannot read property 'Second' of undefined
?. Browser Support - 94%, Oct '22
?? Browser Support - 94%
Node Support - v14+
Update 2020
This long-wished feature is now available in JavaScript!
I'll redirect to Gibolt's answer, which covers it well.
Original 2018 answer
There is no "null-safe navigation operator" in Javascript (EcmaScript 5 or 6), like
?.in C#, Angular templates, etc. (also sometimes called Elvis operator, when written?:) , at least yet, unfortunately.You can test for
nulland return some dependent expression in a single line with the ternary operator?:, as already given in other answers :
(use === null to check only for nulls values, and == null to check for null and undefined)
console.log(myVar == null ? myVar.myProp : 'fallBackValue');
in some cases, like yours, when your variable is supposed to hold an
object, you can simply use the fact that any object is truthy whereasnullandundefinedare falsy values :if (myVar) console.log(myVar.myProp) else console.log('fallbackValue')You can test for falsy values by coalescing to boolean with
!!and make this inline :console.log(!!myVar ? myVar.myProp : 'fallbackValue');Be very careful though with this "falsy test", for if your variable is
0,'', orNaN, then it is falsy as well, even though it is not null/undefined.
I feel like an idiot as this feels like it should be an obvious answer, but every time this has come up I've failed to think of a satisfactory answer, and google with such basic terms is useless.
If I have a value that I want to put in a full conditional (an if() ) to check if it is nullish (null or undefined) but not falsy, what's a clean, concise, and clear syntax?
We have the nullish coallescing operator, but that acts like the ternary/conditional operator and not like a comparison operator. If I have a block of statements I want to run IF the value is nullish (or if it is NOT nullish) but not falsy, I don't feel like I have any option other than to say the explicit if ( value === undefined || value === null ) {...}
I can write my own isNullish() or use constructs like if( !(value ?? true) ) { ...} but these are awful, and I feel like I must be missing something obvious.
This obviously isn't a big deal, checking the two values isn't terrible, but is there something I'm missing that lets me say if( ??nullish ) { ... } when I have more than simple defaulting to do?
[Edit: The answer I was seeking is value == null or value == undefined, as these specific checkes are an exception to the normal practice of avoiding loose comparison, if nullish is what I want to check for. Thanks for the help, I was indeed missing something basic]