Objects in JavaScript

Objects in JavaScript

Objects in JavaScript: The Cornerstone of the Language Objects are a fundamental part of JavaScript. They are flexible and powerful data structures that allow storing collections of data and related functionalities. In this article, we will explore JavaScript objects in depth, from the basics to more advanced features.

1. Object Creation

There are several ways to create objects in JavaScript:

Object Literal Notation

let persona = {
  nombre: "Ana",
  edad: 30,
  saludar: function() {
    console.log("Hola, soy " + this.nombre);
  }
};`

Object Constructor

let persona = new Object();
persona.nombre = 'Ana';
persona.edad = 30;
persona.saludar = function () {
  console.log('Hola, soy ' + this.nombre);
};

Constructor Function

function Persona(nombre, edad) {
  this.nombre = nombre;
  this.edad = edad;
  this.saludar = function () {
    console.log('Hola, soy ' + this.nombre);
  };
}

let persona = new Persona('Ana', 30);

2. Properties and Methods

Properties are the data stored in an object, while methods are functions associated with an object.

let coche = {
  marca: 'Toyota',
  modelo: 'Corolla',
  año: 2020,
  arrancar: function () {
    console.log('El coche está arrancando');
  },
};

console.log(coche.marca); // "Toyota"
coche.arrancar(); // "El coche está arrancando"

3. Access to Properties

There are two main ways to access an object’s properties:

Dot Notation

console.log(coche.modelo); // "Corolla"

Bracket Notation

console.log(coche['modelo']); // "Corolla"

4. Dynamic Properties

You can add, modify, or delete properties of an object at any time:

coche.color = 'rojo'; // Agregar
coche.año = 2021; // Modificar
delete coche.modelo; // Eliminar

5. Object Methods

JavaScript provides several useful methods for working with objects:

Object.keys() Returns an array with the enumerable keys of an object.

console.log(Object.keys(coche)); // ["marca", "año", "arrancar", "color"]
Object.values();

Returns an array with the values of the enumerable properties of an object.

console.log(Object.values(coche)); // ["Toyota", 2021, [Function: arrancar], "rojo"]
Object.entries();

Returns an array of arrays, where each subarray is a [key, value] pair from the object.

console.log(Object.entries(coche));
// [["marca", "Toyota"], ["año", 2021], ["arrancar", [Function: arrancar]], ["color", "rojo"]]

6. Prototypes and Inheritance

JavaScript uses prototypes to implement inheritance. Each object has an internal link to another object called its prototype. This prototype object in turn has its own prototype, and so on, forming what is known as the prototype chain.

Creation of objects with prototypes

let animalProto = {
  comer: function () {
    console.log('Ñom ñom');
  },
};

let perro = Object.create(animalProto);
perro.ladrar = function () {
  console.log('Guau guau');
};

perro.comer(); // "Ñom ñom"
perro.ladrar(); // "Guau guau"

Inheritance with constructor functions

function Animal(nombre) {
  this.nombre = nombre;
}

Animal.prototype.comer = function () {
  console.log(this.nombre + ' está comiendo.');
};

function Perro(nombre) {
  Animal.call(this, nombre);
}

Perro.prototype = Object.create(Animal.prototype);
Perro.prototype.constructor = Perro;

Perro.prototype.ladrar = function () {
  console.log(this.nombre + ' está ladrando.');
};

let miPerro = new Perro('Fido');
miPerro.comer(); // "Fido está comiendo."
miPerro.ladrar(); // "Fido está ladrando."

7. Getters and Setters

Getters and setters allow defining how a property of an object is accessed and modified.

let persona = {
  nombre: 'Juan',
  apellido: 'Pérez',
  get nombreCompleto() {
    return this.nombre + ' ' + this.apellido;
  },
  set nombreCompleto(valor) {
    [this.nombre, this.apellido] = valor.split(' ');
  },
};

console.log(persona.nombreCompleto); // "Juan Pérez"
persona.nombreCompleto = 'María López';
console.log(persona.nombre); // "María"
console.log(persona.apellido); // "López"

8. Object.defineProperty()

This method allows defining new properties or modifying existing ones with finer control over their attributes.

let obj = {};

Object.defineProperty(obj, 'propiedad', {
  value: 42,
  writable: false,
  enumerable: true,
  configurable: true,
});

console.log(obj.propiedad); // 42
obj.propiedad = 77; // No tiene efecto debido a writable: false
console.log(obj.propiedad); // 42

9. Methods of Object.prototype

These methods are available to all objects in JavaScript:

hasOwnProperty() Checks if a property is the object’s own and not inherited.

console.log(persona.hasOwnProperty('nombre')); // true
console.log(persona.hasOwnProperty('toString')); // false

toString() Returns a string representation of the object.

console.log(persona.toString()); // "[object Object]"

10. Object Destructuring

Destructuring allows extracting values from objects and assigning them to variables more concisely.

let { nombre, edad } = persona;
console.log(nombre); // "María"
console.log(edad); // 30

Conclusion

Objects are fundamental in JavaScript, offering versatility and power to structure code and data. Mastering them is essential for developing efficient and scalable applications. With their ability to encapsulate properties and methods, implement inheritance, and create complex abstractions, objects are the foundation of modern programming in JavaScript. A deep understanding of them opens doors to advanced design patterns and significantly improves code quality.