Data types in Javascript are a little different compared to other programming languages like C or JAVA.
JavaScript is a weakly typed language, this means that it is not necessary to define the data type. But it is not that it does not have types, since the data type is defined at run time by Javascript.
This behavior and specification of data types applies to any place where javascript is executed, whether in the browser, in node.js, mongodb, or any tool that uses Javascript.
Now if we analyze the concept of types a little, when you make a sum between numbers in the real world you don't care what type it is, you only care that they can be added, regardless of whether it is an integer or decimal. These subtypes of numbers are still part of the set of real numbers, and are used in real life.
Javascript allows us to apply this thinking and with that we save many type comparisons. There will be times when we have no choice but to convert or compare them, but the less we do it, the simpler our code will be, and therefore easier to understand and faster to execute.
It is said that Javascript has a dynamic data type system, this is because the variables that are created can receive any other type of data at any time, and change type depending on the value they store. What we are really interested in is the value and what we can do with that value, not so much the type.
Later we will see some conversions and comparisons that can confuse and complicate the code, the recommendation is to reduce their use as much as possible. Although we will not see each type in great detail, we will see more important things necessary to use data types in Javascript.
It is useful to know how to define variables and constants, if you do not know how to create a variable or a constant, you can review this information before continuing.
Primitive data types
It is one that is not an object
It has no methods.
They are immutable
We have seven guysprimitive data in Javascript.
number, numbers like; 1, 0, 18500, 89.95124
BigInt, added in 2020, to represent very, very large integers, 99999999999999n
String, character string like 'Hello' and "Good night".
Boolean, only accept true either false, that is, yes or no.
null, serves to indicate that something is nothing, its only value is null.
undefined, serves to indicate that something is not yet defined.
symbol, added in 2015, with EcmaScript 6
Data Types Objects
All other data types in Javascript are objects. In the section Objects there is the explanation.
number
If I had written this before 2020, I would tell you that there is only one numeric data type, unfortunately (with some exceptions) a new numeric value called BigInt. In this section we will pretend that it does not exist.
number is a value 64 bit float, that is, it is a number double In other programming languages, this is basically the only numeric data type in JavaScript, there are no integers (except for BigInt), decimals, floats or doubles. Its specification is provided by IEEE-754.
The way to define and use them is very simple, you simply write the number, it does not matter if it is integer or decimal, floating point or double, as we mentioned before, all of these will be of type double for javascript. This is the recommended way to define them.
const edad =33;const PI =3.1416;const descuento =0.30;const pesoEnDolares =0.05;// que tristeza xD!!edad + descuento;// 33.30, no nos interesa el tipo, solo la suma
As we see in the last line, we can add integers and decimals without any problem, we are not interested in the type, we are interested in the ability to add them.
Float values are known to have a certain precision error when performing arithmetic operations, the most obvious operation being division.
0.2+0.1;// es igual a 0.30000000000000004
As we see, it does not give us an exact value of 0.3, to mitigate this you can multiply the values by 100 and then divide the result by 100.
(0.2*100+0.1*100)/100;// es igual a 0.3
NaN
There is a special number called NaN. This value is the error of an operation with numbers.
25*undefined;// es igual a NaN25*{};// es igual a NaN
Any operation you have NaN as one of its operands, will result in NaN.
25*NaN;// es igua a NaN25+NaN;// es igual a NaN
NaN it is not even equal to NaN
NaN===NaN;// es igual a falseNaN==NaN;// es igual a false
To mitigate this strange behavior, it is recommended to use the method Number.isNaN(), there is also a global function called isNaN(), but due to the implicit functionality of Javascript in wanting to convert between types automatically, it can give us very strange results. So as a recommendation always use Number.isNaN(). This last function checks if the type is number and equal to NaN, any other value will return false.
// Usando funcion globalisNaN('James');// true --> Esto esta mal, deberia seguir regresando false// lo que realmente hace es una conversion automaticaconst result =number('James');// NaNisNaN(result);// truenumber.isNaN('343434');// falsenumber.isNaN('James');//falsenumber.isNaN(1+undefined);// true
We can see in the first example that the global function returns true when it should be false, this is due to the automatic type conversion that javascript does.
Function Number(value)
You can convert a value to a number using the function Number(value), just be careful because this function can return 0 for many values, as well as NaN.
Finally we have the functions Number.parseInt(value) and Number.parseFloat(value), if the value is not a string, then convert it to string using the method .toString() before converting to number.
This type of value is new, added to the language in 2020, it is used to represent very large integer values, especially for mathematical calculations with very large quantities.
To use this type of data, the letter is added to the number n in the end. This is the recommended way.
const enteroMuyGrante =999999999999999999999999999999999999999999999999999n;const otroEnteroMuyGrande =55555555555555555555555555555555555555555555555n;const result = enteroMuyGrande * otroEnteroMuyGrande;//
Operations can be performed between the Number type and the BigInt, but because conversion between types can cause loss of precision, it is recommended to only use values BigInt when values greater than 2 are being used53 and only perform operations with values of the same type BigInt.
Another bad news about BigInt is that you cannot use the object's methods on a BigInt value. MathematicsFor example, you cannot use Math.sqrt().
Mathematics.sqrt(99);// 9.9498743710662Mathematics.sqrt(99999999999999999n);// Uncaught TypeError: Cannot convert a BigInt value to a number
As a final recommendation, do not complicate your life, do not use BigInt unless the problem you want to solve necessarily requires very large integers.
BigInt(value) function
You can convert and create a BigInt with the function BigInt(value)
BigInt('9999999999');// 9999999999n
Boolean
Boolean is a logical data type, which is represented by only two values. true and false. Very useful for making decisions in our programs. Named after the mathematician George Boole.
Boolean type values can be defined as follows. This is the recommended way
const tieneHijos =true;const esEstudiante =false;
They are widely used in logical operations, for example:
if (tieneHijos) {// Si "si" tiene hijos, preguntar cuantos hijos tiene}else{// si "no"}if (esEstudiante) {// Si "si" es estuduante, aplicar descuento}else{// si "no"}
Boolean function(value)
Booleans also have a function Boolean(value), is suitable for creating booleans and explicitly converting a value to Boolean. More details below in the section Values that can generate Booleans.
null
This data type in Javascript is very easy, it is a data that means it is nothing compared to the other data types. In other languages null It refers to a pointer or a memory reference that is empty, but in javascript it is different, it is simply a value that means “nothing".
const nada =null;
undefined
This data type represents something that is not yet defined. It is the automatic value of variables, parameters and properties of objects that have not had a value defined.
let name;// undefinedlet edad;// undefinedname ===undefined;// trueedad ===undefined;// true
symbol
This type of data is primarily used to ensure that its value is unique and immutable. It can be used as object properties to reduce access to those properties and thus avoid unwanted modifications. When we look at the objects in more detail we will see their use in practice.
To create this type of primitive data the function is used Symbol(). It is the only way to create a symbols and it is the recommended one.
const name =symbol('Jaime');const nombreIgual =symbol('Jaime');name === nombreIgual;// false
String or string of characters
Strings allow us to save information in text form. They are a sequence of one or more 16-bit, UTF-16 characters. There is no `char` type like in other languages, if you want a character, you simply create a string with a single character. Simple right?
We have three ways to create a string.
Actually you can also create strings with the function String(value) or in constructor form new String(value), but let's not complicate our existence and only use the three below for simplicity:
With single quotes, ''. Recommended if you do not need to evaluate expressions inside.
Double quotation marks, ""
backticks, `` . Recommended if you need to evaluate expressions within.
const name ='Jaime';const last name ="Cervantes";const mother's last name =`Velasco`;
The third way to define Strings, allows us to use expressions within the character string, so it is very useful. For example:
const name ='Jaime';const last name ="Cervantes";const mother's last name =`Velasco`;const nombreCompleto =`${name}${last name}${mother's last name}`;// Jaime Cervantes Velasco
Strings are immutable, when you modify or extend a string a new one is actually generated.
Two character strings can be the same
You can check that two character strings are the same with ===.
The property length of a string is used to know the length of a string of characters, you will see over time that this is useful when working with strings of characters.
const name ='Jaime Cervantes Velasco';name.length // 23
Objects
All other data types are objects, a function is an object. A object is 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.
Some objects in Javascript:
object
function
array
date
RegExp
Mistake
Primitive Wrapping Objects
Even primitive data types String, Boolean, Number, BigInt and Symbol has its corresponding representation in Object, called enveloping objects. In fact, Javascript implicitly converts this primitive data to objects in order to occupy useful methods and properties. For example the property length of a string of characters.
How were you planning to get the length of a character string? Understanding that a character string is primitive data and has no methods
'Jaime Cervantes Velasco'.length;// 23, el pri// A groso modo, lo que sucede implictamente al querer obtener lenght:const nuevoString =newString('Jaime Cervantes Velasco');nuevoString.length;// 23(5).toFixed(2);// 5.00// Igual a groso modo pasa algo asi:const numero =newnumber(5);numero.toFixed(2);// 5.00false.toString();// 'false'// Igual a groso modo pasa algo asi:const booleano =newBoolean(false);numero.toString(2);// false// Estos dos tipos de datos primitivos no permiten el uso de new(9n).toLocaleString();// '9'symbol('Hi').toString();// 'Symbol(Hi)'
Although the BigInt and Symbol data types do not allow the use of new It does not mean that objects are not created behind, it is clear that javascript wraps them in an object because it allows us to use the methods of the example, toLocaleString and toString.
How to create an object?
To create an object you don't need to create a class, you simply create the object and start using it. The easiest way to create an object is to use the definition called literal object, where you simply open and close keys {}. This is the recommended way.
In the example we have an object person, has several properties of different types, its name is a String, his age is a number, getName and talk are of type function, functions that are members of an object are called methods.
Below are examples of objects.
Accessing properties with square brackets, ['key']
In the previous example we saw how to access the method talk(), this method is still a property and is of type functions. But there is another notation to access properties, using square brackets. Very similar to how the elements of an array are accessed.
person.edad;// regresa 33persona['edad'];// regresa 33// obtenemos la funciónn con corcheteds y la invocamos con parentesisconst frase = persona['talk']();console.log(frase);// 'Hola soy Jaime Cervantes Velasco, tengo 29 años.'
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
How to create an object date?
const fecha =newdate();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
For now, I hope this gives you an idea of the importance of objects in Javascript and why it deserves a more extensive explanation in a future publication.
Values that can generate a boolean false
There are true values and false values, which when applied to a condition behave like Booleans. This is because Javascript does an implicit type conversion, which can surprise us if we are not careful, so here I leave you the list of values that can return a Boolean false.
false
null
undefined
0
0n
NaN
"", "", " (empty character string)
All other values, including objects, in a condition or passed to the function Boolean(value) the Boolean returns true. A string with a space " ", came back true, and a string with value "false" also returns true.
Boolean function(value)
There is a global function to create Boolean values, Boolean(value). Where yes worth It's a real one, come back true, otherwise it returns false.
Boolean(false);// falseBoolean(null);// falseBoolean(undefined);// falseBoolean(0);// falseBoolean(0n);// falseBoolean(NaN);// falseBoolean('');// false// Todos los demas valores van a regresar trueBoolean('');// trueBoolean('false');// trueBoolean('jaime cervantes');// trueBoolean({});// trueBoolean([]);// true;
Under logical conditions
Logical conditions in javascript check without a return expression true either false, they execute an implicit conversion.
This operator allows us to identify the type of data we are working with, useful in case we do not know where the information comes from, or we want to process the data based on its type. The operator returns the lowercase name of the data type.
typeof5;// 'numbertypeofNaN;// 'number'typeof99999999999999999999999999999999999999999999999n;// 'bigint'typeoftrue;// 'boolean'typeofnull;// 'object', esto es un error que existe desde la primera versión de JStypeofundefined;// 'undefined'typeofsymbol('simbolo');// 'symbol'typeof'cadena de caracteres';// 'string'typeof{};// 'object'typeof [];// 'objecttypeofnewdate();// 'object'typeofnewString('Jaime');// Objecttypeoffunctions(){}// 'function'typeofclassA{}// 'function'
There is a known bug in javascript, when the typeof operator is executed on null, this one comes back'object'. This bug has existed since the first version of Javascript, Bad things happen when you write code on the run.
If all other non-primitive values are objects, when we use the operator typeof about them, what type of data will you tell us what they are? Exactly, 'object'. Just like in the example above when we pass an object literal, an empty array, a date type object and when we use the surrounding objects of primitives like new String('Jaime').
Existe una excepción en typeof, cuando el valor es una función o una clase, regresara functions. Recuerda, una función en javascript, también es un objeto.
Check types with the method Object.prototype.toString
As we saw, it is somewhat confusing to use the operator typeof, I prefer to use a safer method, it is somewhat strange, but since everything in Javascript is an object and the base object from which all data types in javascript start is object, with the exception of the primitive data (although these in turn have their object version), then we can do something like the following.
The special property prototype is very important in Javascript, if you have read more than one of my publications, you will have noticed that I have mentioned that Javascript is a multiparadigm and object-oriented programming language based on prototypes, in another publication we will explain in detail the functionality of prototypes in Javascript .
Conclusion
Everything in Javascript is an object, with the exception of primitive types, but as we already saw, when wanting to use them as objects by invoking some method, that is where javascript wraps them (in practice everything is an object).
Any programming language has good things that we can take advantage of, but it can also have strange and confusing things (compared to most modern programming languages), such as the operator typeof and the method Object.prototype.toString, the value NaN, the values that can generate a boolean false, and many other things we didn't see for simplicity's sake. It is up to the programmer to take the best parts and eliminate or mitigate those that do not help us communicate better with our work team, always with a focus on simplifying things.
In the case of creating some type of data in Javascript, the simplest and easiest way to use is simply creating the values that we are going to use. As recommended in previous sections, this way of creating them is called literal.
const numero =9999.54;const enteroGrande =99999999999999n;const boleano =true;const nulo =null;let noDefinido;const simbolo =symbol('identifier');const cadenaDeCaracteres ='Jaime Cervantes Velasco';const cadenaDeCaractresConExpresion =`El numero ${numero} es "Number"`;const object ={};const arreglo = [];
There are even more details to cover about data types in javascript, but as we go we will see more necessary topics, for now it seems to me that this information is enough.
The model or map of how we see the real world, that is a paradigm, it is a way of seeing and doing things. Following this logic, a programming paradigm is nothing more than a way of viewing and creating programming code.
Paradigms are powerful because they create the glasses or lenses through which we see the world.
There are three main programming paradigms used today and in JavaScript they have always existed since its first version.
Structured programming paradigm
Object-oriented
Functional
Now, if we stick to the phrase of Stephen R. Covey, that paradigms create the lenses through which we see the world. Let's imagine that the three previous paradigms, each, are a pair of glasses that we put on when programming and that we can change those glasses according to our visual needs (for programming or problem solving).
Structured programming paradigm
Origin
In 1954 the FORTRAN programming language appeared, then in 1958 ALGOL and in 1959 COBOL. Time after Edsger Wybe Dijkstra in 1968 discover the structured programming paradigm, we say “discover” because they didn't actually invent it. Although this programming paradigm was formalized some time after the appearance of these programming languages, it was possible to do structured programming in them.
Dijkstra He recognized that programming was difficult, and programmers don't do it very well, which I totally agree with. A program of any complexity has many details for the human brain. In fact, the Neuroscience tells us that the focused mind It can only work with four pieces of data at a time, at most. For this reason, if one small detail is neglected, we create programs that seem to work well, but fail in ways you never imagine.
Evidence
Dijkstra's solution was to use tests, only these tests used a lot of mathematics, which was quite difficult to implement. During his research he found that certain uses of GOTO made it difficult to decompose a large program into smaller pieces, it could not be applied “divide and conquer”, necessary to create reasonable evidence.
Sequence, selection and iteration
Böhm and Jacopini They proved two years earlier that all programs can be built by just three structures: sequence, selection and iteration. Dijkstra already knew these three structures and discovered that these are the ones necessary to make any part of the program tested. This is where the structured programming paradigm is formalized.
Edsger tells us that it is bad practice to use GOTO and suggests better using the following control structures:
If, then, else (selection)
do, while, until (iteration or repetition)
Decomposition of small units easy to test
Nowadays most programming languages use structured programming, JavaScript uses this type of programming. The simplest example is if conditions.
const EDAD_MINIMA =18;if (edad >= EDAD_MINIMA) {// hacer algo porque es mayor que 18}else{// Hacer otra cosa en caso contraio}
And if we isolate it in a function, we have a decomposition of functionalities or units that can be tested more easily. In the next section we will see the importance of having a completely probable unit
With this condition we have direct control of what can happen if the age is greater than or equal to 18, and also in the event that the age is younger.
Let's not be so strict either, surely the GOTO ruling has its merits and perhaps it was very efficient in some cases, but I think that to avoid misuses that probably caused disasters, Dijkstra recommended to stop using GOTO.
Test, divide and conquer
Structured programming allows us to apply the “divide and conquer” philosophy, because we allows you to create small unit tests, until the entire program is covered. The mathematical solution of Wybe Dijkstra It was never built, precisely because of its difficulty in implementation. And unfortunately today there are still programmers who do not believe that formal tests are useful for create high quality software.
And I say create, because verify correct operation after create, is nothing more than a simple measurement and the opportunity to reduce time and money is lost.
Scientific method, experiments and impiricism
The good news is that the mathematical method is not the only way to verify our code, we also have the scientific method. Which cannot prove that things are absolutely correct from a mathematical point of view. What we can do is create experiments and obtain enough results to verify that our theories work. Since our theories work on these experiments, then we conclude that they are “correct” enough for our validation purposes.
If the theory is easily validated as false, then it is time to modify or change it. This is the scientific method and this is how tests are currently done:
First we establish our theory (write the test), then we build the experiments (write production code) and finally we verify (run the test) and repeat this cycle until we have enough evidence.
Tests show the presence, not the absence, of defects
Edsger Wybe Dijkstra said “Testing shows the presence, not the absence, of defects.” That is, a program can be proven wrong by testing, but it cannot be proven correct. All we can do with our tests is validate that our program works well enough for our goals. But we can never be one hundred percent sure of the absence of defects.
If we can never be one hundred percent sure that our code is correct, even with its tests, what makes us think that without tests we deliver a program with sufficient validity to affirm that no negligence is consciously committed?
direct control
lto structured programming teaches us about direct control, that is, controlling the sequential flow of operations through the control structures, without neglecting the recommendation of Wybe Dijkstra about GOTO. This recommendation also applies to statements that drastically change the normal flow of operations, for example a breakwithin a cycle for nested, that breakIt breaks direct control because it abruptly complicates the understanding of the algorithm. Let's not be purists either, there will surely be cases where you need these sentences, but in the first instance, try to avoid them.
In conclusion, the structured programming paradigm teaches us:
The direct, clear and explicit control of what a piece of code does
Object-oriented programming paradigm
Arised from functions?
The object-oriented programming paradigm was discovered in 1966 by Ole Johan Dahl and Kristen Nygaard when they were developing simula 67. Two years before structured programming and its adoption by the programming community was some time later. In 1967 it was launched Simulates 67, Simulates It was the first object-oriented programming language, it basically added classes and objects to ALGOL, initially Simula was going to be a kind of extension of ALGOL.
During the development of Simula, it was observed that the execution of an ALGOL function requires certain data, which could be moved to a tree structure. This tree structure is a Heap.
The parent function becomes a constructor, the local variables become the properties, and the child (nested) functions become its methods. In fact, this pattern is still widely used by Javascript to create modules and use functional inheritance. This also describes how classes work in Javascript, behind are functions.
Spread of polymorphism
All this helped a lot to implement polymorphism in object-oriented programming languages. Ole Johan Dahl and Kristen Nygaard invented the notation:
object.function(parametro)
The execution of function that belongs to object, but more importantly, we pass a message through parameters from the first part of the code to the second part located in a different object.
Molecular biology and message passing
Some time later it was created Smalltalk, a much more sophisticated and modern object-oriented programming language, in charge of this project was Alan Kay. This person is credited with the formal definition of object-oriented programming.
The main influence on Alan Kay's object-oriented programming was biology, he has a degree in biology. Although it is obvious that it was influenced by Simula, the influence of LISP (functional programming language) is not so obvious.
From the beginning he thought of objects as interconnected cells in a network, from which they could communicate through messages.
Alan Kay commented:
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
My English is bad so you can check the original text here.
Better object composition over class inheritance
Smalltalk It also allowed the creation of Self, created at Xerox Parc and later migrated to Sun Microsystems Labs. It is said that Self It is an evolution of smalltalk.
In this programming language the idea of prototypes, eliminating the use of classes to create objects, this language uses the objects themselves to allow one object to reuse the functionalities of another.
Self It is a fast language and is generally known for its great performance, self It did a good job on garbage collection systems and also used a virtual machine to manage its execution and memory.
The virtual machine Java HotSpot It could be created thanks to Self. Lars Bak one of Self's latest contributors, he was in charge of creating the V8 Javascript engine. Due to the influence of Self we have today the engine of JavaScriptV8, which uses it node.js, mongoDB andGoogle Chrome internally.
Self followed one of the book's recommendations Design Patterns: Elements of Reusable Object-Oriented Software, long before it came out, published this recommendation:
Better composition of objects to class inheritance.
Design Patterns: Elements of Reusable Object-Oriented Software
Example
Currently Javascript uses prototypes for code reuse, you could say that it uses composition, instead of inheritance. Let's look at an example:
const person ={greet(){return'Hola'}};// se crea un programador con el prototipo igual al objeto personaconst programmer = object.create(persona);programmer.programar=()=>'if true';const saludo = programmer.greet();const codigo = programmer.programar();console.log(saludo);// 'Hola'console.log(codigo);// 'if true'
The object programmer It is based on the prototype of `person`. It doesn't inherit, it just directly reuses the functionality of `person`.
JavaScript emerged shortly after JAVA, in the same year. JavaScript took influences from Self, and in turn Self was influenced by smalltalk.
The syntax of current classes in Javascript is nothing more than a facade, well a little more accurately they are an evolution of the constructor functions, but internally, their basis are functions and prototypes.
Communication with message passing
As we already saw, the origin of object-oriented programming has its origins in functions, and the main idea has always been communication between objects through message passing. We can say that Object-oriented programming tells us of message passing as a key piece for the communication of objects, for example, when a method of one object invokes the method of another.
object.function(parametro);
In conclusion, the object-oriented programming paradigm teaches us:
Message passing for communication between objects
Functional programming paradigm
lambda calculation
Functional programming is the oldest programming paradigm, in fact its discovery was long before computer programming, it was discovered in 1936 by Alonzo Church, when I invented the lambda calculus, based on the same problem to be solved by your student Alan Turing.
As a curious fact, the symbol of the lambda calculus is:
λ
The first language based on functional programming was LISP, created by John McCarthy. As we saw previously, Alan Kay also took influence from LISP to create Smalltalk, with this we can see that the programming paradigms can be united and their relationship between them arises from the idea of how to solve problems more efficiently, they are not fighting, nor Separated, they seek the same goal and somehow evolve together.
The basis of the lambda calculus is immutability,We will review this concept later.
Similarities with OO and structured paradigms
As we saw in the structured programming paradigm, we can decompose our programs into smaller units called procedures or functions. Since functional programming is the oldest paradigm, we can say that the structured programming paradigm also relies on functional programming.
Now, if we analyze the notation a little object.function(x) that we saw in the object-oriented programming paradigm section, is not very different from function(object, parameters), these two lines below are the same, the fundamental idea is the passing of messages, as Alan Kay tells us.
Smalltalk uses the “The Actor Model”, which says that actors communicate with each other through messages.
On the other hand we have LISP, which has a “Function dispatcher model” What we currently call functional language, these models are identical, because what functions and methods do is send messages between actors.
An example of this is when a function calls another function or when an object's method is invoked, what happens is that actors exist and they communicate with each other through messages.
Message passing again
So we can emphasize that the main idea of OOP is the sending of messages and that it is not very different from functional programming, in fact according to what we already established in the previous sections, OOP was born from a functional base. And here it is important to highlight what he said Alan Kay Co-creator of SmallTalk:
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
From the communication models between Smalltalk and LISP messages, it was created scheme.
scheme has the goodness to use tail recursion and closure to obtain a functional language, closure allows access to the variables of an external function even when it has already returned a value. This is the same principle that gave rise to object-oriented programming by Ole Johan Dahl and Kristen Nygaard. Do you remember the closure question in Javascript?
Javascript uses closure a lot in its functional programming paradigm. JavaScript took influences from scheme, at the same time scheme was influenced by LISP.
No side effects
The basis of the lambda calculus is immutability, therefore, lImmutability is also the basis of the functional programming paradigm.
We as functional programmers must follow this principle and limit object mutations as much as possible to avoid side effects.
I repeat, the main idea of functional programming is immutability, which allows you to create your programs with fewer errors by not producing side effects that are difficult to control.
As an example, suppose we have an object person and we want to “change” the name, the most obvious thing would be to modify the name property directly, but what happens if that object is used elsewhere and the name is expected to be “Jaime”, that is why instead of changing the name property , we only create a new person object with a different name, without modifying the original.
functionscambiarNombre(name,person){return{ name:name, edad:person.edad}}const James ={name:'Jaime',edad:30};const juan =cambiarNombre('Juan', jaime);console.log(jaime);// { nombre: 'Jaime', edad: 30 }console.log(juan);// { nombre: 'Juan', edad: 30 }
Here you will find more details about the fundamental principles of functional programming:
Finally, the functional programming paradigm teaches us:
No side effects, for clear expression and less prone to errors
Conclusion
It is important to note that if the three programming paradigms were implemented between 1958 with LISP (functional programming) and Simula (object-oriented programming) in 1966, and the discovery of the structured programming paradigm in 1968, in only a period of 10 For years there has been innovation in programming paradigms, and new paradigms have not really emerged, unless they are based on these three main ones.
Right now more than 60 years have passed, which tells us the importance and firmness they have despite the time that has passed.
Functional programming paradigm (1958, already implemented in a programming language for computers, remember that it was discovered in 1936)
Object Oriented (1966)
Structured (1968)
The implementation of these three paradigms from the beginning within JavaScript has made this programming language the global success it is today. And it proves to us the value of combining paradigms when writing our programs.
JavaScript is a multi-paradigm programming language, so you can combine the paradigms to create much more efficient and expressive code using:
The direct, clear and explicit control of what a piece of code does
Message passing for communication between objects
No side effects, for clear expression and less prone to errors
One of the most used elements are variables in Javascript. We can describe variables in Javascript as boxes to hold information, which we label so that we can find that information easily. This label is the name of the variable and the box is the space used in RAM.
This is what variables are like in Javascript, and in fact in any programming language. You can also store any datatype, whether they are numbers, text strings, functions or any type of object.
There are two ways to declare a variable. One is using let and the other using var.
//Variables de tipo Stringvar name ='Jaime';let last name ="Cervantes"
The shape var It is the one that has always existed since the origin of language, then in 2015 it appeared let in order to mitigate certain deficiencies of var. For this reason, the recommendation is to use letIn any case, it is important to know well var because you will come across a lot of code that still uses var.
How are variables used in Javascript?
The name or identifier of a variable, it cannot start with a number, it must start with some letter (including _ and $), and Javascript is also case-sensitive. Is not the same name and Name, these are two different variables.
Variables are defined in two ways:
With a single let:
let name ='Jaime', last name ='Cervantes', mother's last name ='Velasco';
a single var:
var name ='Jaime', last name ='Cervantes', mother's last name ='Velasco';
Now with a let for each variable:
let name ='Jaime';let last name ='Cervantes';let mother's last name ='Velasco';
With a var for each variable.
var name ='Jaime';var last name ='Cervantes';var mother's last name ='Velasco';
In the previous example we define variables of type string (text strings), but remember that you can store any type of data.
It is advisable to put each variable on its own line because it is faster to understand for the “you” of the future and your colleagues who have not touched your code. For example, DO NOT define the variables like this:
let name ='Jaime', last name ='Cervantes', mother's last name ='Velasco'; edad =32, sexo ='H'
Let's try numbers.
let edad =32.9;let hijos =1;
var edad =32.9var hijos =1;
Boolean data only stores false or true.
let esHombre =true;let esAlto =false;
var esHombre =true;var esAlto =false;
As its name says, its value can be variable, therefore you can reassign a new value to your variable:
var name ='Jaime';name ='Pepito';name ='Menganito';console.log(nombre);// 'Menganito'
Variable scopes in Javascript, let vs var
The main difference between variables defined with let and var is the scope they reach when they are declared:
With let you have block scope {}.
With var you have scope of function function() but not block.
Example of block scope.
if (true) {letname='James';}console.log(nombre);// Uncaught ReferenceError: nombre is not defined
Because let has block scope, when wanting to access the variable name Javascript shows:
Uncaught ReferenceError: name is not defined
Try to use block scope with var.
if (true) {varname='Jaime';}console.log(nombre);// 'Jaime';
In this example the variable name If it can be accessed from outside the blocks, this is because it is not inside any function.
Now we are going to declare the variable with var inside a function.
functionssetearNombre(){varname='Jaime';}setearNombre();console.log(nombre);// Uncaught ReferenceError: nombre is not defined
Let's see what happens with let when we try to use function scope.
functionssetearNombre(){letname='Jaime';}setearNombre();console.log(nombre);// Uncaught ReferenceError: nombre is not defined
If we define a variable with let inside a function, we can't access it from outside either, because the function definition itself uses blocks {}.
Constants in Javascript
Constants are in the same way as variables, labeled boxes to store information, with the only difference that they cannot be reassigned to any other value.
const name ="Jaime";name ="Pepito";// Uncaught TypeError: Assignment to constant variable
Let's not forget to declare each constant on its own line to improve the readability of our code.
const name ="Jaime";const last name ="Cervantes";const mother's last name ='Velasco';
const name ='Jaime', last name ='Cervantes', mother's last name ='Velasco';
Same rules as variables with let
Constants follow the same block scope rules as variables in Javascript with let.
As well as let, const has block scope, so if you define a variable with var and has the same name as a constant, the following error will be thrown:
{constname="Jaime";varname="Pepito";// Uncaught SyntaxError: Identifier 'nombre' has already been declared}
Constants in javascript read-only and mutable
Constants are read-only, which is why they cannot be reassigned a value. Even so, these saved values continue to preserve the behavior of their data type.
For example, if you create a constant for an object, you can change the properties of that object.
An object literal in JavaScript is nothing more than a set of values identified with a name or key, like the following:
const James ={name:"Jaime",last name:"Cervantes",mother's last name:"Velasco"};James.name ="Pepito";// todo bien, se puede cambiar una propiedadJames ={};// Uncaught Type Error: Assigment to constant variable
The reference to the object is read-only, but it does not mean that the value is immutable. As seen in the example, you can change the property, but not reassign a new value to the constant James as we can see in the last line of the example.
How to name variables and constants in Javascript?
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
Martin Fowler
The main objective of naming variables and constants is to immediately understand what we are storing in them. It is important to correctly describe the content of the variables, because this makes life easier for the next person who needs to read and modify our code.
This next person is very often “you” from the future, and unless you are a robot, you won't be able to remember every detail of your code.
Most of the time spent by a programmer is reading and understanding code, we don't want to spend a lot of time deciphering the content of them, as programmers we are happier creating new things.
For this reason we should not be surprised by the importance in naming our variables and constants, it is one of the best ways to not waste our time and the time of our colleagues.
Recommendations:
Take enough time to name a variable. It's like organizing your room, the tidier it is, the faster it will be to find the other sock (it happens to me a lot when I don't organize mine) xd.
The name must be very semantic and explain its context. Avoid names like data either info because they don't say much about the context, it is obvious that they are data and information, but for what? or what?.
Agree with your colleagues on how to name variables, especially those that are closely related to the business. For example, for a user's registration data, it can be “UserRegistration”, “CustomerRegistration”, “VisitorRegistration”, all three forms can be valid (it depends a lot on the context), but it is better to follow a convention through an agreement.
Avoid very short names like “u1”, “a2”, “_”, “_c”
Avoid abbreviations, prefixes, suffixes and infixes. These are difficult to understand. For example pmContentWhat is “pm”?
If the variable or constant has a very small scope, that is, it is used in nearby lines, then the name can be short.
If the variable or constant is used in a large scope, that is, it is referenced over a distance of many lines, then the name must be very descriptive, and therefore it is normal that it can be long.
¿Cómo logramos encapsulación de nuestros nuevos elementos HTML que no provoque conflictos con el resto de una aplicación?, es decir, que los estilos, HTML interno y JS de un componente web, no colisionen con el resto.
La respuesta básicamente es, el Shadow DOM. El Shadow DOM nos permite tener los estilos y contenido HTML interno totalmente aislado del exterior. También se ayuda del API del DOM and custom elements para establecer comunicación con otros elementos y componentes internos. Además con el exterior.
El amor es de naturaleza interna. No lo vas a encontrar en alguien más, naces con ello, es un componente interno de cada persona. Mira a un bebé, simplemente es feliz por el hecho de existir. Irradia amor, te lo comparte.
Anónimo
Antes de comenzar, si aún no estás familiarizado con los custom elements y los componentes web nativos en general, te recomiendo revisar primero estas publicaciones:
Primero vamos a revisar la etiqueta <template>, para luego utilizarla dentro de nuestro componente web usando shadow DOM.
¿Qué es una plantilla?
Un template o plantilla HTML con el tag <template>, es una forma de crear elementos visuales de manera sencilla y eficiente, de tal forma que se pueden definir partes de una página web o aplicación a las cuales les podemos insertar valores.
Este template puede ser reutilizado en diferentes vistas de una aplicación. Tal vez estés familiarizado con jade, pug, mustache, o con algunos frameworks y librerías como angular y vue, los cuales utilizan templates. También si has utilizado wordpress y php, los archivos de los temas serian una especie de templates.
Ahora, los templates que vamos a aprender son específicos de HTML y por lo tanto funcionan en los navegadores web. Para entrar un poco más en contexto veamos un ejemplo sencillo de como podemos crear varios elementos para mostrar un saludo, utilizaremos estas tres fuciones, que forman parte del API del DOM.
document.createDocumentFragment()
document.createElement('nombreTag', [opciones])
nodo.appendChild(nodo)
Queremos mostrar en nuestra aplicación un saludo al usuario y lo hacemos de la siguiente forma:
Ahora veamos como hacer lo mismo, pero utilizando la etiqueta <template>:
Como podemos ver, con la etiqueta <template> se usa mucho menos código, si el contenido de lo que queremos mostrar crece, solo debemos agregar las etiquetas y demás contenido de manera sencilla dentro de la etiqueta <template>. Pero si usamos el primer método, nuestro código javascript crecerá mucho más, esto es más difícil de entender y mantener con el tiempo.
La etiqueta template usa internamente un DocumentFragment, la ventaja de utilizar document fragments es que su contenido no es aún agregado al árbol de nodos, sino que se encuentra en memoria y se inserta una sola vez al final, cuando el contenido esta completo.
// Agregar document fragment a la páginahost.appendChild(df);
Existen 4 puntos importantes al utilizar la etiqueta <template> para crear plantillas:
The label <template> no se pinta en nuestra aplicación, por default tiene un display: none;.
El contenido de la etiqueta <template> es un document fragment, el cual tiene la característica de no estar insertado en el árbol de nodos. Esto es bueno para el rendimiento de la aplicación debido al alto costo de pintar elementos.
El código JS necesario es muy simple y corto
Cuando clonamos el contenido de nuestro template usando cloneNode(), debemos pasar el valor true como parámetro, de otra manera NO clonaríamos los elementos hijos del document fragment de nuestro template.
Shadow DOM
El shadow DOM es un DOM o árbol de nodos en las sombras, escondidos de los demás elementos de una aplicación. Para entender esto vamos a crear nuestro primer componente web utilizando el estándar de custom elements, la etiqueta <template> y el shadow DOM.
Nuestro componente se llama mi-saludo, con el contenido del ejemplo anterior:
Si aún no sabes que son los custom elements, sigue este link. En el ejemplo anterior creamos un custom element llamado mi-saludo, dentro del constructor() creamos una instancia del template.
// Obtengo la única etiqueta 'template'const tpl = document.querySelector('template');// Clono su contenido y se crea una instancia del document fragmentconst tplInst = tpl.content.cloneNode(true);
Luego creamos un shadow DOM y lo adjuntamos al custom element mi-saludo:
// Se crea un nuevi shadow DOM para las instancias de mi-saludothis.attachShadow({mode:'open'});
Y finalmente agregamos el contenido clonado del template dentro del shadow DOM:
// Y se agrega el template dentro del shadow DOM usando el elemento raíz 'shadowRoot'this.shadowRoot.appendChild(tplInst);
En este último paso usamos la propiedad shadowRoot, creada cundo invocamos attachShadow, esta propiedad hace referencia a un nodo raíz especial de donde se empieza a colgar todo lo que definimos dentro de nuestra etiqueta <template>, y es a partir de este nodo que agregamos contenido.
Lo que se agrega al shadow DOM esta oculto para el exterior, ningún document.querySelector() externo puede acceder a los elementos del shadow DOM y los estilos definidos en el exterior no pueden acceder a estos elementos ocultos. Esto quiere decir que dentro del shadow DOM podemos utilizar atributos id and name sin temor a colisionar con los ids y name del exterior.
Cuando creamos un shadow DOM, se hace con la propiedad mode: open, de esta manera se puede acceder al contenido del shadow DOM usando Javascript y el atributo shadowRoot. Sin el atributo shadowRoot es imposible acceder a los elementos y eso nos proporciona encapsulación a nuestro componente.
Para crear una nueva instancia de nuestro nuevo componente, solo utilizamos el nombre que registramos como etiqueta:
// Se registra el custom element para poder ser utilizado declarativamente en el HTML o imperativamente mediante JScustomElements.define('mi-saludo', MiSaludo);
Y en el html utilizamos código declarativo:
<mi-saludo></mi-saludo>
¿Qué pasa si a nuestro template le agregamos una etiqueta style? Debido a que las instancias de nuestro template son agregadas al shadow DOM, entonces esos estilos solo afectan dentro del shadow DOM.
Para establecer estilos dentro del shadow DOM al nuevo tag creado, se utiliza la pseudoclase :host, que hace referencia a la etiqueta huésped del shadow DOM, es decir, mi-saludo.
También agregamos en el exterior estilos para las etiquetas <h1>, estos estilos no pudieron afectar al contenido interno del shadow DOM, el único h1#mi-id con borde rojo es el que se encuentra fuera de nuestro componente. El h1 externo como el interno tienen el mismo id, a causa del encapsulamiento con shadow DOM, no colisionan los estilos con el mismo selector de id.
Ahora en nuestro código html, agreguemos más etiquetas mi-saludo:
Como podemos ver la combinación de estas tres tecnologías; custom elements, template y shadow DOM nos permite crear nuevas etiquetas personalizadas con su propio contenido interno sin afectar el exterior y también el exterior no puede afectar directamente la implementación interna de nuestro componente. En el último ejemplo podemos ver como creamos cuatro instancias de nuestro componente simplemente utilizando etiquetas, es decir, reutilizando nuestro componente encapsulado.
En la próxima publicación veremos como implementar más funcionalidad Javascript encapsulada del componente web y también más características muy útiles del shadow DOM como composición, eventos y más estilos. Finalmente veremos los módulos de JS para completar un componente web reutilizable que pueda ser importado en cualquier otra aplicación web.
“Event loop”, tal vez lo has escuchado. Esto es porque javascript tiene modelo de ejecución de código donde utiliza un ciclo de eventos (event loop), que una vez entendiendo su funcionamiento, se puede crear código mucho más eficiente, y resolver problemas rápidamente, que a simple vista no son tan obvios. Es la base de la concurrencia y el asincronismo.
Para comenzar:
Javascript se ejecuta en un solo hilo de ejecución, como se ejecuta un solo hilo, su ejecución es secuencial, no es como JAVA donde se pueden lanzar otros hilos.
Existen ambientes huéspedes donde se ejecuta javascript que tienen su propia API, ejemplo:
Navegador web
Node.js
Este funcionamiento secuencial es el mismo, no cambia por estar relacionado con un ambiente huésped.
La concurrencia se logra a través de invocaciones asíncronas a la API del ambiente huésped, esto evita que el funcionamiento se bloquee y provoque lentitud de las aplicaciones.
Elementos para la concurrencia
Veamos con más detalle los elementos que hacen funcionar Javascript en los ambientes huéspedes.
Call Stack – Pila de ejecuciones
Callback Queue – Cola de retrollamadas, tambien llamado Task Queue
Event Loop – Ciclo de eventos
Host Environment – Funcionalidad del ambiente huésped
Calls Stack, heap y motor de javascript
Del lado izquierdo tenemos al motor de javascript, este motor se encarga de ejecutar nuestro código. A veces es llamado máquina virtual, porque se encarga de interpretar nuestro código a lenguaje máquina y ejecutarlo. Solo puede ejecutar una línea de código a la vez. Tiene un Heap para guardar objetos y demás datos en memoria que el código pueda generar.
Pero también tenemos una Pila de llamadas (Call Stack). Los elementos de la pila son objetos y datos de memoria, pero tienen una estructura especifica. Tienen un orden y el último elemento en entrar es el primero en salir, se le llama LIFO (Last-in, First-out).
Cada elemento de la pila es un trozo de código Javascript y guarda las referencias del contexto y variables utilizadas. La pila ejecuta el trozo de código en turno hasta quedar vacía.
Callbacks Queue
Abajo tenemos Callbacks Queue, es una estructura de datos y guarda pedazos de código que el motor de javascript puede ejecutar. Es una cola, y como la cola de las tortillas el primero en formarse, es el primero en salir (FIFO, First-in, First-out).
Un callback, es una función que se pasa por parámetro a otra, de tal manera que esta última ejecuta el callback en un punto determinado, cuando las condiciones y/o los datos cumplen una cierta regla de invocación.
Event loop
Event Loop, este elemento nos permite mover la siguiente callback del Callbacks Queue al Call Stack. Como es un ciclo, en cada iteración toma un solo callback.
Ambiente huésped
Del lado derecho tenemos El ambiente huésped, el ambiente huésped es el lugar donde corremos Javascript, los más comunes son el Navegador web and Node.js. Las tareas que ejecuta el ambiente huésped son independientes de los demás componentes. En el navegador web tiene sus propias API como fetch, setTimeout, alert. Node.js también cuenta con su propia API como net, path, crypto.
¿Cómo es posible?, ¿Y la concurrencia? ¿Puedo hacer muchas cosas a la vez en un sitio web?
Todo el trabajo de poner un temporizador, renderizar contenido como texto, imágenes, animaciones, o ver videos, están a cargo del ambiente huesped. Lo que pasa es que las APIs del navegador web generan callbacks cuando su tarea ya está completada y los agrega al Callbacks Queue para que el event loop las tome y las mueva al Callstack.
Javascript se comunica con el ambiente huésped a través de su API, mas adelante vamos a utilizar un ejemplo basado en el diagrama de arriba, donde se utiliza window.setTimeout, la cual es una función del navegador web.
Concurrencia
Home es la función principal, con la que se inicia el proceso de ejecución en el call stack. Dentro de inicio tenemos cuatro setTimeout de dos segundos. La función setTimeout es propia del ambiente huésped, y a los cuatro setTimeouts le pasamos un callback, estos son, cb1, cb2, cb3 y cb4.
Los temporizadores setTimeout se ejecutan en la parte de la funcionalidad del ambiente huésped dejando tiempo de ejecución para el call stack. He aquí la concurrencia, mientras el ambiente huésped ejecuta un temporizador, el call stack puede continuar ejecutando código.
Después de los primeros dos segundos, el ambiente huésped, a través del primer setTimeout pasa cb1al callback queue, pero durante estos dos segundos se pueden realizar otras operaciones en el ambiente huésped, en el caso del navegador, un ejemplo seria que el usuario puede seguir escribiendo dentro de un textarea. De nuevo, he aquí la concurrencia.
Tras el primer setTimeout, el segundo setTimeout pasa cb2al callback queue y así sucesivamente hasta el cb4. Mientras los callbacks se pasan al callback queue. He event loop nunca deja de funcionar, por lo que en alguna iteración el event Loop pasa cb1al call stack y se empieza a ejecutar el código de cb1y esto mismo sucede con cb2, cb3 and cb4.
Event loop en acción
Aquí abajo esta el ejemplo del que hablamos, el temporizador genera los callbacks en el orden que aparecen los setTimeouts más dos segundos. El Event Loop toma un callback en cada iteración, por lo que cada cb de setTimeout se invocan uno después del otro, y no exactamente después de dos segundos, pues entre que se posicionan los callbacks en la cola y se mueven al callstack de ejecución transcurre más tiempo. Esto sin contar el tiempo que trascurre entre cada invocación de setTimeout.
Si en los cuatro callbacks se indica el mismo tiempo en milisegundos. Presiona el botón RERUN, Te darás cuenta de que los tiempos no son iguales y que pueden pasar más de dos segundos.
Conclusion
Las APIs huéspedes reciben callbacks que deben insertar en la callback queue cuando el trabajo que se les encomienda esta hecho, por ejemplo un callback de una petición ajax se pasa a la callback queue solo cuando la petición ya obtuvo la respuesta. En el ejemplo que describimos arriba con setTimeout, cuando pasan dos segundos, se inserta el callback al callback queue.
Mientras el ambiente huésped realiza sus tareas, en este caso, los demás temporizadores, el call stack de ejecución de javascript puede ejecutar el código que el event loop le puede pasar desde el callback queue.
He Event loop es un ciclo infinito que mientras existan callbacks en el callback queue, pasara cada callback, uno por uno, al call stack.
He call stack no puede ejecutar más de un código a la vez, va ejecutando desde el último elemento hasta el primero, en nuestro caso hasta la terminación de la función inicio que dio origen a todo el proceso. Es una estructura de datos tipo Pila.
Gracias a que los callbacks se ejecutan hasta que un trabajo específico esté terminado, proporciona una manera asíncrona de ejecutar tareas. Las tareas pueden realizarse en el ambiente huésped sin afectar la ejecución del call stack. En la pila solo se ejecuta código que recibe el resultado de las tareas realizadas por el ambiente huésped.