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

173
Vistas
Can function expression be used in forEach method?

Here's my example of code:

let arr = [18, 23, 44, 50];
let obj = {
    name: 'Kate',
};
arr.forEach(let func = function(value) {
    console.log(`${this.name} is ${value} years old`);
}, obj); //SyntaxError

So, it looks like we can use in forEach() method only function declaration and arrow function. Am I right or just missing something?

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

0

Using let, var, or const where a callback function is expected is the SyntaxError. You could drop let and the code will run fine or you could declare the function outside of forEach and call it within forEach as follows:

let func = function(value) {
    console.log(`${this.name} is ${value} years old`);
};
arr.forEach(func, obj);

In the code below, I show the original code you provided without the let keyword in the forEach call to show that it works. I also added the suggested function declaration and the corresponding forEach call.

let arr = [18, 23, 44, 50];
let obj = {
  name: 'Kate',
};

console.log('\tfunc');
arr.forEach(func = function(value) {
  console.log(`${this.name} is ${value} years old`);
}, obj);

console.log('\tfunc2');
let func2 = function(value) {
  console.log(`${this.name} is ${value} years old`);
};
arr.forEach(func2, obj);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use it without the assignment. The name (func) is optional.

let arr = [18, 23, 44, 50];
let obj = {
    name: 'Kate',
};
arr.forEach(function func(value) {
    console.log(`${this.name} is ${value} years old`);
}, obj);

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