A tu propio ritmo

Explora nuestra extensa colección de cursos diseñados para ayudarte a dominar varios temas y habilidades. Ya seas un principiante o un aprendiz avanzado, aquí hay algo para todos.

Bootcamp

Aprende en vivo

Únete a nosotros en nuestros talleres gratuitos, webinars y otros eventos para aprender más sobre nuestros programas y comenzar tu camino para convertirte en desarrollador.

Próximos eventos en vivo

Catálogo de contenidos

Para los geeks autodidactas, este es nuestro extenso catálogo de contenido con todos los materiales y tutoriales que hemos desarrollado hasta el día de hoy.

Tiene sentido comenzar a aprender leyendo y viendo videos sobre los fundamentos y cómo funcionan las cosas.

Full-Stack Software Developer - 16w

Data Science and Machine Learning - 16 wks

Buscar en lecciones


IngresarEmpezar

Weekly Coding Challenge

Todas las semanas escogemos un proyecto de la vida real para que construyas tu portafolio y te prepares para conseguir un trabajo. Todos nuestros proyectos están construidos con ChatGPT como co-pilot!

Únete al reto

Podcast: Code Sets You Free

Un podcast de cultura tecnológica donde aprenderás a luchar contra los enemigos que te bloquean en tu camino para convertirte en un profesional exitoso en tecnología.

Escuchar el podcast
← Volver a Cómo hacerlo
Editar en Github

How to Create an object in Javascript

Escrito por:

Creating an object in JavaScript may be achieved by different means, this example allows us to create the object and establish its properties:

1function Geek(tech, years) { 2 this.tech = tech; 3 this.years = years; 4} 5 6const geek1 = new Geek("javascript", 3) 7const geek2 = new Geek("node", 2) 8console.log(geek1) 9console.log(geek2) 10 11/* 12Output: Geek { tech: 'javascript', years: 3 } 13Output: Geek { tech: 'node', years: 2 } 14*/

Object with literal syntax:

This is the simpliest way to create an object, the downside is that you´ll need to set the properties for each of the objects you want to create manually. The example is as follows:

1//Obj declaration with literal sintax 2const obj = { 3 tech: "javascript", 4 years: 2 5} 6 7console.log(obj) 8//Output: { tech: 'javascript', years: 2 }

Object with new keyword

There are different ways to create objects in javascript using the new keyword.

The built-in Object constructor

To create an object with the built-in constructor use the following sintax:

1 2const geek = new Object(); 3 4console.log(geek) 5// Output: {}

Ok, we created an empty object, now let´s give it some properties:

1geek.tech = "javascript" 2geek.years = 3

Now, if we check the obj, we see the properties we just added

1console.log(geek) 2// Output: { tech: 'javascript', years: 2 }

User defined constructor function

Using a user defined constructor function we take care of a problem that happens when using the new Object() and is that, the later, is longer to code and not quite dynamic as the one we´ll discuss now.

1function Geek(tech, years) { 2 this.tech = tech; 3 this.years = years; 4} 5 6/* 7Output: Geek { tech: 'javascript', years: 3 } 8*/

Every time we´ll execute the Geek() function, we´ll pass the value of the properties Geek("javascript", 3) and the function will create for us the object with the given properties (remember to send the correct type of values the object receives to prevent errors).

Object.create()

Object.create() receives an obj as prototype (or blueplrint) and creates a new object from it

Syntax:

1Object.create(proto, propertiesObject)

Parameters:

  • proto: the object used as prototype
  • propertiesObject (optional): If specified and not undefined, the properties you want to add to the new object

An example will be most welcome to make all that more understandable, here it is:

First we create our prototype obj (parent object, or anyway you feel more comfortable to name it).

1const geekForce = { company: "4 Geeks Academy"}

We use the Object.create() method, and as first argument we pass the geekForce object, then we follow the syntax:

1{ 2 propertyName: {value: "property-value"}, 3 otherPropertyName: {value: "other-property-value"} 4}

A full example would look like this:

Now that we have our prototype object, we can use it with Object.create() like this:

1const geek1 = Object.create(geekForce, { 2 name: {value: "Javier Seiglie"}, 3 tech: {value: "javascript"}, 4 years: {value: 3} 5})

Now, let´s see the properties we just added

1console.log(geek1.tech) 2// Output: javascript 3console.log(geek1.years) 4// Output: 3 5console.log(geek1.name) 6// Output: Javier Seiglie

Object.assign()

If we want to create an object that needs other object properties as its own, then we use the Object.assign() method.

This method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

Let´s see an example, given two objects:

1const companyObj = {company: "4 Geeks Academy"} 2const tech = { geekTech: "javascript"}

Now, we want to create a new object that cointains both of them.

1const geekForce = Object.assign({}, companyObj, tech); 2console.log(geekForce) 3//Output: { company: '4 Geeks Academy', geekTech: 'javascript' }

We explored different ways on how to create objects in javascript, from the most straightforward one to a dynamic way, and using other object as a prototype creating an object from other objects.

Hope you enjoyed the reading and keep on the geek side.