What causes a JavaScript function to return undefined?

Challenge: Find the indices of two numbers in an array that add up to a specific target. For example, given nums = [2,7,11,15] and target = 9, the output should be [0,1] because nums[0] + nums[1] equals 9.

Having trouble with a JavaScript function called TwoSum that should solve this problem? You're not alone! It's frustrating when the code works in Python but returns undefined in JavaScript. I noticed that the function doesn't even enter the second loop, which is strange.

var twoSum = function(nums, target) {
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] >= target) {
      continue;
    }
    for (let j = i; j < nums.length; j++) {
      if (nums[j] >= target) {
        continue;
      }
      if (nums[i] + nums[j] === target) {
        const ans = [i, j];
        return ans;
      }
    }
  }
};
console.log(twoSum([2,7,11,15],9));

Any assistance would be greatly appreciated.

Answer №1

There is a typo mistake in your code. Please correct legth to length in the second loop.

var twoSum = function (nums, target) {
      for (let i = 0; i < nums.length; i++) {
        if (nums[i] >= target) {
          continue;
        }
        for (let j = i; j < nums.length; j++) {
          if (nums[j] >= target) {
            continue;
          }

          if (nums[i] + nums[j] === target) {
            const ans = [i, j];
            return ans;
          }
        }
      }
    };

    console.log(twoSum([2, 7, 11, 15], 9));

Answer №2

Although this question is old, I still wanted to provide my input.

Nested loops can be quite perplexing. One suggestion I have is to ensure that your variable, ans, is defined in the main scope of the function to avoid any issues with returning it;

Alternatively, I highly recommend utilizing Array.reduce() as it is the current best practice. You can find my solution on leetcode:

var twoSum = function(nums, target) {

let acc = nums.reduce((acc, curr, currIndex, array) => {
    array.forEach((number, index) => {
        
        if(number + curr === target && index !== currIndex) {
            acc = [currIndex, index];
        }
    })
    
    return acc;
}, []);

return acc.sort();

};

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

Unable to fetch the identification number from the database

I'm encountering an issue with retrieving the ID from my database: https://i.sstatic.net/oSAi8.jpg Here is a snapshot of my database: https://i.sstatic.net/j5PpZ.jpg Below is my event controller class: <?php namespace App\Http\Contro ...

Utilizing JQuery to select list items for pagination purposes

I am currently working on a pagination script and everything seems to be functioning well, except for one minor issue. I am struggling with triggering an action when the page number (li) is clicked. The pagination data is being retrieved via ajax and disp ...

Ways to modify an object similar to manipulating an array collection

Hey there, I've heard that iterating and editing objects (not arrays) is not the best practice. Is there a more efficient way to do it as easily as it can be done with an array of objects? Check out this link for reference new Vue({ el: '#app ...

Navigating between iframes using InternJS

I am facing the challenge of switching to an iframe with a dynamically changing name and id. <iframe name="easyXDM_1435765828615" id="easyXDM_1435765828615">...</iframe> While exploring LeadFoot, I came across the switchToFrame() function. Ho ...

Unexpected outcomes when rigging a .dae model in Three.js with Blender

I have been working on creating a rigged model for use in a browser using Three.js. Before rigging the model, it loads perfectly fine, allowing me to move and rotate it without any issues. However, after rigging the model, the pieces load in different loca ...

Troubleshooting JQuery AJAX HTML Problems in Google Chrome and Firefox

I'm facing an issue with my code and I'm not sure what to do. It works perfectly on Internet Explorer, but when I try to open it on Chrome or Mozilla, the links in my menu don't work! I click on them but nothing happens. Can someone please h ...

How can we stop the page from scrolling after a click?

Upon clicking the link labeled Click Me, the page automatically scrolls back to the top. This behavior is not desired. How can I correct this issue? For example, here is a link to a relevant resource: http://jsfiddle.net/Y6Y3Z/ Regarding the scroll-bar: ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Logging in using Selenium WebDriver in Java

I'm just starting out with selenium webdriver and I need to automate a webpage for my project. Right now, I'm working on the login page but I'm having trouble with the login button. I'm not sure which locator to use for it. The login bu ...

Encountering infinite loop in Node modules triggering a Catch-22 situation while attempting to use M

I have been working on a project that involves using some customized Node.js modules. I have developed a 'helpers' module that helps with loading various helper methods: /helpers/index.js: var mutability = require('./mutability'), ...

What is the best way to conceal certain choices in a dropdown menu?

How can I display only the cities in Australia in a dropdown list? I have tried to find "Australia" in the options and hide everything before and after it, but I have been unsuccessful! Here is my fiddle. <select class="dropdown" id="dropdown"> ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Modify the variable for each VU in K6 (refresh token)

When I start my K6 test, I utilize my setup() function to obtain a token that will be used by every VU. I want each VU to have the same token, rather than generating individual tokens for each one. Although this works fine initially, the challenge arises ...

Error message: The specified file or directory named '-stylus' could not be found

Encountered an error message while using stylus with npm on my Linux machine. After installing nodejs from GitHub, I executed the command npm install -g stylus autoprefixer-stylus and received the following error log: npm ERR! Error: EACCES, unlink ' ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

Component that dynamically changes background images in Vue

I'm currently working on a Vue banner that requires a dynamic background, but for some reason, it's not functioning as expected. I've experimented with different methods, and using an image tag like this works: <img :src="require(`@/asse ...

What is the best way to transform the incoming data using JavaScript?

The data I have from Algolia in my project includes a seconds data presented as an array. This is the method I use to extract the seconds data from Algolia: @if(isset($content['length'])) <div class="flex items-center space-x-6"> ...

obtaining information from newly added form elements in an Angular application

I'm currently working on an app with the MEAN stack. I've managed to dynamically add form elements, but I'm running into an issue where all dynamically added elements are taking the same data when I use ng-model="something.something". What I ...

Removing items dynamically from a list created using ng-repeat

I have an array of nested JSON objects and I am using ng-repeat to create a list with the nested arrays. My goal is to dynamically delete items from this list upon button click by calling a function in the controller: $scope.remove= function(path){ va ...