Using optional chaining and logical assignment in JavaScript

I am facing an issue while trying to determine if a property exists in my object or not. If it exists, I want to increase a number associated with it; if it doesn't, I want to create the property and set the value to 1. I have tried using optional chaining and logical assignment, but encountered the following error: Uncaught SyntaxError: Invalid left-hand side expression in postfix operation Could you please help me identify the problem? Here is the code snippet:

const scores = {};
for (const player of Object.values(game.scored)) {
  scores?.[player]++ && scores[player] = 1;
}

For reference, the variable game.scored contains 4 names.

I managed to achieve the desired outcome using a ternary operator, but I am curious as to why it did not work with optional chaining and logical assignment.

Answer №1

When dealing with an optionally chained expression, it is important to note that you cannot assign a value to it. This type of expression cannot be on the left side of an assignment.

In order for it to work, you would need something like this:

a?.foo = 1

But what happens if a is null? You would essentially be creating the statement undefined = 1.

In your specific case, you are attempting to make this work:

 scores?.[player] = scores?.[player] + 1

However, if scores is null, you would end up with undefined = undefined + 1, which does not make sense in terms of assignment.


It is important to realize that the syntax being used here is incorrect. Writing scores?.[player] right after assigning scores = {} does not make sense. The intention should be to check whether scores[player] already exists, not whether scores is null. You can learn more about this concept here: How to check if object property exists with a variable holding the property name?

Answer №2

  totalScores[player] = (totalScores[player] ?? 0) + 1;

In this situation, the code (totalScores[player] ?? 0) is used to determine if the value on the left is null. If it is, then the value on the right is returned. If the value is not null, then the left value is returned. So, totalScores[player] will be updated to totalScores[player] + 1 if it already exists, or it will be created and set to 1 if it doesn't. Hope this helps!

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

Screen white on the right side

I am encountering an issue where my screen shows white on the side when I scroll to the right. I am unsure how to remove it and cannot locate the problem in the code. Here is a link to the code: https://jsfiddle.net/y3j01hbt/ In the provided code, there i ...

Tap, swipe the inner contents of a <div> element without being inside it

(Make sure to check out the image below) I'm facing an issue with a <div> on my website. It's not taking up the full width of the page, and the scrolling functionality within the <body> is not working as expected. I just want the cont ...

Highlight all the written content within the text box

I'm struggling with a piece of code that is supposed to select all the text inside an input field: <input id="userName" class="form-control" type="text" name="enteredUserName" data-ng-show="vm.userNameDisplayed()" data-ng-model="vm.enteredUs ...

Emptying the AnyChart (Javascript) container prior to generating new charts

I have been utilizing the anychart JavaScript library to generate a pie-chart from my data, which is dynamically pulled whenever a user modifies a dropdown selection. Below is the code snippet I am employing for this purpose: var stage = anychart.graph ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

Calculating minutes per hour during a specific date range using JavaScript

What is the method to create an array representing minute counts per hour within a specified date range? If we have the following dates: const initial = new Date('2019-04-04 12:14'); const final = new Date('2019-04-04 16:21'); How ca ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

How can I efficiently extract specific data from JSON using AngularJs?

In my array (_users), there are JSON objects. { "User": { "userid":"19571", "status":"7", "active":"1", "lastlogin":"1339759025307", "Stats": [ { "active":"1", "catid":"10918", "typeid":"71", ...

What is the best way to share models across different node.js projects?

In my setup, I have two node.js projects - project A and project B. Project A serves as the main project, while project B is more of an "ad-hoc" project with a specific purpose. The challenge lies in the fact that project B requires access to project A&apo ...

Assigning a value to an attribute as either a "string" or null within JSON Schema while specifying a maximum length

I'm currently working on crafting a JSON schema that supports a nullable attribute. I am aiming to have the ability for specific JSON structures like this one be considered valid: { "some_name" : null } This is how my schema looks like: { "type" ...

Utilize Vue.js - Link computed properties with data()

I am currently working on an input field that needs to be either blank or pre-populated based on certain conditions. Condition A: If the user is a new student, the field should be blank Condition B: If the user is an existing student, the field should be ...

Loading Angular.js scripts into the webpage

My app is built using the MEAN stack. When a user visits the URL: http://localhost:3000/edit/0 Where 0 represents a record id. Initially, it seems like everything should work fine, but I am facing an issue where my scripts are not loading in the edit.js ...

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Error: Custom Service is behaving unpredictably

My latest project involves creating a customized service. While the service function is returning data as expected, I encounter an issue when calling it in the controller - it returns 'undefined'. Service: var toDoListServices = angular.module( ...

"An error occurred when processing the JSON data, despite the JSON

Incorporating Ajax syntax for datatables and angularjs has been my current endeavor. Encountering an invalid JSON response with the following: self.dtOptions = DTOptionsBuilder.fromSource([{ "id": 860, "firstName": "Superman", "lastName": "Yoda" }]) How ...

Differentiate among comparable values through placement regex

I'm currently tackling a challenge involving regex as I work on breaking down shorthand CSS code for the font property. Here is my progress thus far: var style = decl.val.match(/\s*(?:\s*(normal|italic|oblique)){1}/i); style = style ? style ...

Tips for retrieving a cropped image with Croppr.js

Currently, I am developing a mobile application using Ionic 3. Within the application, I have integrated the Croppr.js library to enable image cropping before uploading it to the server. However, I am facing an issue where I am unable to retrieve the cropp ...

discovering obscured information using jquery

I am working on a code snippet where I need to hide the detailed content for display purposes and only show it during printing: <div> <ul> <li> <span style="font-size: 1.25em;"> <strong> ...

I keep encountering a double key error - MongoError: E11000 for the duplicate key error in my database. I currently have two collections set up: one for users and another

I am currently working on a project that requires the following flow: Registration -> Login -> Profile Creation -> The secret page. I have successfully implemented the registration and login routes, but I encountered an error while saving data for ...

Having trouble retrieving response content in Mithril

I've been experimenting with making a request to a NodeJS API using the Mithril framework in my client application. I attempted to fetch data by following their example code: var Model = { getAll: function() { return m.request({method: "G ...