Introduction
“Objects in Node.js and Javascript. What's really important” refers to the principles behind objects, which is really important to continue learning, improving the understanding of objects in programming and in Node.js and Javascript.
Let's start with understanding what an object is in programming.
What are objects in programming?
It has been said a lot that object-oriented programming represents the real world. The truth is that programming in general is about representing the real world in something digital. So object-oriented programming is also about digitally representing the real world, just with a little more emphasis on the use of objects. But as we have established in this post, the important thing is NOT the objects, the important thing is:
Message passing for communication between objects
In programming a object It is a digital form of group features and that some of them may be analogous to an object in real life, but that it is much more limited and should not be expected to be the same, because it is only a digital representation.
When you develop software, and you need to add functionality, modify or fix a bug, your logical thinking is based on representation of digital objects, their relationships and communications with other digital entities. You should never think that as the real object behaves in a certain way, so does its representation. It is very helpful conceptually, but in implementation they are very often different.
Let's remember what Alan Kay tells us:
I'm sorry I coined the term a long time ago. Objects for programming because it made people focus on the least important part. The big idea is "Sending messages«
Alan Kay
Also a object serves for store data useful that other objects can use. So an object serves us to:
- Create communications between digital representations of objects.
- It allows grouping functionalities related to the digital representation of the object.
- Stores data that another object can use. (It works like some data structures.)
What are objects in Node.js and JavaScript?
The objects in Node.js and Javascript, they are a collection of pairs name: value
, similar to PHP's "associative arrays." These pairs of name/value
They are called properties, a property is like a variable and can contain any type of value.
The key to the previous paragraph is that it can contain any type of value, including functions. And with this two types of objects are identified.
- Objects with functionalities and communications
- Which for the most part have methods to communicate with other objects and solve problems.
- Objects with data. Also called data structure
- Which for the most part contains data and which helps us to store and send information through messages. These objects are used by objects with functionalities and communications.
Let's remember that everything related to objects also works anywhere JavaScript is executed, node.js including.
How to create objects in Node.js and Javascript?
The simplest way to create an object is through an object literal. A literal object is one that is created with curly braces {}
, adding its properties and methods. Like the following example.
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
}
};
James.getName(); // Jaime Cervantes Velasco
We have an object with five properties, name
, last name
and mother's last name
are of type string, age
is type number
and the last property, getName()
is type functions
. Here you have more information about data types.
Although we will see the functions in detail later, for now, we can say that the functions allow us to encapsulate and execute a set of operations that we do very often. Instead of repeating the code of these operations many times, we better put these operations inside a function.
Whenever we need to execute these operations, we simply execute the function, this execution of the function is called invocation. Example of invocation is in the last line, where we use parentheses, jaime.getName();
.
How do I get the value of a property?
To obtain some property of an object, we can do it in two ways:
- Dot notation
- Using square brackets, much like accessing data in a
array
The first way, dot notation, is very simple, example:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
}
};
James.name // 'Jaime'
James.last name; // 'Cervantes'
James.mother's last name; // 'Velasco'
James.edad; // 33
James.getName // function () { return 'Jaime Cervantes Velasco'; }
The second way, using square brackets []
, example:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
}
};
jaime['name'] // 'Jaime'
jaime['last name']; // 'Cervantes'
jaime['mother's last name']; // 'Velasco'
jaime['edad']; // 33
jaime['getName'] // function () { return 'Jaime Cervantes Velasco'; }
jaime['getName']() // 'Jaime Cervantes Velasco'
Here we access the properties with square brackets using the name of the properties, which are strings
.
Highlights how we invoke the function getName
. These two statements do the same thing, invoke the function getName
:
jaime.getName(); jaime['getName']();
Property names are character strings
When we use square bracket notation, we use a string of characters to get the value. What we mentioned before about An object is a collection of pairs name: value
. He name
of all properties are strings.
Since property names are strings, we can define properties enclosed by quotes, like the following example:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
},
'nueva-propiedad-con-guion-medio': 'Mi propiedad con guión medio encerrada por comillas'
};
jaime['nueva-propiedad-con-guion-medio']; // 'Mi propiedad con guión medio encerrada por comillas'
And get them with bracket notation like this, jaime['new-property-with-middle-hyphen']
.
A property like this cannot be accessed with dot notation, so jaime.new-property-with-script.medium
. This statement will give you an error in Javascript because it is not a valid property name.
In fact in Javascript the name of valid variables or properties must:
- Start with a letter, included
$
and_
. - It cannot begin with numbers or characters used in the language for other purposes, e.g.
-, %, /, +, &
. - After the starting letter you can use numbers, other valid letters,
$
and_
.
Objects in Node.js and Javascript that contain other objects?
An object can contain any type of data, so it can contain other objects. Let's look at an example:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
},
address: {
calle: 'Melchor Ocampo',
numero: 2,
colonia: 'Las Flores',
municipio: 'Tezonapa',
estado: 'Veracruz'
}
};
Here we add an object address
to the object James
. Simply using curly braces to create object literals.
How do I add, modify and delete properties?
Once you create an object, you can add more properties, modify them, and delete them.
Add properties to objects in Node.js and Javascript
Assignment is used to add new properties that do not previously exist.
const James = {
name: 'Jaime',
};
James.last name = 'Cervantes';
James.appelidoMaterno = 'Velasco';
console.log(jaime ); // { nombre: 'Jaime', apellidoPaterno: 'Cervantes', apellidoMaterno: 'Velasco }
Update properties to objects in Node.js and Javascript
Assignment is also used to update the value of properties that already exist.
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
};
James.last name = 'Perez'
James.mother's last name = 'Moreno';
console.log(jaime ); // { nombre: 'Jaime', apellidoPaterno: 'Perez', apellidoMaterno: 'Moreno' }
Remove properties from objects in Node.js and Javascript
To delete properties, use the operator delete
. Example:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
};
delete James.last name;
// o tambien así:
delete jaime['apellidoMaterno];
console.log(jaime); // { nombre: 'Jaime' }
The properties last name
and mother's last name
, no longer exists in the object James
.
Are objects in Node.js and Javascript a reference or a value?
Objects in Node.js and JavaScript will always be a reference, that is:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
};
const Pedro = James;
Pedro.name = 'Pedro';
James.name === Pedro.name; // true;
James.name; // 'Pedro'
Pedro.name; // 'Pedro'
The constants James
and Pedro
they refer to same object in memory.
How do I cycle through the properties of an object?
There are several ways, the simplest to go through the properties of an object is the following.
We have the object James
:
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
}
};
The first thing is to obtain the name of its properties with the method Object.keys
, which generates a array
with the names of the properties.
const namesProps = object.keys(jaime);
console.log(nombresProps); // ["nombre", "apellidoPaterno", "apellidoMaterno", "edad", "getNombre"]
Now we go through the arrangement namesProps
to get the values.
namesProps.forEach(nombreProp => {
console.log(James[nombreProp]); // imprime el valor del nombre de propiedad actual
});
The result of the above code is something like the following.
'Jaime'
'Cervantes'
'Velasco'
33
functions () {
return 'Jaime Cervantes Velasco';
}
The prototype of an object?
Javascript is a multi-paradigm programming language, On its object-oriented side, it does not use classes for code reuse, rather it uses object composition. But how do you do this composition of objects?
Better object composition over class inheritance
Better object composition over class inheritance
Design Patterns: Elements of Reusable Object-Oriented Software
This principle is widely applied in Javascript and therefore applies in the same way in Node.js, in fact that is how it was built. Every object in Javascript has a link to a prototype, and can use all the properties and functions of its prototype.
This prototype link can be referenced in code, using the special property __proto__
.
In the case of literal objects, such as James
, are linked to Object.prototype
, which is the base object of all objects in Javascript.
const James = {
name: 'Jaime',
last name: 'Cervantes',
mother's last name: 'Velasco',
edad: 33,
getName: functions () {
return 'Jaime Cervantes Velasco';
}
};
James.__proto__; // { constructor: f Object(), hasOwnProperty: f hasOwnProperty, ... }
James.__proto__ === object.prototype; // true
James.toString === object.prototype.toString; // true
James.toString(); //[object Object]
If we expand the prototypes in a web browser like chrome, it is displayed like this.
Graphically, the prototype link looks like the image below.
You can also see the prototype at node.js if you link it to a debugger. But we won't see how to do that today.
What is the prototype chain?
We have created the object James
literally, but what if we create it through another object person
, making the person object its immediate prototype.
const person = {
greet: functions () {
return 'Hola';
},
eat: functions () {
return 'comiendo...';
}
};
const James = object.create(persona); // Creamos jaime en base al prototipo persona
If we now do a console.log(jaime)
:
console.log(jaime);
And we expand the result in a web browser like Chrome, the result is displayed as follows.
In the image, we can see that [[prototype]]
points to the object person
, hence James
has access to the methods eat
and greet
of the object person
.
And if we make these comparisons we see that the link to the person prototype exists.
James.__proto__; // { saludar: f (), comer: f () }
James.__proto__ === person; // true
We can invoke the methods eat
and greet
of the person object as if they were James
.
James.eat(); // 'Comiendo...'
James.greet(); // 'Hola'
Now if we expand the last [[prototype]]
What do you think the result will be?
We clearly see that the last [[prototype]]
is Object.prototype
, the base prototype of all objects in Javascript. And you can check it in code by comparing Object.prototype
with special properties __proto__
.
James.__proto__.__proto__ === object.prototype; // true
We can also use the method toString
as if it were from James
.
James.toString(); // [object Object]
This is called a prototype chain., an object can have the necessary sub prototypes to reuse its properties and methods. In this case it was like this, jaime → person → Object.prototype
.
Peculiarities with the prototype chain
Use the methods and properties of sub prototypes
The object James
you can directly use the properties and methods of your prototypes.
James.toString(); // '[object Object]' --> de Object.prototype
James.hasOwnProperty('name'); // true --> de Object.prototype
James.greet(); // 'Hola' --> de persona
James.eat(); // 'Comiendo...' --> de persona
James.name; // 'Jaime' --> de si mismo, objeto jaime
Updating properties does not affect the prototype chain
When we have a property that exists in multiple sub prototypes, javascript uses the one that is closest in the prototype chain. Suppose we want to change the behavior of the method toString
in James
so instead of using Object.prototype.toString
, to James
We add a method with the same name.
You can say that what we are doing is updating it.
James.toString = functions () {
return `${this.name} ${this.edad}`;
};
James.toString(); // 'Jaime 33'
Now the method is used toString
of James
, the prototype chain is not traversed until reaching Object.prototype.toString
as was done in the previous examples. Because there is already a method toString
directly in our object James
.
The operator delete
does not remove properties from prototypes
When we occupy the operator delete
, this never touches the prototype chain, it only eliminates the properties of the object in question.
If a property with the same name as the one we removed exists in the prototype chain, then now that property in the prototype chain will be used.
Using the previous example, of the method toString
of James
, if we eliminate it with delete
, so now the toString()
of Object.prototype
It is the one that will be used because the person object does not have that method directly.
James.toString = functions () {
return `${this.name} ${this.edad}`;
};
James.toString(); // 'Jaime 33'
delete James.toString
James.toString(); // '[[object Object]]' --> De Object.prototype
In the last line we notice that now James
use the again toString()
of Object.prototype
.
Examples of predefined objects in Node.js and Javascript
As we have already mentioned in other publications, except for primitive types, everything else in javascript are objects. In future publications we will see more detail about type objects functions
and array
How to create an object functions
?
functions printPerson(person) {
console.log(person.name);
console.log(person.edad);
}
As the function printPerson
It is an object, we can add properties to it without any problem.
printPerson.miPropiedad = 'Mi propiedad de una funcion';
console.log(imprimierPersona.miPropiedad); // 'Mi propiedad de una funcion
The functions are very useful, so versatile that with them we can generate new objects, but that topic does not belong to this publication.
How to create an object array
?
The recommended way is to simply create them using square brackets []
.
const vacio = [];
const numeros = [1, 2, 3, 4, 5, 6];
const animales = ['perro', 'gato', 'caballo'];
const conObjetos = [
{
name: 'Jaime',
edad: 33
},
functions printPerson(person) {
console.log(person);
}
];
Since an array is an object, just like a function, you can also add properties to it.
const numeros = [1, 2, 3, 4, 5, 6];
numeros.miPropiedad = 'Mi propiedad de un arreglo';
console.log(numeros.miPropiedad); // 'Mi propiedad de un arreglo
He array
is the clearest object to use as a data structure.
How to create an object date
?
const fecha = new date();
console.log(fecha); // Fri May 28 2021 10:46:27 GMT-0500 (hora de verano central)
As you can imagine, we can also add properties to the date object because it is an object
Conclusion
In Javascript and on any platform where it is executed, an example is in node.js, they have the peculiarity of always having a link to a prototype. This is how the language is designed. I already know that classes currently exist, but in reality these are functions that internally make use of prototypes, we will also explain this in another publication.
With the exception of primitive data, everything else in Javascript is objects, it is important to know how they work so as not to get stuck in this learning.
With this information you have enough to continue advancing and use items more wisely.
The topic of objects is quite extensive, there are still many things to take into account, but there is already too much information that we have to divide it into more publications. So very soon we will continue. If you have any questions, do not hesitate to write them in the comments, we will be happy to help you!
Objects in Node.js and Javascript that contain other objects?
Un objeto puede contener cualquier tipo de dato, así que puede contener otros objetos. Veamos un ejemplo:
olonia: ‘Las Flores’,
municipio: ‘Tezonapa’,
estado: ‘Veracruz’
}
};
1
const jaime = {
2
nombre: ‘Jaime’,
3
apellidoPaterno: ‘Cervantes’,
4
apellidoMaterno: ‘Velasco’,
5
edad: 33,
6
getNombre: function () {
7
return ‘Jaime Cervantes Velasco’;
8
},
9
direccion: {
10
calle: ‘Melchor Ocampo’,
11
numero: 2,
12
colonia: ‘Las Flores’,
13
municipio: ‘Tezonapa’,
14
estado: ‘Veracruz’
15
}
16
};
Aquí agregamos un objeto direccion al objeto jaime. Simplemente usando las llaves para crear objetos literales.
como podria acceder a una propiedad dentro de otra por ejemplo quiere que me devuelva el valor municipio de direccion de jaime
Excelente informaciòn gracias por compartir