1

function Car() {
  const fuel = 50
  return {
    fuel
  }
}

const car = Car();
console.log(car);

I happened to see the code above, and I thought the value of car would be 50, but strangely, car became an object. Can you tell me why car is an object? I happened to see it in the link below. Why use getters and setters in JavaScript?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Neo
  • 27
  • 4
  • 1
    `return fuel` will give you 50 and `return { fuel }` will give you `{ fuel: 50 }`. *why you're getting an object?* because you are returning an object. – Layhout Nov 25 '22 at 09:20
  • 1
    console it like this and see the result console.log(car.fuel) – Leenard Nov 25 '22 at 09:23

1 Answers1

0

Notice the curly braces {} when it returns. These mean that it is an object that contains fuel. If you returned just fuel(without {} ) then it would be 50 as you expected.

Marios
  • 339
  • 1
  • 14