Engaged in revisiting a previous project and stumbling upon unfamiliar code

I need help understanding the code below. It's a bit confusing to me, but I really want to understand it.

reverse = [-1, 1][+!!reverse];

Answer №1

Assume the value of reverse is 5. When we evaluate !5, it becomes false because all numbers except 0 are considered truthy. If we negate false one more time, we get true. Finally, we can convert this boolean expression to either 1 or 0 by using the + operator.

var reverse = 5;
reverse = [-1, 1][+!!reverse];

This is effectively the same as:

var reverse = 5;
reverse = [-1, 1][1];

To clarify further, the expression could also be written as:

var reverse = 5;
reverse = [-1, 1][Number(Boolean(reverse))];

Answer №2

Here we have a piece of code crafted by someone who fancied themselves clever, overlooking the importance of not just speed but also readability in great code.

The opening segment

[-1,1] 

creates an array with -1 at index 0 and 1 at index 1.

!!reverse

Changes the value of reverse to a boolean true.

When the unary + operator (operators that take only one argument) is applied, it converts the boolean value of reverse into a number.

Effectively, this means that if reverse is true, it becomes 1. If reverse is false, it becomes -1.

Answer №3

!!reverse will change the variables to a boolean value

+!!reverse' will convert it to either 0 or 1

The resulting number is then used as an index for the array on the left side

Therefore, this entire expression will assign reverse to -1 if the original value was false, or 1 if it was true

A more concise way to express the above would be

reverse = reverse? 1:-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

Unique Google Maps API V3 PEGMAN Customization

Can custom zoom controls and Pegman controls be styled with the same design? To add custom zoom controls, follow the instructions provided in this question's answer: <!DOCTYPE html> <html> <head> <meta name="viewport" cont ...

The PHP random number generator appears to be malfunctioning when being compared to the $_POST[] variable

In this section, random numbers are generated and converted to strings. These string values are then used in the HTML. $num1 = mt_rand(1, 9); $num2 = mt_rand(1, 9); $sum = $num1 + $num2; $str1 = (string) $num1; $str2 = (string) $num2; The following code ...

Distinguishing between web development, frontend, and backend: Identifying ownership of an entity by a user

In my web application, I have a setup where each user can have multiple projects and each project can have multiple users. This relationship is managed through three tables in the database: user, project, and user2project which maps the n:m relation betwee ...

When a page is changed, the Vue.js Active Menu color remains enabled

Check out my website at . I want to customize the navigation bar so that only the active page's navbar li is colored in red. <div class="navigation-items"> <ul class="nav-list"> <li class="nav-item"><nuxt-link to="/en" ...

Protect a one-page application using Spring's security features

After successfully developing a single page application using JavaScript, I incorporated a few jQuery commands and Twitter Bootstrap for added functionality. The method used to load my page is demonstrated below: $('#contact').click(function () ...

-g option must be enabled for jscoverage to function properly

To install jscoverage globally, use the following command: npm install jscoverage -g Do you know what purpose the -g option serves? Without using the -g option, my system does not recognize jscoverage as a valid command. ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Handling AJAX requests using jQuery

I'm currently in the process of learning how to utilize jQuery Ajax. Could you explain to me the significance of function(response), as well as what exactly is meant by response == 1 and response == 2? jQuery.post(ajaxurl, data, function(response) { ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly. I'm unsure how to properly implement the logout method in the current context to allow for succes ...

The Angular method for retrieving the child's ID when it is clicked

As a newcomer to Angular 1.0 with a background in jQuery, I am facing the following scenario: Let's imagine we have the following HTML structure : <div id="filters"> <div id="filter1">Filter 1</div> <div id="filter2"> ...

Using Javascript, dynamically animate the text in the hero unit with fading in and out effects

I currently have a "Hero" unit with the following code: <div class="hero-unit"> <div class="container"> <h1>Dapibus Euismod Mollis</h1> <p>Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

Is it best practice to initialize loaded scripts before the JQuery .load callback is called or should it be done after the .ready callback in the loaded script?

When I click a button in my main document, I load the content of a specific div using jQuery: $("#my_div").load(function() { alert("Content Loaded"); }); The loaded content contains a script: <script> alert("Initial Alert from External Script" ...

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

What is the best way to tailor specific text in d3.js?

I need assistance with customizing the appearance of an asterisk added to the end of a template literal in d3js. I want to be able to independently adjust the size and color of the asterisk regardless of the variable it's attached to. Below is the cod ...

Strategies for managing data sharing between PHP and JavaScript

Today, I am seeking your valuable advice. Currently, I am working on a significant legacy project at my company, which involves finding a solution to share constants between our PHP 5 back-end (MVC architecture, no framework) and our front-end with Angula ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

Is there a way to utilize flex or other CSS properties to wrap element content onto the next line, beginning from the start of its container?

Is there a way to wrap the text content of an element onto the next line, starting from the beginning of its container? I'm looking for something similar to the image provided. Can this be achieved using flexbox or other CSS properties? Here's a ...