Problem in transferring an array to an object

After running the following code, the result doesn’t seem right.

function checkCashRegister(cid) {
    var register = {};
    cid.forEach(([unit,money])=>{register[unit]=money});
    console.log(register);
}
checkCashRegister( [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]);

Result: Why the last property has quotes while others don’t?

{ PENNY: 1.01,
  NICKEL: 2.05,
  DIME: 3.1,
  QUARTER: 4.25,
  ONE: 90,
  FIVE: 55,
  TEN: 20,
  TWENTY: 60,
  'ONE HUNDRED': 100 }

Possibly, because it’s more than one word … guessing here … Seems to depend on the environment though.
Chrome: no quotes:
image

Firefox: quotes:
image

→ JavaScript objects do not contain single or double quote marks around the keys when no spacing is used in the key name. So, if there’s spacing in the key name, quotes are used. An Example is given below:

var person= {first name: “Depp”, address: “earth”}; **//invalid** // **To prevent this error:**
var person= {“first name”: “Depp”, "address": “earth”};

Based on your guess, I did another small test. Screen Shot 2020-06-18 at 9.32.28 pm
Even I type quotes for c property, it doesn’t show quotes later. So my guess is that the browser adds quotes to variables with spaces for better Readability. And a good practice is to use camelCase!

Thank you for replying to me!

1 Like

You’re right. Anyway, it’s not a good idea to name variables with spaces.

you can’t name variables with spaces. You can use spaces inside object properties names.