0

I'm learning JavaScript and I was looking for a while about this and I have not got any answer about this. My question is if there is any rule to define a JSON key in JavaScript.

For example, in python there is a rule defining dict and is All the keys must be of an immutable data type such as strings, numbers, or tuples.

var json = {};
json[""] = "White space";
json[" "] = "Two white space";


var emptyJSON = {};
var emptyArray = [];
function a (){}
 
json[a] = "Function";
json[emptyJSON] = "Json";
json[emptyArray]= "Array";
//I don't know why this property whit an empty array does not appear when I console the json

console.log("Print the entire object =>", json);

//But it appears when I console the specific property  
console.log("Print empty array property =>", json[emptyArray]);
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
michaelitoh
  • 2,317
  • 14
  • 26
  • 2
    Please read "[What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation)" as there is no JSON at all in your question. – str Aug 24 '18 at 14:00
  • Properties of JavaScript objects are named by strings. Any string can be a property name. – Pointy Aug 24 '18 at 14:00
  • Thank you Luis Saul @str lol – michaelitoh Aug 24 '18 at 14:17

1 Answers1

2

Object keys are strings. Anything that is not a string is converted to a string.

 var obj = {};

 obj[1] = 1;
 console.log(obj["1"]);

 obj[{}] = 2;
 console.log(obj["[Object object]"]);

 obj[[1, 2]] = 3;
 console.log(obj["1,2"]);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • After read your answer i was trying with some other thinks like adding `null` or a `function` as key and i test what you said. Thank you! – michaelitoh Aug 24 '18 at 14:07