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

177
Vistas
Javascript: a function returned a value but when I console.log it, always shows undefined

    var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
            {'date': '11:00', 'electricity': 0.14, 'temp': 50},
            {'date': '11:15', 'electricity': 0.87, 'temp': 35}]
    function findData(time){
        testData.forEach(function(item){
            if(item['date'] == time){
                console.log('item: ', item);
                var result = new Array(item['electricity'], item['temp'])
                console.log('result: ', result)
                return result;
            }
        })
    }
    var a = findData('10:45');
    console.log(a)

Any idea why console.log(a) gives undefined? I have done some research but didn't get the answer:(

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

0

You can not return from a callback for Array#forEach and you need at least a return statment in the function block to get a different value as undefined.

Instead, you could find the object with Array#find, destructure the wanted properties and return an array of values.

function findData(data, time) {
     const result = data.find(({ date }) => date === time);
     if (result) {
         const { electricity, temp } = result;
         return [electricity, temp];
     }
}

var testData = [{ date: '10:45', electricity: 0.49, temp: 49 }, { date: '11:00', electricity: 0.14, temp: 50 }, { date: '11:15', electricity: 0.87, temp: 35 }]

var a = findData(testData, '10:45');
console.log(a)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your function needs to return something. Also, returning something from the forEach() callback won't do it; you have to store that result in a variable that is visible to findData():

function findData(time){
    var r;
    testData.forEach(function(item){
        if(item['date'] == time){
            console.log('item: ', item);
            var result = new Array(item['electricity'], item['temp'])
            console.log('result: ', result)
            r = result;
        }
    })

    return r;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Because you didn't stop the forEach loop after it found result, so the loop keep going to the next index. There are many ways to achieve the result you need. Array.find is one way.

    var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
            {'date': '11:00', 'electricity': 0.14, 'temp': 50},
            {'date': '11:15', 'electricity': 0.87, 'temp': 35}]
    function findData(time){
        const foundItem = testData.find(function(item){
            return item['date'] == time;
        });
        console.log('item: ', foundItem);
        const result = new Array(foundItem['electricity'], foundItem['temp'])
        console.log('result: ', result) 
        return result;
    }
    var a = findData('10:45');
    console.log(a)

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