Tips for JavaScript syntax: Avoid using incorrect left hand in prefix expressions while auto formatting

Upon inheriting a codebase, also known as "legacy code," I have been extremely cautious not to make any unintended changes. While attempting to auto-format the code, I encountered an error.

The function in question is meant to sort a chart. There is a part of the code that appears confusing to me:

function sortChartBy(field,dir=1) {
    if(g_sortMethod != field){
        g_sortDir = 1;
    }
    g_sortMethod = field;
    g_sortDir = g_sortDir * -1 * dir;
    
    var ranks = g_chart["ranks"];
    var sortMethod = g_sortMethod;
    var sortDir = g_sortDir;
    
    var sortFunc = undefined;
    if(field == "release_date"){
        sortFunc = function(a,b){
            var aVal = a[sortMethod];
            var bVal = b[sortMethod];
            if(aVal == "1970-01-01") aVal = "9999--99-99";
            if(bVal == "1970-01-01") bVal = "9999-99-99";
            if(aVal < bVal) return -1 * sortDir;
            if(aVal > bVal) return  1 * sortDir;
            return 0;
        };
    }else{
        sortFunc = function(a,b){
      var aVal = a[sortMethod];
      var bVal = b[sortMethod];

      // ###### QUESTION HERE ########################################
      if (aVal == -1 && bVal !=- -1) return 1; 
      // 'bVal !=- -1' What does that mean? Why '-' directly after '!='

      if (aVal != -1 && bVal == -1) return -1;
      if (aVal < bVal) return -1 * sortDir;
      if (aVal > bVal) return  1 * sortDir;
      return 0;
        };
    }
    
    ranks.sort(sortFunc);
    renderChart();
}

Utilizing IntelliJ as my IDE, I noticed that during auto-formatting, the '-' character following '!=' moves one position to the right in the line:

if (aVal == -1 && bVal != --1) return 1; // Invalid left hand side in prefix expression

IntelliJ displays an error indicating

Invalid left hand side in prefix expression
and marks the '1' with a red underline as erroneous.

I am puzzled by the presence of two minuses separated by a space !=- -1 in the original code and why this would trigger an error upon autoformatting. Although the code functions correctly in its original form, I haven't encountered !=- syntax in JavaScript before, which raises doubts about its validity.

I am seeking clarification on why the line

if (aVal == -1 && bVal !=- -1) return 1;
executes without issue initially but throws an error post autoformatting.

How should the correct code be structured?

Answer №1

Please help me understand why the line of code

if (aVal == -1 && bVal !=- -1) return 1;
initially appears to be functioning properly, but then encounters an error after autoformatting.

It seems that the formatting tool is causing issues with this specific line of code, although I suspect there was already an underlying problem. :-) The formatter is essentially altering the code's meaning, transitioning it from valid-but-potentially-incorrect syntax to outright invalid syntax :-D )

Credit goes to Mellet who pointed out that after running the code through a different formatter, I now grasp why the original version actually works: It revolves around the double use of the unary - operator.

Therefore, in the line != - -1, we are effectively dealing with != -(-1), which eventually simplifies to != 1.

However, it is highly likely that this discrepancy is a typo and the intention was originally to verify against -1 rather than 1.

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

How much does it typically cost to implement external libraries into a project?

Here are some of the most commonly used front-end web development libraries: jquery-min.js (95.9 kB) angular.min.js (108.0 kB) bootstrap.min.css (113.5 kB) bootstrap-theme.min.css (19.8 kB) bootstrap-fonts (185.7 kB) bootstrap.min.js (35.6 kB) All in al ...

Generate an array of arrays containing objects using different variable names

