You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
const bigintFromNumber = BigInt(10); //same as 10n
const bigintFromNumber = BigInt(10); //lo mismo que 10n
```
##Math operators
##Operadores matemáticos
`BigInt`can mostly be used like a regular number, for example:
`BigInt`puede ser usado mayormente como un número regular, por ejemplo:
```js run
alert(1n + 2n); // 3
alert(5n / 2n); // 2
```
Please note: the division `5/2`returns the result rounded towards zero, without the decimal part. All operations onbigintsreturn bigints.
Por favor, ten en cuenta: la división `5/2`devuelve el resultado redondeado a cero, sin la parte decimal. Todas las operaciones sobrebigintsdevuelven bigints.
We can't mix bigintsand regular numbers:
No podemos mezclar bigintscon números regulares:
```js run
alert(1n + 2); // Error:Cannot mixBigIntand other types
alert(1n + 2); // Error:No se puede mezclarBigInty otros tipos.
```
We should explicitly convert them if needed: using either`BigInt()`or `Number()`, like this:
Podemos convertirlos explícitamente cuando es necesario: usando`BigInt()`o `Number()` como aquí:
```js run
let bigint = 1n;
let number = 2;
// numberto bigint
//Denumbera bigint
alert(bigint + BigInt(number)); // 3
// bigintto number
//Debiginta number
alert(Number(bigint) + number); // 3
```
The conversion operations are always silent, never give errors, but if the bigintis too huge and won't fit the number type, then extrabitswill be cut off, so we should be careful doing such conversion.
Las operaciones de conversión siempre son silenciosas, nunca dan error, pero si el bigintes tan gigante que no podrá ajustarse al tipo numérico, losbitsextra serán recortados, entonces deberíamos ser cuidadosos al hacer tal conversión.
````smart header="The unary plus is not supported on bigints"
The unary plus operator `+value`is a well-known way to convert`value` to a number.
````smart header="El unario más no tiene soporte en bigints"
El operador unario más `+value`es una manera bien conocida de convertir`value` a number.
On bigints it's not supported, to avoid confusion:
Para evitar las confusiones, con bigints eso no es soportado:
```js run
let bigint = 1n;
alert( +bigint ); // error
```
So we should use`Number()`to convert a bigint to a number.
Entonces debemos usar`Number()`para convertir un bigint a number.
````
##Comparisons
##Comparaciones
Comparisons, such as `<`, `>`work withbigintsand numbers just fine:
Comparaciones tales como `<`, `>`funcionan bien entrebigintsy numbers:
```js run
alert( 2n > 1n ); // true
alert( 2n > 1 ); // true
```
Please note though, as numbers and bigints belong to different types, they can be equal `==`,but not strictly equal `===`:
Por favor, nota que como number y bigint pertenecen a diferentes tipos, ellos pueden ser iguales `==`,pero no estrictamente iguales `===`:
```js run
alert( 1 == 1n ); // true
alert( 1 === 1n ); // false
```
##Boolean operations
##Operaciones booleanas
When inside`if`or other boolean operations,bigintsbehave like numbers.
Cuando estan dentro de un`if`u otra operación booleana, losbigintsse comportan como numbers.
For instance, in `if`, bigint `0n`is falsy, other values are truthy:
Por ejemplo, en `if`,elbigint `0n`es falso, los otros valores son verdaderos:
```js run
if (0n) {
//never executes
//nunca se ejecuta
}
```
Boolean operators, such as `||`, `&&`and others also work with bigints similarto numbers:
Los operadores booleanos, tales como `||`, `&&`y otros, también trabajan con bigintsen formasimilara los number:
```js run
alert( 1n || 2 ); // 1 (1nis considered truthy)
alert( 1n || 2 ); // 1 (1nes considerado verdadero)
alert( 0n || 2 ); // 2 (0nis considered falsy)
alert( 0n || 2 ); // 2 (0nes considerado falso)
```
## Polyfills
Polyfillingbigintsis tricky. The reason is that manyJavaScriptoperators, such as`+`, `-`and so on behave differently with bigints compared to regular numbers.
Hacer Polyfill conbigintses trabajoso. La razón es que muchos operadoresJavaScriptcomo`+`, `-`y otros se comportan de diferente manera comparados con los números regulares.
For example, division ofbigintsalways returns a bigint (rounded if necessary).
Por ejemplo, la división debigintssiempre devuelve un bigint (redondeado cuando es necesario).
To emulate such behavior, a polyfillwould need to analyze the code and replace all such operators with its functions. But doing so is cumbersome and would cost a lot of performance.
Para emular tal comportamiento, un polyfillnecesitaría analizar el código y reemplazar todos los operadores con sus funciones. Pero hacerlo es engorroso y tendría mucho costo en performance.
So, there'snowell-known good polyfill.
Por lo quenose conoce un buen polyfill.
Although, the other way around is proposed by the developers of[JSBI](https://github.com/GoogleChromeLabs/jsbi) library.
Aunque hay otra manera, la propuesta por los desarrolladores de la librería[JSBI](https://github.com/GoogleChromeLabs/jsbi).
This library implements big numbers using its own methods. We can use them instead of nativebigints:
Esta librería implementa bigint usando sus propios métodos. Podemos usarlos en lugar debigints nativos:
|Operation |native`BigInt` | JSBI |
|Operación | `BigInt` nativo | JSBI |
|-----------|-----------------|------|
|Creation from Number | `a = BigInt(789)` | `a = JSBI.BigInt(789)` |
|Creación desde Number | `a = BigInt(789)` | `a = JSBI.BigInt(789)` |
|Suma | `c = a + b` | `c = JSBI.add(a, b)` |
|Resta| `c = a - b` | `c = JSBI.subtract(a, b)` |
| ... | ... | ... |
...And then use thepolyfill (Babelplugin) to convert JSBI calls to nativebigintsfor those browsers that support them.
...Y entonces usarpolyfill (plugin Babel) para convertir las llamadas de JSBI enbigintsnativos para aquellos navegadores que los soporten.
In other words, this approach suggests that we write code inJSBIinstead of native bigints. But JSBIworks withnumbersas with bigints internally, emulates them closely following the specification, so the code will be"bigint-ready".
En otras palabras, este enfoque sugiere que escribamos código enJSBIen lugar de bigints nativos. Pero JSBItrabaja internamente tanto connumberscomo con bigints, los emula siguiendo de cerca la especificación, entonces el código será"bigint-ready" (preparado para bigint).
We can use such JSBIcode "as is" for engines that don't support bigints and for those that do support - the polyfillwill convert the calls to nativebigints.
Podemos usar tal código JSBI"tal como está" en motores que no soportan bigints, y para aquellos que sí lo soportan - el polyfillconvertirá las llamadas enbigints nativos.
##References
##Referencias
- [MDNdocs on BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt).
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.