this will do the trick for you

if (!!val) {
    alert("this is not null")
} else {
    alert("this is null")
}
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing
Nullish coalescing operator (??) - JavaScript | MDN
... const count = 0; const text = ""; const qty = count || 42; const message = text || "hi!"; console.log(qty); // 42 and not 0 console.log(message); // "hi!" and not "" The nullish coalescing operator avoids this pitfall by only returning the second operand when the first one evaluates to ...
People also ask

Is null false in JavaScript?
Null is not considered false in JavaScript, but it is considered falsy. This means that null is treated as if it’s false when viewed through boolean logic. However, this is not the same thing as saying null is false or untrue.
🌐
builtin.com
builtin.com › software-engineering-perspectives › javascript-null-check
How to Check for Null in JavaScript | Built In
What is a strict null check?
StrictNullChecks is a feature that treats null and undefined as two separate types, reducing errors and making it easier to find coding bugs. It also has stronger measures for defining variables as null or undefined, ensuring variables are declared as null only when it’s safe to do so.
🌐
builtin.com
builtin.com › software-engineering-perspectives › javascript-null-check
How to Check for Null in JavaScript | Built In
What is a null check?
In JavaScript, null represents an intentional absence of a value, indicating that a variable has been declared with a null value on purpose. On the other hand, undefined represents the absence of any object value that is unintentional. A null check determines whether a variable has a null value, meaning a valid instance of a type exists.
🌐
builtin.com
builtin.com › software-engineering-perspectives › javascript-null-check
How to Check for Null in JavaScript | Built In
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Optional_chaining
Optional chaining (?.) - JavaScript | MDN
By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Nullish coalescing operator '??'
The nullish coalescing operator is written as two question marks ??. As it treats null and undefined similarly, we’ll use a special term here, in this article. For brevity, we’ll say that a value is “defined” when it’s neither null ...
🌐
TypeScript
typescriptlang.org › docs › handbook › release-notes › typescript-2-0.html
TypeScript: Documentation - TypeScript 2.0
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 <T>x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Nullish_coalescing_assignment
Nullish coalescing assignment (??=) - JavaScript | MDN
In fact, if x is not nullish, y is not evaluated at all. ... You can use the nullish coalescing assignment operator to apply default values to object properties.
🌐
Built In
builtin.com › software-engineering-perspectives › javascript-null-check
How to Check for Null in JavaScript | Built In
Logical NOT Operator !: This method works because empty objects are truthy and null is the only falsy object. Object.is(): This is the helper method for changes of state in React, and it operates similar to the === operator.
Published   August 4, 2025
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-check-if-a-variable-is-not-null-in-javascript
How to check if a Variable Is Not Null in JavaScript ? - GeeksforGeeks
August 5, 2025 - One of the most direct and simple ways to check if a variable is not null is to use the strict equality operator !==. This operator checks if the value is strictly not equal to null, ensuring there’s no type coercion.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › null
null - JavaScript | MDN
When checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion. ... typeof null; // "object" (not "null" for legacy reasons) typeof undefined; // "undefined" null === undefined; // false null == undefined; // true null === null; // true null == null; // true !null; // true Number.isNaN(1 + null); // false Number.isNaN(1 + undefined); // true
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-check-if-variable-is-not-null
Check if a Variable is Not NULL in JavaScript | bobbyhadz
Use the strict inequality (!==) operator to check if a variable is not null, e.g. `myVar !== null`.
Top answer
1 of 16
2331

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"
2 of 16
82
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.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-check-for-null-in-javascript
JS Check for Null – Null Checking in JavaScript Explained
November 7, 2024 - As you can see, it only returns true when a null variable is compared with null, and an undefined variable is compared with undefined. Object.is() is an ES6 method that determines whether two values are the same. This works like the strict equality operator.
🌐
Medium
medium.com › @gabrielairiart.gi › advanced-javascript-use-of-nullish-coalescing-and-optional-chaining-and-for-efficient-coding-7d1d3fe3eedf
Advanced JavaScript: Use of Nullish Coalescing ?? and Optional Chaining and ?. for Efficient Coding | by Gabriela Iriart | Medium
March 22, 2024 - Choosing between the Nullish Coalescing Operator (??) and the Optional Chaining Operator (?.) ultimately hinges on the particular situation at hand: Employ ?? when you need to assign a default value to a variable that might be null or undefined.
🌐
Chris Pietschmann
pietschsoft.com › post › 2008 › 10 › 14 › javascript-gem-null-coalescing-using-the-or-operator
JavaScript: Null Coalesce using the || Operator | Chris Pietschmann
October 14, 2008 - Since JavaScript returns a boolean value of true when your looking at a variable that is not set to null or undefined, you can use the || (or) operator to do null coalescing. Basically, as long as the first value is not null or undefined it’s ...
🌐
GitConnected
levelup.gitconnected.com › how-to-check-for-an-object-in-javascript-object-null-check-3b2632330296
How to Check for an Object in Javascript (Object Null Check) | by Dr. Derek Austin 🥳 | Level Up Coding
January 5, 2023 - Typically, you’ll check for null using the triple equality operator (=== or !==), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null.
Top answer
1 of 3
170

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 (!)

2 of 3
45

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.

Top answer
1 of 8
142

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+

2 of 8
31

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 null and 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 whereas null and undefined are 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, '', or NaN, then it is falsy as well, even though it is not null/undefined.

🌐
Reddit
reddit.com › r/javascript › [askjs] nullish check in conditional
r/javascript on Reddit: [AskJS] Nullish Check in conditional
August 16, 2024 -

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]

🌐
Javatpoint
javatpoint.com › how-to-check-if-a-variable-is-not-null-in-javascript
How to check if a variable is not NULL in JavaScript - javatpoint
How to check if a variable is not NULL in JavaScript with javascript tutorial, introduction, javascript oops, application of javascript, loop, variable, objects, map, typedarray etc.