Logo

dev-resources.site

for different kinds of informations.

Exploring JavaScript's Modern Primitives: BigInt and Symbol

Published at
10/14/2024
Categories
javascript
programming
bigint
es6
Author
joanperamas
Categories
4 categories in total
javascript
open
programming
open
bigint
open
es6
open
Author
11 person written this
joanperamas
open
Exploring JavaScript's Modern Primitives: BigInt and Symbol

In the ever-evolving world of JavaScript, new features are introduced to tackle the limitations of the language and provide developers with more robust tools to build their applications. Two such features are the BigInt and Symbol primitives, both introduced in ECMAScript 2015 (ES6) and later. These types bring new capabilities to JavaScript, allowing developers to handle large integers and create unique identifiers with ease.

Understanding BigInt

The BigInt type in JavaScript is designed to represent whole numbers larger than the safe integer limit of the Number type, which is (2^{53} - 1). The BigInt type allows you to work with numbers beyond this limit without losing precision, making it ideal for use cases in cryptography, scientific computation, and financial applications.

Creating BigInt Values

Creating a BigInt is straightforward. You can use the n suffix for literals or the BigInt constructor for strings or numbers:

// Using the 'n' suffix
const bigInt1 = 1234567890123456789012345678901234567890n;

// Using the BigInt constructor
const bigInt2 = BigInt("1234567890123456789012345678901234567890");
Enter fullscreen mode Exit fullscreen mode

BigInt Operations

You can perform arithmetic operations with BigInt just like with regular numbers, but with some caveats. Operations between BigInt and Number require explicit conversion:

const bigInt = 100000000000000000000n;
const num = 2;

// Addition
const sum = bigInt + BigInt(num); // 100000000000000000002n

// Multiplication
const product = bigInt * 3n; // 300000000000000000000n

// Division
const quotient = bigInt / 2n; // 50000000000000000000n
Enter fullscreen mode Exit fullscreen mode

Considerations for BigInt

  • No Mixing Types: You must explicitly convert between BigInt and Number.
  • No Decimals: BigInt is strictly for whole numbers.
  • Performance: Operations may be slower than those with Number due to overhead.
  • JSON Compatibility: BigInt cannot be directly serialized to JSON.

Understanding Symbol

The Symbol type in JavaScript represents a unique and immutable value that can be used as an identifier for object properties. Symbols are especially useful in scenarios where property keys need to be unique or when you want to add metadata to objects without risking property name collisions.

Creating Symbols

Symbols are created using the Symbol() function. Each call returns a unique symbol:

const sym1 = Symbol();
const sym2 = Symbol('description');

console.log(sym1 === sym2); // false
Enter fullscreen mode Exit fullscreen mode

Using Symbols in Objects

Symbols are often used as keys for object properties, offering a form of private property:

const sym = Symbol('mySymbol');

const myObject = {
  [sym]: 'value'
};

console.log(myObject[sym]); // 'value'
Enter fullscreen mode Exit fullscreen mode

Symbols do not appear in standard property enumeration:

console.log(Object.keys(myObject)); // []
console.log(Object.getOwnPropertySymbols(myObject)); // [ Symbol(mySymbol) ]
Enter fullscreen mode Exit fullscreen mode

Well-Known Symbols

JavaScript includes well-known symbols that allow you to modify behavior of built-in operations:

  • Symbol.iterator: Define custom iteration for objects.
  • Symbol.toPrimitive: Customize type conversion.
  • Symbol.toStringTag: Change the default string description.

Example of custom iteration:

const myIterable = {
  *[Symbol.iterator]() {
    yield 1;
    yield 2;
    yield 3;
  }
};

for (const value of myIterable) {
  console.log(value); // 1, 2, 3
}
Enter fullscreen mode Exit fullscreen mode

Global Symbol Registry

Symbols can be shared using the global symbol registry with Symbol.for() and Symbol.keyFor():

const globalSym1 = Symbol.for('globalSymbol');
const globalSym2 = Symbol.for('globalSymbol');

console.log(globalSym1 === globalSym2); // true
console.log(Symbol.keyFor(globalSym1)); // 'globalSymbol'
Enter fullscreen mode Exit fullscreen mode

Conclusion

The BigInt and Symbol primitives significantly enhance JavaScript's capabilities, offering solutions for handling large integers and creating unique property keys. By understanding and leveraging these modern primitives, developers can write more robust and flexible code, avoiding potential pitfalls associated with traditional data types. Whether you're dealing with large numerical values or need unique identifiers, these features can be indispensable tools in your JavaScript toolkit.

es6 Article's
30 articles in total
Favicon
Next-Generation Buttons: Implementing the Command Pattern through Web Components
Favicon
Hoisting: facing Temporal dead zone
Favicon
Learn javascript promises. Part 1 β€” What is a promise?
Favicon
Bootcamping 02: Named exports and default exports - does it really matter?
Favicon
Mastering Modern JavaScript: A Deep Dive into ES6 Function Creation and Best Practices
Favicon
Promises: The Ability to Write Asynchronous Code Using Javascript
Favicon
Exploring JavaScript's Modern Primitives: BigInt and Symbol
Favicon
JavaScript ES6 Release Notes: Unleashing the Power of Modern JavaScript
Favicon
WHY YOU SHOULD LEARN ES6
Favicon
Understanding ES6 API's
Favicon
Transpiler vs Polyfills
Favicon
JavaScript Spread Syntax: Expanding Arrays and Objects
Favicon
API Design and Debugging:A Comprehensive Guide for BeginersπŸš€
Favicon
Understanding the JavaScript Spread Operator (With Examples)
Favicon
A Comprehensive Guide to ES6 and Arrow Functions
Favicon
Controla tus promesa con JavaScript
Favicon
Sets
Favicon
Enhanced Object Literals
Favicon
Iteration Stament i.e for-of loop
Favicon
1.1 Ins & outs of ES6(JavaScript) Import with Realworld Example and Demo Project.
Favicon
Math Namespace & BigInt
Favicon
JavaScript - Destructuring Arrays & Objects [Live Doc]
Favicon
ES2015 (ES6) Tips, Tricks, Best Practices, and Code Snippet Examples for Your Day-to-Day Workflow
Favicon
Objects in JavaScript
Favicon
Intro to DSA & Big O Notation
Favicon
Execution Context & Call Stack
Favicon
Asynchronous programming in Javascript - Callbacks, Promises & Async Await
Favicon
Loops in JavaScript !!πŸ“šπŸ”„
Favicon
Array
Favicon
Functions

Featured ones: