(()=>()) and (()=>{}) are different because:
-
()=>()— parentheses mean an expression with an implicit return -
()=>{}— curly braces mean a function body, so you must usereturnyourself
Let’s break it down.
1️⃣ ()=>() — implicit return (expression)
Whatever is inside the parentheses is automatically returned.
const add = (a, b) => (a + b);
console.log(add(2, 3)); // 5
No return keyword needed.
This is often used when returning simple values.
2️⃣ ()=>{} — block body (no implicit return)
Curly braces mean it's a normal function body.
So this:
const add = (a, b) => { a + b };
console.log(add(2, 3)); // undefined
returns undefined, because there is no return statement.
To return, you must write:
const add = (a, b) => {
return a + b;
};
⚠️ Special case: returning an object
Because {} means “function body”, if you try:
const getUser = () => { name: "Ayush" };
This is treated as a block, not an object → returns undefined.
To return an object, you wrap it in parentheses:
const getUser = () => ({ name: "Ayush" });
📌 Summary
| Syntax | Meaning | Return behavior |
|---|---|---|
()=>() | expression | implicit return |
()=>{} | function block | must use return |
()=>({}) | object in parentheses | implicit return object |
If you want, I can give exercises or more examples — just tell me 👍
Good — this is a great place where many learners get stuck 🙂
Your code:
const getUser = () => {
return name: "Ayush"
};
console.log(getUser())
❌ Why it’s wrong
Two problems:
1️⃣ After return, you cannot use key: value directly.
JavaScript thinks you’re writing a label, not an object.
2️⃣ When returning an object from an arrow function body, the syntax should be:
return { name: "Ayush" }
✅ Correct version
const getUser = () => {
return { name: "Ayush" };
};
console.log(getUser());
Output:
{ name: 'Ayush' }
👍 Shorter version (implicit return)
Because it’s just one expression, we can skip return and braces:
const getUser = () => ({ name: "Ayush" });
console.log(getUser());
Notice the parentheses around the object — they tell JavaScript:
“this is an object, not a function block”.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment