No, there is no built-in property that tells you how many properties the object has (which is what you're looking for). The closest I can think of for plain objects (keep reading for an alternative) are things that return arrays of property keys (which you can then get length
from):
Object.keys
- Returns an array of the object's own, enumerable, string-keyed properties.
Object.getOwnPropertyNames
- Like Object.keys
, but includes non-enumerable properties as well.
Object.getOwnPropertySymbols
- Like Object.getOwnPropertyNames
, but for Symbol-keyed properties instead of string-keyed properties.
Reflect.ownKeys
- Returns an array of an object's own properties (whether or not they're enumerable, and whether they're keyed by strings or Symbols).
For instance, you could use Reflect.ownKeys
like this:
var quesArr = new Array(); // Keep reading, don't do this
quesArr["q101"] = "Your name?";
quesArr["q102"] = "Your age?";
quesArr["q103"] = "Your school?";
console.log(Reflect.ownKeys(quesArr).length); // 4 -- includes the built-in
// `length` property!
Notice that showed 4, not 3, because of the built-in length
property of arrays. Since you don't seem to be using the Array
features of the object, don't make it an array. You could make it a plain object:
const questions = {};
questions["q101"] = "Your name?";
questions["q102"] = "Your age?";
questions["q103"] = "Your school?";
// Or just:
// const questions = {
// q101: "Your name?",
// q102: "Your age?",
// q103: "Your school?",
// };
console.log(Reflect.ownKeys(questions).length); // 3
But since you want to know how many things are in it, you might consider using a Map
, because unlike objects, Map
instances do have a property telling you how many entries they have in them: size
.
const questions = new Map();
questions.set("q101", "Your name?");
questions.set("q102", "Your age?");
questions.set("q103", "Your school?");
// Or you can pre-fill the `Map` by passing an array of `[name, value]` arrays:
// const questions = new Map([
// ["q101", "Your name?"],
// ["q102", "Your age?"],
// ["q103", "Your school?"],
// ]);
console.log(questions.size); // 3