Skip to main content

Objects in JavaScript: A Beginner's Guide with Examples

Objects in JavaScript: A Beginner's Guide with Examples

Objects in JavaScript are data structures that allow you to store multiple values and related functionalities in a single entity. Objects are fundamental to object-oriented programming and are widely used in JavaScript to organize and manage complex data.

What is an object in JavaScript?

An object in JavaScript is a collection of properties, where each property is an association between a name (key) and a value. Values can be of any data type, including other objects and functions (methods). Objects allow you to group related data and behaviors, facilitating the organization and manipulation of information.

Creating Objects

You can create an object using curly braces.{}and defining properties and methods within them. Here's a basic example:

let persona = {
nombre: "Juan",
edad: 30,
saludar: function () {
console.log("Hola, mi nombre es " + this.nombre);
},
};

In this example, we have created an object calledpersonawith two properties (nombre and edad) and a method (saludar).

Object Properties: Definition and Use

Object properties are key-value pairs that store data related to the object. You can define properties using dot notation (.) or bracket notation ([]).

let coche = {
marca: "Toyota",
modelo: "Corolla",
año: 2020,
};

console.log(coche.marca); // Acceso a la propiedad 'marca' usando notación de punto

console.log(coche["modelo"]); // Acceso a la propiedad 'modelo' usando notación de corchetes

Accessing Properties and Methods

You can access an object's properties and methods using dot notation (.) or bracket notation ([]).

console.log(persona.nombre); // Acceso a la propiedad 'nombre'

persona.saludar(); // Llamada al método 'saludar'

console.log(persona["edad"]); // Acceso a la propiedad 'edad' usando corchetes

Modifying Properties

You can modify an object's properties by assigning them new values.

persona.edad = 31; // Modificación de la propiedad 'edad'

console.log(persona.edad); // Resultado: 31

Adding New Properties and Methods

You can add new properties and methods to an object at any time.

persona.apellido = "Pérez"; // Añadir una nueva propiedad 'apellido'

persona.despedir = function () {
console.log("Adiós, " + this.nombre);
}; // Añadir un nuevo método 'despedir'

persona.despedir(); // Llamada al nuevo método 'despedir'

Removing Properties

You can remove properties from an object using the keyworddelete

delete persona.apellido; // Eliminar la propiedad 'apellido'

console.log(persona.apellido); // Resultado: undefined

Methods in Objects: Functions as Properties

Methods are functions associated with an object and used to define behaviors related to that object. You can define methods within an object as follows:

let calculadora = {
sumar: function (a, b) {
return a + b;
},
restar: function (a, b) {
return a - b;
},
};

console.log(calculadora.sumar(5, 3)); // Resultado: 8

console.log(calculadora.restar(5, 3)); // Resultado: 2

##thisIn JavaScript: how it works inside an object

The value ofthisWithin an object's method, the reference is to the object itself. This allows methods to access the object's properties and other methods.

let persona = {
nombre: "Ana",
edad: 25,
presentarse: function () {
console.log(
"Hola, soy " + this.nombre + " y tengo " + this.edad + " años.",
);
},
};

persona.presentarse(); // Resultado: Hola, soy Ana y tengo 25 años.

Traversing an object withfor...in and Object.keys

You can iterate through an object's properties using a loop.for...inor the methodObject.keys()

let libro = {
titulo: "1984",
autor: "George Orwell",
año: 1949,
};

// Usando for...in

for (let clave in libro) {
console.log(clave + ": " + libro[clave]);
}

// Usando Object.keys()

let claves = Object.keys(libro);

claves.forEach(function (clave) {
console.log(clave + ": " + libro[clave]);
});

Nested Objects: Working with Complex Structures

Objects can contain other objects as properties, allowing for the creation of more complex data structures.

let estudiante = {
nombre: "Carlos",
edad: 22,
direccion: {
calle: "Calle Falsa 123",
ciudad: "Springfield",
pais: "USA",
},
};

console.log(estudiante.direccion.calle); // Acceso a la propiedad 'calle' del objeto anidado 'direccion'

Comparing Objects: Equality and References

In JavaScript, objects are compared by reference, not by value. This means that two objects are equal only if they point to the same memory location.

let obj1 = { clave: "valor" };

let obj2 = obj1; // obj2 apunta a la misma referencia que obj1

let obj3 = { clave: "valor" }; // obj3 es un objeto diferente con el mismo contenido

console.log(obj1 === obj2); // Resultado: true (misma referencia)

console.log(obj1 === obj3); // Resultado: false (diferentes referencias)

Copying and cloning objects:Object.assignand spread operator

You can copy and clone objects usingObject.assign()or the spread operator.

let original = { a: 1, b: 2 };

// Usando Object.assign()

let copia1 = Object.assign({}, original);

// Usando spread operator

let copia2 = { ...original };

console.log(copia1); // Resultado: { a: 1, b: 2 }

console.log(copia2); // Resultado: { a: 1, b: 2 }

Converting Objects to Arrays and Vice Versa

You can convert an object to an array usingObject.entries(),Object.keys() either Object.values()To convert an array into an object, you can use the methodreduce()

let objeto = { a: 1, b: 2, c: 3 };

// Convertir objeto en array de pares clave-valor

let entries = Object.entries(objeto);
console.log(entries);
// Resultado: [['a', 1], ['b', 2], ['c', 3]]

// Convertir objeto en array de claves

let keys = Object.keys(objeto);
console.log(keys);
// Resultado: ['a', 'b', 'c']

// Convertir objeto en array de valores

let values = Object.values(objeto);
console.log(values);
// Resultado: [1, 2, 3]

// Convertir array de pares clave-valor en objeto

let arrayDePares = [
["x", 10],
["y", 20],
["z", 30],
];
let nuevoObjeto = Object.fromEntries(arrayDePares);
console.log(nuevoObjeto);
// Resultado: { x: 10, y: 20, z: 30 }

// Convertir array en objeto usando reduce()

let array = ["manzana", "pera", "naranja"];
let objetoDesdeArray = array.reduce((acc, valor, indice) => {
acc[indice] = valor;
return acc;
}, {});
console.log(objetoDesdeArray);
// Resultado: { 0: 'manzana', 1: 'pera', 2: 'naranja' }

Built-in Objects in JavaScript (Math and Date)

JavaScript provides several built-in objects that offer useful functionality. Some of the most common include:

-MathIt provides properties and methods for performing mathematical operations.

console.log(Math.PI); // Resultado: 3.141592653589793

console.log(Math.sqrt(16)); // Resultado: 4

-DateIt allows you to work with dates and times.

let fechaActual = new Date();

console.log(fechaActual); // Resultado: Fecha y hora actual

console.log(fechaActual.getFullYear()); // Resultado: Año actual

Best Practices When Working with Objects in JavaScript

  • Use descriptive names for properties and methods.

  • Avoid modifying global objects to prevent conflicts.

  • Useconstto declare objects that should not be reassigned.

  • Consider usingObject.freeze()To make an object immutable if you don't want its properties to be modified.

Resources
Exercises

💻Try these basic exercises on Objects in JavaScript:

Creating a Person Object with JavaScript

Function that Returns an Object