3

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)
  }
}
2
  • 1
    Is there a particular part of this code that you don't understand? You seem to understand that it is returning an object already (which is what the {} is after the return)? Commented Jun 8, 2022 at 4:42
  • 1
    What are you confused about exactly? It is definitely weird, in that value is never used, but the gist is: call expect() and the return is an object with a single property: toBe, which is another function that ignores what it is passed and simply logs "success" to the console. Commented Jun 8, 2022 at 4:42

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

a more accurate es5 representation would be return console.log(success). why did you add an explicit return undefined when the es6 isn't doing that?
My bad, got mixed up @Mulan (although it is functionally identical, only syntactically different).
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')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.