JavaScript Objects 101

Ido Green - Jan 6 '23 - - Dev Community

The Object type represents one of JavaScript’s data types. It’s important stuff as we will use them—a lot.

It is used to store various keyed collections and more complex entities. Objects can be created using the Object() constructor or the object initializer / literal syntax. Did you know that all modern JavaScript utilities for working with objects are static?

Here is an example of a JavaScript object that contains two names and one key:

let obj = {
  name1: "John",
  name2: "Jane",
  key: "value"
}
Enter fullscreen mode Exit fullscreen mode

This object has three properties: name1, name2, and key. The values of name1 and name2 are strings, and the value of key is also a string. You can access the values of these properties using the dot notation, like this:

console.log(obj.name1); // Output: "John"
console.log(obj.name2); // Output: "Jane"
console.log(obj.key); // Output: "value"
Enter fullscreen mode Exit fullscreen mode

You can also use the square bracket notation to access the properties of the object, like this:

console.log(obj["name1"]); // Output: "John"
console.log(obj["name2"]); // Output: "Jane"
console.log(obj["key"]); // Output: "value"

Enter fullscreen mode Exit fullscreen mode

You can use the for…in loop to iterate over the properties of the object, like this:

for (let prop in obj) {
  console.log(prop + ": " + obj[prop]);
}
Enter fullscreen mode Exit fullscreen mode

Output:

name1: John

name2: Jane

key: value

Here is a more ‘full’ example to the properties inside an object:

tmpObj= {};
tmpObj= {a: 'foo', b: 42, c: {}};

const a = 'foo';
const b = 42;
const c = {};
tmpObj= { a: a, b: b, c: c };

tmpObj= {
  get property() {},
  set property(value) {}
};

tmpObj= { proto: prototype };

// Shorthand property names
tmpObj= { a, b, c };

// Shorthand method names
tmpObj= {
  property(parameters) {},
};

// Computed property names
const prop = 'foo';
tmpObj= {


};
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .