Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
JavaScript variable returns undefined throughout if statements and loops

I'm trying to do the basic twoSum question from leetcode. My nums array comes back as undefined throughout this function, and I'm totally lost as to why. I'm sure it's obvious, but I'm having a hard time even troubleshooting it, because no matter where I put console logs in this function, it always says that nums is undefined.

const nums = [2, 7, 11, 15];
const target = 9;

function twoSum() {
    if (nums.length > 0) {
        while (nums === Number) {
            for (let i = 0; i < nums; i++) {
                for (let k = 0; k < nums; k++) {
                    if (i + k == target) {
                        console.log([i, k]);
                    } else {
                        console.log("no result");
                    }
                }
            }
        }
    } else {
        console.log("Array is Empty");
    }
};

console.log(twoSum());

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You need to make the following changes in your code. It should fix your issue

  • No need for while (nums === Number) condition
  • replace i + k == target with nums[i] + nums[k] == target. As i and k are indexes not actual values in array
  • Don't use console.log("no result"); in else condition. Instead create a flag and check if it's false then do the console.log Otherwise it will console.log everytime nums[i] + nums[k] !== target.

const nums = [2, 7, 11, 15];
const target = 9;

let  flag = false;
function twoSum() {
  if (nums.length > 0) {
    for (let i = 0; i < nums.length -1; i++) {
      for (let k = 1; k < nums.length; k++) {
        if (nums[i] + nums[k] == target) {
        flag = true;
          console.log('indexes', [i, k], 'values', [nums[i], nums[k]]);
        }
      }
    }
    if (!flag) {
    console.log("No Result")
    }

  } else {
    console.log("Array is Empty");
  }
}

twoSum();

about 4 years ago · Juan Pablo Isaza Denunciar

0

Assumed objective

Given an array of integers and a target, find any pairs of integers in the array whose sum matches the target.

Code Snippet

const nums = [2, 7, 11, 15];
const target = 9;

const twoSum = (tgt = target, arr = nums) => (
  arr.forEach(x => 
    arr.forEach(y =>
      x + y === tgt && console.log(x, y)
    )
  )
);

console.log('target = 9');
twoSum();

console.log('target = 4');
twoSum(4);

console.log('target = 30');
twoSum(30);

console.log('target = 55');
twoSum(100) || console.log('no matches');

Explanation

  • Iterate through the array with each item taken as x
  • Now, iterate again with each item taken as y
  • If the sum of x and y matches target, then console.log

NOTES

  • As seen in the test cases, same numbers may be considered twice. So, for target of 4 the code prints out 2 2.
  • This may be avoided by changing the limits of the outer and inner loops.
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda