DEV Community

Cover image for JavaScript - Object
Lachelle Zhang
Lachelle Zhang

Posted on • Updated on

JavaScript - Object

Object

Object - MDN

An object is a collection of properties(key/value pairs). When the value is a function, the property becomes a method.
Objects can be created using the Object() constructor, Object.create() or the literal notation.

  • Object() constructor: The Object constructor creates an object wrapper for the given value - new Object(value)
    • If the value is null or undefined, it will create and return an empty object.
  let obj1 = new Object(null);
  console.log(obj1); // {}
  let obj2 = new Object(undefined);
  console.log(obj2); // {}
  // let obj = new Object() will do the same
Enter fullscreen mode Exit fullscreen mode
  • Otherwise, it will return an object of a Type that corresponds to the given value.
  let obj3 = new Object(2);
  console.log(obj3); // [Number: 2]
  let obj4 = new Object("hi");
  console.log(obj4); // [String: 'hi']
  let obj5 = new Object(true);
  console.log(obj5); // [Boolean: true]
Enter fullscreen mode Exit fullscreen mode
  • If the value is an object already, it will return the value.
  let obj6 = new Object({ age: 2 });
  console.log(obj6); // { age: 2 }
Enter fullscreen mode Exit fullscreen mode
  • Object.create() The Object.create() method creates a new object, using an existing object as the prototype of the newly created object.
  const person = {
    isHuman: false,
    printIntroduction: function () {
      console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
    },
  };

  const me = Object.create(person);

  me.name = "Matthew"; // "name" is a property set on "me", but not on "person"
  me.isHuman = true; // inherited properties can be overwritten

  me.printIntroduction();
  // expected output: "My name is Matthew. Am I human? true"
Enter fullscreen mode Exit fullscreen mode
  • The literal notation
const object = { a: 1, b: 2, c: 3 };
Enter fullscreen mode Exit fullscreen mode

We can access the values in an object by using object['key'] or object.key.

const object = { a: 1, b: 2, c: 3 };
console.log(object["a"]); // 1
console.log(object.a); // 1
Enter fullscreen mode Exit fullscreen mode

Deleting a property from an object - delete operator
The JavaScript delete operator removes a property from an object.

const Employee = {
  firstname: "John",
  lastname: "Doe",
};

console.log(Employee.firstname);
// expected output: "John"

delete Employee.firstname;

console.log(Employee.firstname);
// expected output: undefined
Enter fullscreen mode Exit fullscreen mode

Top comments (0)