What is the functionality of this JavaScript code after the "if" statement?

I am having trouble understanding how this code works, especially after the if(y in hash) statement. I don't see any values being pushed into hash initially. Can someone explain what happens behind the scenes and the significance of y in hash?

var twoSum = function(nums, target) {

  const hash = {}
  
  for (const i in nums) {
    const x = nums[i];
    const y = target - x
    if (y in hash)
      return [i, hash[y]]
    hash[x] = i
  }

}

let arr = [2, 3, 4, 5, 6]
console.log(twoSum(arr, 11))

Answer №1

The hash is currently empty and I am not adding any values to it.

When I use hash[x] = i, it adds values to the hash because it falls outside of the if(y in hash) condition.

What does y in hash mean?

As mentioned by Nick Parsons in a comment, "it checks if the key stored in y exists in the hash object (or its prototype chain)."

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

Comparing JSON files in JavaScript to identify and extract only the new objects

I need a way to identify and output the newly added objects from two JSON files based on their "Id" values. It's important for me to disregard changes in object positions within the files and also ignore specific key-value changes, like Greg's ag ...

Tips for creating JavaScript event handlers for Laravel forms

Looking to create a form for my Laravel application that includes text input boxes, radio buttons, and optional values. Here is the basic structure of the form: <html> <head> <title>Form Generation</title> <body> <form act ...

Dropdown menu featuring a customizable input field

Is it possible to have a drop-down list with an input textbox field for creating new items in the same dropdown menu? ...

Incorporating PruneCluster into an AngularJS Leaflet Directive for Enhanced Mapping

I am currently facing an issue with loading clustered markers for geojson data using PruneCluster. The clusters are not appearing on the map and there are no errors showing up in the console to assist with troubleshooting. Below is the snippet of my curr ...

What is the best way to call a JavaScript function with multiple arguments from a Silverlight project?

I encountered an issue when trying to invoke a JavaScript function with multiple arguments from an HTML page. Here is what I am attempting to do: wbNavigator.Navigate(new Uri("http://localhost:56433/route.html", UriKind.Absolute)); object results = wbNavi ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

Displaying a project in the same location using jQuery

Struggling with jQuery and positioning hidden items that need to be shown? I have two white boxes - the left one is the Client Box (with different names) and the right one is the Project Box (with different projects). My goal is to show the projects of a c ...

React, Axios, and the PokeAPI are like a team of explorers navigating an

Trying to enhance my React abilities, I decided to follow this tutorial on creating a list of names using PokeAPI. However, I hit a roadblock at 11.35 into the tutorial while implementing the provided code snippets in both App.js and PokemonList.js: fu ...

Understanding XML parsing problems

I've decided to keep the live xml/atom-feed URL private, as it's hosted on LiveJournal. However, I'm a bit confused about how this all works: let XML_URL = "https://users.livejournal.com/<username>/data/atom"; $(function(){ ...

Adjust the sidebar size in Bootstrap 5 to align perfectly with the navbar brand

https://i.stack.imgur.com/Ra0c7.png I'm trying to ensure that the width of the sidebar on this page aligns consistently with the end of the logo in the top right. However, using variations of col-xxl-1 etc. is causing inconsistent sizes at different ...

how to pass arguments to module.exports in a Node.js application

I have created a code snippet to implement a Node.js REST API. app.js var connection = require('./database_connector'); connection.initalized(); // I need to pass the connection variable to the model var person_model = require('./mod ...

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

Tips for changing a "raw" DOM Event into a React SyntheticEvent

Currently, I am working with two separate libraries. The first library emits "raw" DOM events (lib.dom.d.ts), while the other library consumes React.SyntheticEvents. I am seeking advice on the most efficient method to transform the raw event into a Synthe ...

Unable to establish a connection with the default port on Mongo DB while utilizing Node.js

I am new to using Node.js and I'm trying to establish a connection with MongoDB in my Node.js application, but I'm encountering issues. Here is the code snippet: var mongo = require("mongodb"); var host="127.0.0.1"; var port=mongo.Connection.DE ...

Choosing the subsequent div after the current one using Jquery

I am currently in the process of creating a drop-down menu button that, when clicked, reveals the previously hidden div underneath it. The code is functioning properly without the use of $(this).next, but it is displaying all divs with the class .menudrop ...

What is the best way to design a footer that remains fixed at the bottom of the screen but becomes unfixed when the user scrolls down?

Currently, I am working on creating a footer that remains fixed at the bottom of the user's screen regardless of the screen size. However, I also want the header to transition from a fixed position to being part of the page when the user scrolls down. ...

Stop the sudden jump when following a hashed link using jQuery

Below is the code snippet I am working with: $( document ).ready(function() { $( '.prevent-default' ).click(function( event ) { event.preventDefault(); }); }); To prevent the window from jumping when a hashed anchor ...

Utilizing Firebase in place of .json files for the AngularJS Phonecat application

I am currently exploring firebase and attempting to retrieve data using this service from firebase instead of json files. However, I have encountered some challenges in getting it to function properly. This is inspired by the angularjs phonecat example .f ...

jQuery selector for attributes with values that are higher than a specific amount using the ">" symbol or lower than a certain value using the "<" symbol

I currently have several div elements with the following structure: <div class="roomnamecta" data-price="1189" data-adult="3">Room 1</div> <div class="roomnamecta" data-price="578" data-adult ...