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

144
Vistas
JavaScript function that returns an object

This function is supposed to return an object, however, the construction used below is unfamiliar to me. How does this function work?

function expect(value) {
  return {
    toBe: exp => console.log(success)
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This is a standard JavaScript function:

function(parameter1, parameter2) {
    return returnVal;
}

But the object that is being returned looks like this:

{
    toBe: exp => console.log(success)
}

Which is an object containing an ES6 arrow function, and can be alternatively expressed like so (a direct translation to an ES5 function):

{
    toBe: function(exp) { 
        return console.log(success);
    }
}

Read here for more information on ES6 arrow function notation.

about 4 years ago · Juan Pablo Isaza Denunciar

0

I think it worth emphasizing that returns an object with a key that contains a function as a value. You can run it in the same way to run a method belonging to a class. Obliviously it fails because there is no success defined.

function expect(value) {
  return {
    toBe: exp => console.log(success)
  }
}

let res = expect('value')
console.log(res)
res.toBe('test')

I would say that this is the intent of the code, imo this makes a lot of sense; the evaluation is done when toBe is invoked, this invokes console.log(which tests the condition, when is invoked and prints the result):

function expect(value) {
  return {
    toBe: exp => console.log(exp === value)
  }
}

expect('value').toBe('value')
expect('notvalue').toBe('value')

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