Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function.

I am seeking clarity on the distinctions between these two operators and guidance on when it is more appropriate to use them over an if statement.

/* --------------------  ?? operator -------------------- */
const foo = null ?? '?? default string';
console.log(foo);

const baz = 0 ?? 10;
console.log(baz);

/* --------------------  && operator -------------------- */

const foo_1 = null && '&& default string';
console.log(foo_1);

const baz_1 = 0 && 20;
console.log(baz_1);

Answer №1

In order to distinguish between operators and determine the appropriate usage, creating a comparison table can be quite helpful:

                        |    ||   |    &&   |    ??   |
    --------------------+---------+---------+---------+
        0, 'default'    |'default'|    0    |    0    |
       '', 'default'    |'default'|   ''    |   ''    |
    false, 'default'    |'default'|  false  |  false  |
     null, 'default'    |'default'|   null  |'default'|
undefined, 'default'    |'default'|undefined|'default'|
     true, 'default'    |  true   |'default'|  true   |
       20, 'default'    |   20    |'default'|   20    |

Answer №2

&& - serves as the logical AND operator.

?? - an operator that returns the right-side expression if the left side is null or undefined.

For instance

if(someValue && otherValue) {
// executes when someValue and otherValue are both true
}

Known as the nullish coalescing operator, ?? simply assigns the right-side value when the left-side is null or undefined.

let foo = someValue ?? "default value"; 
// if someValue is null, assign "default value" to variable foo.

Answer №3

The Nullish Coalescing Operator ?? differentiates between nullish values (null, undefined) whereas the OR operator || or the AND operator && checks for falsy values which include an empty string "", zero 0, false false, null, and undefined.

var x = '';

console.log(x ?? "default"); // ''
console.log(true && x); // ''

var y; // undefined

console.log(y ?? "default"); // 'default'
console.log(true && y); // undefined

Answer №4

The explanation provided in the documentation should clarify the first two statements in your code:

The nullish coalescing operator (??) is a logical operator that returns the right-hand side operand when the left-hand side operand is null or undefined, and it returns the left-hand side operand otherwise.

When it comes to && : The second expression following theAND(&&) operator is only evaluated if the first expression is considered truthy, and then the second expression is returned. If the first expression is not truthy, it gets returned instead.

const foo_1 = null && '&& default string';
console.log(foo_1);

const baz_1 = 0 && 20;
console.log(baz_1);

const baz_2 = 20 && 30;
console.log(baz_2);

Answer №5

When the left-hand side operand of the ?? operator is null or undefined, it returns the right-hand side operand.

const emptyString = ""
const nullValue = null

const valA = emptyString ?? "valA"  // ""
const valB = nullValue ?? "valB" // "ValB"

const valC = emptyString && "valC" // ""
const valD = nullValue && "valD" // null

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...

Assistance with offsetting a jQuery drop down menu

This is the third jQuery script that I've been working on. While parts of it have been inspired by other scripts, I'm now focusing on implementing a specific feature. I've dedicated 4 hours to solving the issue of displaying the submenu on ...

Is it possible to add my own designs to a three.js model?

I am looking to add some personal touches to my three.js model by drawing on it in the scene. How can I achieve this effect of 'graffiti' on my models within the scene? ...

Prevent the bottom row from being sorted

I have implemented sortable table rows in my angular project, however the sorting functionality also affects some query-ui code elements. Now I am looking to exclude the last row from being sortable. HTML <div ng:controller="controller"> <ta ...

Could you explain the distinction among req.path, req.params, and req.query?

I'm curious about the distinctions among req.path, req.params, req.query, and req.body in node.js. Can someone provide an explanation? ...

How can I generate a hyperlink for a specific directory on Github Pages?

If I have a repository with one file and one folder, as listed below: index.html folder The folder contains another file named: work.html My goal is to access the folder website using only the link: username.github.io/repositoryname/folder Instead ...

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

Is there another option besides PHP not being compatible with JavaScript?

I'm looking to dynamically change the properties of a div, so I've turned to using the jquery.keyframes plugin. The second class currently has a low-res blurred background image from the croploads directory. Now my goal is to switch it out for a ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

Storing audio files in Firebase Cloud Database and displaying them in React js + Dealing with an infinite loop problem

Lately, I've been encountering a persistent issue that has proven to be quite challenging. Any assistance would be greatly appreciated. Thank you in advance. The objective is to create a form that allows for the easy addition of new documents to the ...

Leveraging a function for filtering in AngularJS

I have developed an application where the content filter changes depending on which button is clicked. I have managed to figure out the straightforward filters, but now I am attempting to create a filter that displays content within a specified range. Bel ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...

Webpack2 now transforms sass/scss files into JavaScript rather than CSS during compilation

I've created a webpack script to compile all .scss files into one css file. I decided to use webpack instead of gulp or grunt for simplicity, as it can be configured in a single file. However, I am encountering an issue where scss files are being com ...

Achieving optimal performance with scoped CSS in Vue.js

As I work on creating a new app using VueJs, I have noticed the implementation of "css scoped" as shown below: <style scoped> .example { color: red; } </style> <template> <div class="example">hi</div> </template> ...

Apply a specific class using JavaScript/jQuery when a user selects a specific timezone from the user interface

Currently, I am coding in HTML with the code below extracted from this website link. The listings under timezone ET are all correct as they align with the accurate dates; however, for other timezones (PT, MT, CT, AT, NT) some shows seem to be on incorrect ...

Troubleshooting Images in a React Application Integrated with WordPress API

I am struggling to understand why this GET request is consistently returning a 404 error. I have thoroughly tested the URL using Postman and everything seems to be in working order for the title and excerpt, but the images are causing some issues. Does a ...

Configuring JsFiddle with Vue and integrating vue-tables-2 - The variable "t" is not defined

Seeking assistance for implementing the vue-tables-2 package and encountering a persistent issue. Despite my efforts to set up a jsfiddle, I keep encountering an error stating "t is undefined" even with a simple implementation. Has anyone faced this specif ...