JavaScript - Object
Lachelle Zhang
Posted on May 10, 2022
Object
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: TheObject
constructor creates an object wrapper for the given value -new Object(value)
- If the value is
null
orundefined
, it will create and return an empty object.
- If the value is
let obj1 = new Object(null);
console.log(obj1); // {}
let obj2 = new Object(undefined);
console.log(obj2); // {}
// let obj = new Object() will do the same
- 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]
- If the value is an object already, it will return the value.
let obj6 = new Object({ age: 2 });
console.log(obj6); // { age: 2 }
-
Object.create()
TheObject.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"
- The literal notation
const object = { a: 1, b: 2, c: 3 };
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
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
💖 💪 🙅 🚩
Lachelle Zhang
Posted on May 10, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.