Does your code run or is an error thrown? Perhaps you can share a screenshot.
As a preliminary refresher,
name = "Jake";
age = 55;
const someObject = {
name: name,
age: age
}
console.log(someObject);
// { name: 'Jake', age: 55 }
There is a shorthand notation for accomplishing the same as above.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#property_definitions
name = "Jake";
age = 55;
const someObject = {
name,
age,
}
console.log(someObject);
// { name: 'Jake', age: 55 }
With that out of the way, let’s look at your code snippets.
In your second snippet, you have an arrow function artificialII
which has two parameters name
and age
. Since curly braces have been used for the body of the arrow function, therefore we need an explicit return
if we wish to return something. In your code, an object will be returned which will have two properties. The values assigned to these properties will be provided by the arguments assigned to the parameters.
const artificialII = (name, age) => {
return {
name,
age,
}
};
console.log(artificialII("Jake", 55));
// { name: 'Jake', age: 55 }
Your first snippet will throw up a SyntaxError (unless you have made some mistake while copy pasting). That is because the curly braces after the the arrow will be interpreted as being the body of the arrow function and then name, age,
won’t make sense. However if you do something like:
const artificialI = (name, age) => ({
name,
age,
});
console.log(artificialI("Jake", 55));
// { name: 'Jake', age: 55 }
then this will work and will be equivalent to the artificialII
version.
After the arrow =>
, the interpreter looks at whether there is a curly brace or not.
If there is a curly brace immediately after the arrow, then it is interpreted as being the body of the arrow function.
If there isn’t a curly brace, then it is interpreted as being a single expression whose value after evaluation will be implicitly returned. By using parentheses, we have chosen not to use curly braces for the body of the arrow function. The curly braces inside the parentheses will be interpreted as belonging to an object (and there will be no ambiguity that the braces aren’t meant to designate the body of the arrow function). This object will then be implicitly returned by the arrow function.