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)
}
}
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.
return console.log(success). why did you add an explicit return undefined when the es6 isn't doing that?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')
{}is after thereturn)?valueis never used, but the gist is: callexpect()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.