Data types

Data types

JavaScript is a dynamic and flexible programming language, known for its versatility in web development. One of the fundamental features that every developer must master is data types. In this article, we will explore in detail the different data types in JavaScript and how to work with them.

Primitive Data Types

JavaScript has six primitive data types:

1. Number

The type Number represents both integer and floating-point numbers.

let entero = 42;
let decimal = 3.14;

JavaScript also includes special values like Infinity, -Infinity, and NaN (Not a Number).

2. String

Text strings are represented with the type String.. They can be enclosed in single quotes, double quotes, or backticks.

let nombre = 'Alice';
let saludo = 'Hola, mundo!';
let plantilla = `Bienvenido, ${nombre}`;

3. Boolean

The Boolean type has only two possible values: true or false.

let estaLloviendo = true;
let haceSol = false;

4. Undefined

undefined represents a variable that has been declared but not initialized.

let variableSinDefinir;
console.log(variableSinDefinir); // Imprime: undefined

5. Null

null is a special value that intentionally represents “nothing” or “empty”.

let valorNulo = null;

6. Symbol (ES6)

Introduced in ES6, Symbol creates unique identifiers.

const simbolo = Symbol('descripcion');}

Object Data Type

In addition to primitive types, JavaScript has a complex data type: Object.

Object

Objects are collections of key-value pairs and can contain properties and methods.

let persona = {
  nombre: 'Bob',
  edad: 30,
  saludar: function () {
    console.log('Hola!');
  },
};

Arrays, functions, and regular expressions are special types of objects in JavaScript.

let numeros = [1, 2, 3]; // Array
let funcion = function () {}; // Función
let regex = /abc/; // Expresión regular

Type Checking

To check the type of a variable, you can use the operator typeof:

console.log(typeof 42); // "number"
console.log(typeof 'hola'); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (esto es considerado un error en JavaScript)
console.log(typeof {}); // "object"

Type Conversion

JavaScript allows conversion between different data types:

let num = Number('42'); // Convierte string a number
let str = String(42); // Convierte number a string
let bool = Boolean(1); // Convierte a boolean (true para valores "truthy", false para "falsy")

Conclusion

Understanding data types in JavaScript is fundamental for writing robust and efficient code. The dynamic nature of JavaScript offers great flexibility, but it also requires developers to be aware of how different data types behave in various operations.

Mastering data types will allow you to:

  • Avoid common type errors
  • Optimize the performance of your code
  • Write more predictable and easier-to-debug functions
  • Make the most of the features of the language

Sources: Language JavaScript