ES6: Write Concise Object Literal Declarations Using Simple Fields question

There is this code:

const getMousePosition = (x, y) => ({
  x: x,
  y: y
});

The second x and the second y in the object come from the function arguments?

1 Like

So there are a few things happening here. First, it’s using the ‘fat arrow function’ or ‘lambda function’. Let’s expand that out, so it becomes a little less confusing:

const getMousePosition = function(x, y){
  return {
    x: x,
    y: y
  };
};

So that function takes two parameters, an x and a y, and creates an object. Within the object to be returned, we see two x and two y. Why? The first is the object’s property name, the second is the value we’re setting it to (in our case, the parameters we were passed in. Let’s make it a shade less confusing:

const getMousePosition = function(xPos, yPos){
  return {
    x: xPos,
    y: yPos
  }
}

let mouse = getMousePosition(event.screenX, event.screenY);
console.log(mouse.x);

Thanks for the reply.

Thanks for the question, it was a good one. :wink: