Symbol and BigInt in JavaScript

Symbol and BigInt in JavaScript

Introduction to Symbol

In JavaScript, a Symbol is a type of primitive data that was introduced in ECMAScript 2015 (ES6). Symbolss are unique and immutable, which makes them useful for identifying object properties without the risk of collision with other properties.

Creation of a Symbol

To create a Symbol, the Symbol() function is used. Each call to Symbol() generates a unique value of type Symbol.

const symbol1 = Symbol();
const symbol2 = Symbol();

console.log(symbol1 === symbol2); // false

You can also create a Symbol with an optional description, which is mainly useful for debugging purposes.

const symbolWithDesc = Symbol('mySymbol');
console.log(symbolWithDesc.description); // "mySymbol"

Use of Symbol in object properties

Symbols can be used as keys for object properties, allowing you to define properties that will not collide with other properties of the object.

const mySymbol = Symbol('uniqueKey');
const myObject = {
  [mySymbol]: 'Value associated with mySymbol',
};

console.log(myObject[mySymbol]); // "Value associated with mySymbol"

Unlike properties defined with strings, properties defined with Symbols are not listed in a for…in loop or in methods like Object.keys(), which can be useful for defining “hidden” properties.

Introduction to BigInt

The type BigInt was introduced in ECMAScript 2020 (ES11) and allows representing integers larger than the limit that the Number type can handle in JavaScript, which is 2^53 - 1 for positive numbers and -(2^53 - 1) for negative numbers.

Creation of a BigInt

A BigInt can be created by adding the letter n at the end of an integer, or by using the BigInt() function.

const bigInt1 = 1234567890123456789012345678901234567890n;
const bigInt2 = BigInt('1234567890123456789012345678901234567890');

console.log(bigInt1 === bigInt2); // true

Operations with BigInt

BigInts support the same operations as regular numbers (+, -, *, /, etc.), with the exception that BigInt and Number cannot be mixed in arithmetic operations.

const bigIntSum = 100000000000000000000000000000n + 100000000000000000000000000000n;
console.log(bigIntSum); // 200000000000000000000000000000n

const bigIntDivide = 10n / 3n;
console.log(bigIntDivide); // 3n (Los BigInt siempre redondean hacia cero)

Conclusion

Symbol and BigInt are powerful features of JavaScript that allow developers to handle unique identifiers and extremely large integers, respectively. Proper use of these tools can lead to more robust and less error-prone code in complex applications.