Here is the issue at hand: const data : [ {labelSlug: 'cola', category: 'catering', subCategory: 'drinks', provider: 'coca cola'}, {labelSlug: 'cola', category: 'catering', subCategory: 'drin ...

Navigate to the top of the shiny dashboard panel using the sidebarmenu

Exploring the captivating shiny dashboard example illustrated below (adapted from ). One might ponder if there's a way to seamlessly scroll within one tab item, and upon transitioning to another tab item by selecting it in the sidebar, end up at the t ...

Guide to creating an Angular JS function that can output a specific value

Issue Description: Having trouble with an AngularJS function that retrieves data from a service, concatenates certain columns, and then returns the concatenated data. AngularJS Function: $scope.findCompanyAddressById = function( cmpId ) { var addres ...

Best practices for passing an object/variable to a layout view in SailsJS

Hello, I am curious about the proper way to pass a variable or object to a layout view. Currently, this is what I am doing and it seems to be effective: index: function(req, res){ res.view({ layout: 'mylayout', myvar: 'This is a view var& ...

Correcting Typing Errors in TypeScript

My current challenge involves a method that is consuming data from an external API: public async getStatus(id: string): Promise<APIRes | undefined> { try { const result = await getRequest(`${this.URL}/endpoint/${id}`) const respo ...

Creating responsive list items using Bootstrap 4 and Flexbox: Adjusting the width of <li> elements to fit within containers

Struggling with expanding li elements to match the container width? Despite tweaking individual widths and Flexbox properties, the desired outcome remains elusive. How can the width of each li be adjusted to align with the container, mirroring the dimensio ...

There was an unexpected error encountered while trying to use Jade

I encountered an error in my jade template: Error: E:\Do\hello_express\node_notes\views\simple.jade:6 4| meta(charset="utf-8") 5| meta(name="viewport",content="width=device-width,initial-scale=1,maximum-scal ...

What is the best way to update content without having to refresh the entire page?

I need to update the content of the page without having to reload it using JavaScript. Unfortunately, my current method isn't working. window.location.assign("#/invoice/" + $scope.invoiceId); ...

Navigating to the Top of the Page

I am facing an issue with my webpage that is similar to the code provided below: var btn = document.getElementById('test') test.addEventListener("click", function(){ window.scroll(0,0) }) .wrap { overflow-y: scroll; position: absolute; ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Angular: The $scope object is failing to retrieve data from the HTML elements

I am encountering an issue with this code where the variable $scope.cityName is coming up as undefined, even though I am expecting data from the View/HTML. app.controller("citycontroller", function ($scope, cityfactory) { $scope.searchByCid = func ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

Error: The React component throws a TypeError because it is unable to read the property 'map' from an undefined source

I encountered the following error TypeError: Cannot read property 'map' of undefined at ListItemFactory.ts:84:57 at The specific line where the error occurs is: return announcementitems=json.value.map((v,i)=>( To provide mor ...

Managing various types of form tags within a function-based view in Django

Coding Challenge: <form method="POST" enctype="multipart/form-data" id="p_formUpload"> {% csrf_token %} <fieldset class="form-group"> <p> { p_form|crispy }} </p> </fieldset> </form> ...

A guide on sorting through a multi-dimensional array list in a ReactJS application

I've recently attempted to incorporate a search feature into a multi-array list. The objective is to search for specific keywords within the array, but I encountered an error during my attempts. Array for Searching: const listComponent = [{ i ...

I am looking to implement a Mouseover effect on my Canvas element using JavaScript

To create a mouseover effect only on a specific canvas location, I have developed the MousePosition function (as seen below). The commands for the mouseover effect should be implemented within the MouseOverButton function. However, despite my efforts, it ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

FilterTextBoxExtender in AJAX enables the input of carriage returns

I need assistance with a multi-line text box that I'm using an AJAX FilteredTextBoxExtender on to restrict user input to just numbers. However, I also want users to be able to add a new line by pressing the enter key. I've looked around for a sol ...

Switching class on a specific element in Angular 2

My element list appears like this: <ul *ngFor="let period of periodsDate"> <li [class.show]="isShown" (click)="toggleClass()"> <a>{{ period.id }} </a> </li> </ul> ...