Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda