Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!