Introduction

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 guys primitive data in Javascript.
  1. number, numbers like; 1, 0, 18500, 89.95124
  2. BigInt, added in 2020, to represent very, very large integers, 99999999999999n
  3. String, character string like 'Hello' and "Good night".
  4. Boolean, only accept true either false, that is, yes or no.
  5. null, serves to indicate that something is nothing, its only value is null.
  6. undefined, serves to indicate that something is not yet defined.
  7. 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 NaN
25 * {}; // es igual a NaN

Any operation you have NaN as one of its operands, will result in NaN.

25 * NaN; // es igua a NaN
25 + NaN; // es igual a NaN

NaN it is not even equal to NaN

NaN === NaN; // es igual a false
NaN == 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 global
isNaN('James'); // true --> Esto esta mal, deberia seguir regresando false
// lo que realmente hace es una conversion automatica
const result = number('James'); // NaN
isNaN(result); // true
number.isNaN('343434'); // false
number.isNaN('James'); //false
number.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.

number('5'); // 5
number(''); // 0
number(undefined); // NaN
number(null); // 0
number('8778jaime'); // NaN
number(false); // 0
number(true); // 1;
number({}); // NaN
number([]); // 0

Number.parseInt and Number.parseFloat

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.

number.parseInt(''); // NaN
number.parseInt('78.5jaime'); // 78
number.parseInt(78.58977); // 78
number.parseFloat(''); // NaN
number.parseFloat('78.5jaime'); // 78.5

BigInt

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.9498743710662
Mathematics.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; // undefined
let edad; // undefined
name === undefined; // true
edad === 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:

  1. With single quotes, ''. Recommended if you do not need to evaluate expressions inside.
  2. Double quotation marks, ""
  3. 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 ===.

"James" === "James"; // true
'James' === "James"; // true
`James` === 'James'; // true

Function String(value)

To convert a value to a string you can use the function String(value).

String(1); // '1'
String(null); // 'null'
String(undefined); // 'undefined'

String.length

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 = new String('Jaime Cervantes Velasco');
nuevoString.length; // 23
(5).toFixed(2); // 5.00
// Igual a groso modo pasa algo asi:
const numero = new number(5);
numero.toFixed(2); // 5.00
false.toString(); // 'false'
// Igual a groso modo pasa algo asi:
const booleano = new Boolean(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.

const vacio = {};
const person = {
  name: 'Jaime',
  apellidos: 'Cervantes Velasco',
  edad: 33,
  getName: functions () {
    return `${this.name} ${this.apellidos}`;
  },
  talk: functions () {
    return `Hola, soy ${this.getName()}, tengo ${this.edad} años.`;
  }
};
const frase = person.talk();
console.log(frase); // 'Hola soy Jaime Cervantes Velasco, tengo 33 años.'

In the example we have an object person, has several properties of different types, its name is a String, his age is a numbergetName 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 33
persona['edad']; // regresa 33
// obtenemos la funciónn con corcheteds y la invocamos con parentesis
const frase = persona['talk']();
console.log(frase); // 'Hola soy Jaime Cervantes Velasco, tengo 29 años.'

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

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 imprimierPersona(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

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

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); // false
Boolean(null); // false
Boolean(undefined); // false
Boolean(0); // false
Boolean(0n); // false
Boolean(NaN); // false
Boolean(''); // false
// Todos los demas valores van a regresar true
Boolean(' '); // true
Boolean('false'); // true
Boolean('jaime cervantes'); // true
Boolean({}); // true
Boolean([]); // true;

Under logical conditions

Logical conditions in javascript check without a return expression true either false, they execute an implicit conversion.

if (false) {
} else {
  console.log(false);
}
if (null) {
} else {
  console.log(false);
}
if (undefined) {
} else {
  console.log(false);
}
if (0) {
} else {
  console.log(false);
}
if (0n) {
} else {
  console.log(false);
}
if (NaN) {
} else {
  console.log(false);
}
if ('') {
} else {
  console.log(false);
}
if (' ') {
  console.log(true);
}
if ('false') {
  console.log(true);
}
if ({}) {
  console.log(true);
}
if ([]) {
  console.log(true);
}

Verify types with the operator typeof

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.

typeof 5; // 'number
typeof NaN; // 'number'
typeof 99999999999999999999999999999999999999999999999n; // 'bigint'
typeof true; // 'boolean'
typeof null; // 'object', esto es un error que existe desde la primera versión de JS
typeof undefined; // 'undefined'
typeof symbol('simbolo'); // 'symbol'
typeof 'cadena de caracteres'; // 'string'
typeof {}; // 'object'
typeof []; // 'object
typeof new date(); // 'object'
typeof new String('Jaime'); // Object
typeof functions() {} // 'function'
typeof class A {} // '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.

object.prototype.toString.call(5); // '[object Number]'
object.prototype.toString.call(NaN); // '[object Number]'
object.prototype.toString.call(99999999999999999999999999999999999999999999999n); // '[object BigInt]'
object.prototype.toString.call(true); // '[object Boolean]'
object.prototype.toString.call(null); // '[object Null]',
object.prototype.toString.call(undefined); // '[object Undefined]'
object.prototype.toString.call(symbol('simbolo')); // '[object Symbol]'
object.prototype.toString.call('cadena de caracteres'); // '[object String]'
object.prototype.toString.call({}); // '[object Object]'
object.prototype.toString.call([]); // '[object Array]'
object.prototype.toString.call(new date()); // '[object Date]'
object.prototype.toString.call(new String('Jaime')); // '[object String]'

From this method, you can create a function that verifies the data type.

functions getTypeOf(worth) {
  const texto = object.prototype.toString.call(worth); // '[object Number]', '[object Boolean]', etc
  const sinPalabraObject = texto.slice(8, -1); // Number, Boolean, Null, Undefined, Symbol, String, etc.
  const tipo = sinPalabraObject.toLowerCase(); // number, boolean, null, undefined, symbol, string, etc.
  return tipo;
}
getTypeOf(1); // 'number'
getTypeOf(new date()); // date
getTypeOf([]); // array

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.

en_USEN