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

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

Whenever I adjust the layout of the navigation bar, the edges end up getting clipped

I'm having trouble with the border shape of my navbar. When I try to make it a rounded pill shape, the edges get cut off instead of being properly displayed. https://i.stack.imgur.com/sUN2Y.png Below is the HTML template: <template> <div cl ...

Minimize the count of switch cases that are not empty

How can I optimize the number of cases in my switch statement to align with SonarQube recommendations? Currently, I have 37 cases in a switch statement, but SonarQube recommends only 30. I believe that my code is functioning correctly, and the issue lies ...

Pull data from another domain's DIV using jQuery's load/ajax function

I need to load content from a different domain into a DIV on my JSP page. For example: $("#myDiv").load("https://www.google.com") The issue I'm facing is that the request is being blocked by the browser's same origin policy. I've explore ...

Particles.js fails to persist as I scroll down the HTML page

After creating a website page, I incorporated Particles.js for the background. However, when I scroll down, the particles seem to be confined to the initial corner of the screen and do not continue downward. Here are my current particle settings: #particl ...

Spicing up PHP data insertion into the database

I am working with two fields: one is a textarea and the other is an image field. <textarea name="siteplan" id="siteplan" class="form-control" rows="10"></textarea> The image field looks like this: <input type="file" name="image" id="image ...

Eliminating the "undefined" error in TypeScript within a React application

Having recently dived into TypeScript configuration, I encountered an issue when coding and tried to resolve it by encapsulating the code block in an if statement checking for usersData to eliminate the "Object is possibly undefined" errors. However, upon ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Understanding the response from an AJAX call

VB code Dim temp3 As String = dt.ToString() cmd.Connection = con con.Open() i = cmd.ExecuteNonQuery() con.Close() If i = 1 Then msg = "Record successfully inserted" ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

Is there a way to create a dynamic CSS class without relying on the use of IDs?

Is there a way to create a dynamic CSS class without using an ID? $( "#mydiv" ).css( "width", $("#widthtextbox").val() ); $( "#mydiv" ).css( "height", $("#heighttextbox").val() ); I am looking to implement multiple CSS classes for this task. ...

Django enables anonymous Ajax requests to reach a Generic View

Here is the current progress I have made: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(Configurati ...

Steps for aligning the upper rectangular text in the center of the larger rectangular border

https://i.stack.imgur.com/7yr5V.png I was aware of a particular element in html that had text positioned in the upper left corner, but my knowledge didn't go beyond that. Should I be adjusting the translation on both the X and Y axes based on the par ...

How to insert an image into a placeholder in an .hbs Ember template file

I'm looking to enhance a .hbs template file in ember by incorporating an image. I am not a developer, but I'm attempting to customize the basic todo list app. <section class='todoapp'> <header id='header'> & ...

Issues persist with Ajax form submissions; the submitted data never seems to go through

I have encountered variations of this issue multiple times, but despite analyzing numerous examples, I am unable to determine why my code is not functioning properly. <script> $('document').ready(function(){ $('datafixForm' ...

Error: The variable "Set" cannot be found in the react.js code, specifically in Safari browser

An issue has been identified in Safari where a ReferenceError is thrown: "Can't find variable: Set" when using react.js. This error occurs only in Safari, while all other browsers work perfectly fine. The error message points to the main.js file which ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...

Absent 'dist' folder in Aurelia VS2015 TypeScript project structure

After downloading the Aurelia VS2015 skeleton for typescript, I encountered an issue trying to run the Aurelia Navigation app in IIS Express. One modification that was made to the skeleton was adding "webroot": "wwwroot" to the top level of project.json. ...

Explaining the union type using a list of data types

Is there a way to create a union type that strictly limits values to 'a', 'b', 'c' when using a list like const list: string[] = ['a', 'b', 'c']? I know one method is: const list = ['a' ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...