The nullish coalescing operator in JavaScript is running code on both of its sides

console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist');

console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exist'

orderPizza and orderRissotto are two methods within the object restaurant.

When I use the Nullish Coalescing operator to log them, both the method output and the message 'Method does not exist' get logged. This raises the question of why.

Log:

Your pizza with onion, tomato, and basil is ready
Method does not exist

Answer №1

The concept of the Null Safe is that it returns a value of null, while the Nullish coalescing operator will only return the second piece if the first one is either null or undefined. This means that if a method does not exist, the Null Safe operation will return null and then the second part will be returned. However, if the method exists but returns a value of null or undefined, the first part will run but ultimately the second part will be printed since the Nullish coalescing operator considers these values when deciding whether to return the second part.

Answer №2

let foodPlace = {
  orderBurger: function(arg1, arg2, arg3) {
    return `Your burger with ${arg1}, ${arg2} and ${arg3} is ready`
  },
  orderPasta: function(arg1, arg2, arg3) {
    return `Your pasta with ${arg1}, ${arg2} and ${arg3} is ready`
  }
}


console.log(foodPlace.orderBurger?.('cheese', 'lettuce', 'pickles') ?? "Method not found");

console.log(foodPlace.orderPasta?.('cheese', 'tomato sauce', 'basil')) ?? "Method not found";

When I tried running the above code on my local machine, it executed as expected without any issues.

NOTE: The output of both console.log statements is different.

If you run these commands in the developer tools console, the results may vary.

For the first console.log statement -

console.log(foodPlace.orderBurger?.('cheese', 'lettuce', 'pickles') ?? "Method not found");

the expected result will be printed since the string is returned by the orderBurger method and the Nullish coalescing operator checks that the left side of the expression is NOT null or undefined. Therefore, the console will display -

Your burger with cheese, lettuce and pickles is ready

However, for the second console.log statement -

console.log(foodPlace.orderPasta?.('cheese', 'tomato sauce', 'basil')) ?? "Method not found";

pay attention to the closing parenthesis after the console.log. In this case, the output will be -

Your pasta with cheese, tomato sauce and basil is ready
"Method not found"

The orderPasta method functions correctly and returns a string, which is then passed to the console log method. As the log method does not return anything (void), it evaluates as undefined, causing the Nullish coalescing operator to check the right side as well.

I hope this explanation clarifies things.

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

Delaying UI interactivity until the document is fully loaded

I'm currently developing a web application that must be compatible with Internet Explorer 8 (yes, you read it right, compatible with the HELL). The issue I'm facing is with uploading a file which is later processed by PHP code and then refreshes ...

Creating stunning light effects with camera flash using three.js

I'm working on a website using the amazing three.js library. My current challenge is figuring out how to incorporate a camera flash effect into three.js. Currently, I have a rotating cube in my scene and I would like to have a camera flash occur after ...

Click on the React JS infinite render component to load more items

Just diving into the world of react/next and I'm a bit stuck on this issue. I've searched high and low, tried different solutions, but I can't seem to figure out what I'm missing or not grasping here. I understand that loadStats() is ...

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...

ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding column ...

JQuery table sorter is unable to effectively sort tables with date range strings

I am facing an issue with sorting a column in my table that contains text with varying dates. The text format is as follows: Requested Statement 7/1/2014 - 9/16/2014 When using tablesorter, the sorting does not work properly for this column. You can see ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...

Issue with Angular ngModel not syncing with variable changes

Currently using Angular 4 and Typescript, I have a table containing <select> elements in my template: <tr *ngFor="let task of tasksDetails"> <td>{{task.name}}</td> <td> <select class="form-control" [(ngMode ...

Problem with Jquery Sticky Navigation

I've been struggling to understand this issue and can't seem to find any help. http://fiddle.jshell.net/DQgkE/7/show/ The user experience is currently a bit glitchy, but what I would like is: 1) When scrolling down the page, I want the Sticky ...

Using Dynamic Jinja HTML to Select Elements Dynamically

I have a unique system where forms are dynamically created based on values from a dictionary. Each form is assigned an ID corresponding to the key value and initially hidden. <div id="subforms" style="display: none" > {%for k, v in options.items() ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

Once an email address is entered, kindly instruct the driver to press the tab key twice for navigation

Adding a user to a website involves entering an email address first, which is then checked against the server's list of users. However, the issue arises when the email validation doesn't occur until clicking outside the input box or pressing tab ...

The transition effect of changing opacity from 0 to 1 is not functioning properly in Firefox

Having some trouble with this animation not working in Firefox. I'm triggering the animation using JavaScript after a delay like so: document.getElementById('my_id').style.webkitAnimationPlayState = "running"; I've also attempted: s ...

Tips for designing the microphone appearance on the Google Chrome speech input interface

Google Chrome features an input control for speech recognition. If you want to know how to use it, check out this link. I'm looking to enlarge the microphone icon and possibly use a customized image for it. Increasing the width and height of the inp ...

Different ways to modify the underline and label color in Material-UI's <Select/> component

A while ago, I came across this useful demo that helped me change the colors of input fields. Here is the link: https://stackblitz.com/edit/material-ui-custom-outline-color Now, I'm on a quest to find a similar demo for customizing the color of selec ...

Divergent outcomes observed in various browsers when fetching XMLHttpRequest responseText

Utilizing XMLHttpRequest responseText to retrieve a server txt file and populate the contents of that file into an editable text box has been my recent task. The txt file consists of concise lines of letters separated by new lines. Users have the option to ...

Ways to determine if your code is written in ES6

After completing a lot of Javascript coding, I just learned about the existence of various JS 'versions' such as ES5 and ES6. My project is now up on Github, and someone advised me to convert my ES6 code to ES5 using Babel. The problem is, I&ap ...

ReactJS encounters errors even when the backend is returning a 200 OK status code

My ReactJS frontend receives an error when sending a GET request, even though the django backend terminal shows [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930. I am using redux sagas in my project. In src/index.js: (index.js code snippet here) In ...