ES6 - Objects
ES6 - Objects
Section titled “ES6 - Objects”In JavaScript, objects are fundamental data structures that store collections of key-value pairs. Keys are typically strings (or Symbols in ES6+), and values can be any data type, including other objects or functions (methods). ES6 introduced several enhancements to make working with objects more concise and powerful.
Object Literals
Section titled “Object Literals”Object literals are the most common way to create objects, using curly braces {}.
ES6 Enhancements for Object Literals:
Section titled “ES6 Enhancements for Object Literals:”- Shorthand Property Names: If a variable name is the same as the intended property key, you can omit the colon and value.
const name = "Alice";const age = 30;
// ES5 way// const personES5 = { name: name, age: age };
// ES6 shorthandconst person = { name, age };console.log(person); // { name: "Alice", age: 30 }- Shorthand Method Names: You can define methods more concisely.
// ES5 way// const calculatorES5 = {// add: function(a, b) { return a + b; }// };
// ES6 shorthandconst calculator = { add(a, b) { return a + b; }, subtract(a, b) { // Also an example of a shorthand method return a - b; }};console.log(calculator.add(5, 3)); // 8- Computed Property Names: Allows you to use an expression for a property key within the object literal.
let propPrefix = "user";const dynamicObject = { [propPrefix + "Id"]: 123, [propPrefix + "Name"]: "Bob", [`${propPrefix}Role`]: "Admin" // Using template literal};console.log(dynamicObject); // { userId: 123, userName: "Bob", userRole: "Admin" }Accessing Properties
Section titled “Accessing Properties”- Dot Notation:
object.propertyName(when the property name is a valid identifier). - Bracket Notation:
object['propertyName'](when the property name is dynamic, a string with special characters, or a variable).
console.log(person.name); // "Alice"console.log(dynamicObject['userId']); // 123let keyToAccess = "userName";console.log(dynamicObject[keyToAccess]); // "Bob"Object Constructors
Section titled “Object Constructors”While object literals are common, objects can also be created using constructor functions or ES6 classes.
1. new Object() Constructor (Less Common):
Section titled “1. new Object() Constructor (Less Common):”const car = new Object();car.make = "Ford";car.model = "Mustang";console.log(car.make); // "Ford"// This is equivalent to: const car = {};2. Custom Constructor Functions (Pre-ES6 Classes):
Section titled “2. Custom Constructor Functions (Pre-ES6 Classes):”function Vehicle(make, model) { this.make = make; this.model = model; this.displayInfo = function() { console.log(`Vehicle: ${this.make} ${this.model}`); };}const myVehicle = new Vehicle("Toyota", "Camry");myVehicle.displayInfo(); // "Vehicle: Toyota Camry"3. ES6 Classes (Preferred for complex objects):
Section titled “3. ES6 Classes (Preferred for complex objects):”// See the 'ES6 - Classes' section for more detailsclass Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a sound.`); }}const lion = new Animal("Leo");lion.speak(); // "Leo makes a sound."Static Object Methods
Section titled “Static Object Methods”The Object constructor itself provides several useful static methods:
Object.assign(target, ...sources) (ES6)
Section titled “Object.assign(target, ...sources) (ES6)”Copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. This is a shallow copy.
const target = { a: 1, b: 2 };const source1 = { b: 4, c: 5 };const source2 = { d: 6 };const merged = Object.assign(target, source1, source2);console.log(target); // { a: 1, b: 4, c: 5, d: 6 } (target is modified)console.log(merged); // { a: 1, b: 4, c: 5, d: 6 }
// Cloning an object (shallow clone)const original = { x: 10, y: 20 };const clone = Object.assign({}, original);console.log(clone); // { x: 10, y: 20 }clone.x = 100;console.log(original.x); // 10 (original is not affected for primitive properties)Object.create(proto, propertiesObject?)
Section titled “Object.create(proto, propertiesObject?)”Creates a new object with the specified prototype object and optional properties.
const animalPrototype = { greet() { console.log(`Hello, I am a ${this.type}`); }};const dog = Object.create(animalPrototype);dog.type = "Dog";dog.greet(); // "Hello, I am a Dog"Object.keys(obj) (ES5)
Section titled “Object.keys(obj) (ES5)”Returns an array of a given object’s own enumerable property names (strings).
Object.values(obj) (ES2017)
Section titled “Object.values(obj) (ES2017)”Returns an array of a given object’s own enumerable property values.
Object.entries(obj) (ES2017)
Section titled “Object.entries(obj) (ES2017)”Returns an array of a given object’s own enumerable string-keyed property [key, value] pairs.
const user = { id: 1, username: 'testuser', email: 'test@example.com' };console.log(Object.keys(user)); // ["id", "username", "email"]console.log(Object.values(user)); // [1, "testuser", "test@example.com"]console.log(Object.entries(user)); // [["id", 1], ["username", "testuser"], ["email", "test@example.com"]]Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, prototype) (ES6)
Section titled “Object.getPrototypeOf(obj) and Object.setPrototypeOf(obj, prototype) (ES6)”Standard ways to get and set the prototype of an object. Object.setPrototypeOf should be used with caution due to performance implications.
Deleting Properties
Section titled “Deleting Properties”The delete operator removes a property from an object.
const myObj = { a: 5, b: 12 };delete myObj.a;console.log(myObj); // { b: 12 }console.log('a' in myObj); // falseComparing Objects
Section titled “Comparing Objects”Objects are reference types. Two distinct objects are never equal (=== or ==) even if they have the same properties, because they refer to different memory locations. Comparison only yields true if both variables point to the exact same object instance.
const obj1 = { name: "Tom" };const obj2 = { name: "Tom" };const obj3 = obj1;
console.log(obj1 === obj2); // false (different objects in memory)console.log(obj1 === obj3); // true (obj3 refers to the same object as obj1)Object Destructuring (ES6)
Section titled “Object Destructuring (ES6)”A convenient way to extract properties from objects into distinct variables.
const employee = { firstName: 'John', lastName: 'Doe', department: 'Engineering'};
// Basic destructuringconst { firstName, department } = employee;console.log(firstName); // "John"console.log(department); // "Engineering"
// Destructuring with different variable namesconst { lastName: surname } = employee;console.log(surname); // "Doe"
// Destructuring with default valuesconst { country = "USA" } = employee;console.log(country); // "USA"
// Destructuring in function parametersfunction printEmployeeInfo({ firstName, department }) { console.log(`${firstName} works in ${department}.`);}printEmployeeInfo(employee); // "John works in Engineering."For further information on Object methods and features, refer to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object