Numbers and strings
This chapter introduces the two most fundamental data types in #"#numbers">Numbers
Numbers
In JavaScript, numbers are implemented indouble-precision 64-bit binary format IEEE 754 (i.e., a number between ±2^−1022 and ±2^+1023, or about ±10^−308 to ±10^+308, with a numeric precision of 53 bits). Integer values up to ±2^53 − 1 can be represented exactly.
In addition to being able to represent floating-point numbers, the number type has three symbolic values:Infinity,-Infinity, andNaN (not-a-number).
See alsoJavaScript data types and structures for context with other primitive types in JavaScript.
You can use four types of number literals: decimal, binary, octal, and hexadecimal.
Decimal numbers
123456789042Decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading0 are smaller than 8, the number is interpreted as an octal number. This is considered a legacy syntax, and number literals prefixed with0, whether interpreted as octal or decimal, cause a syntax error instrict mode — so, use the0o prefix instead.
0888 // 888 parsed as decimal0777 // parsed as octal, 511 in decimalBinary numbers
Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" (0b or0B). If the digits after the0b are not 0 or 1, the followingSyntaxError is thrown: "Missing binary digits after 0b".
0b10000000000000000000000000000000 // 21474836480b01111111100000000000000000000000 // 21390950400B00000000011111111111111111111111 // 8388607Octal numbers
The standard syntax for octal numbers is to prefix them with0o. For example:
0O755 // 4930o644 // 420There's also a legacy syntax for octal numbers — by prefixing the octal number with a zero:0644 === 420 and"\045" === "%". If the digits after the0 are outside the range 0 through 7, the number will be interpreted as a decimal number.
const n = 0755; // 493const m = 0644; // 420Strict mode forbids this octal syntax.
Hexadecimal numbers
Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" (0x or0X). If the digits after 0x are outside the range (0123456789ABCDEF), the followingSyntaxError is thrown: "Identifier starts immediately after numeric literal".
0xFFFFFFFFFFFFF // 45035996273704950xabcdef123456 // 1889009675930460XA // 10Exponentiation
0e-5 // 00e+5 // 05e1 // 50175e-2 // 1.751e3 // 10001e-3 // 0.0011E3 // 1000Numeric separators
For all literal syntaxes shown above, an underscore (_) can be inserted between digits to improve readability.
1_000_000_000_0001_050.950b1010_0001_1000_01010o2_2_5_60xA0_B0_C01_000_000_000_000_000_000_000nSee thelexical grammar reference for more details about number literals.
Number object
The built-inNumber object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:
const biggestNum = Number.MAX_VALUE;const smallestNum = Number.MIN_VALUE;const infiniteNum = Number.POSITIVE_INFINITY;const negInfiniteNum = Number.NEGATIVE_INFINITY;const notANum = Number.NaN;You always refer to a property of the predefinedNumber object as shown above, and not as a property of aNumber object you create yourself.
The following table summarizes theNumber object's properties.
| Property | Description |
|---|---|
Number.MAX_VALUE | The largest positive representable number (1.7976931348623157e+308) |
Number.MIN_VALUE | The smallest positive representable number (5e-324) |
Number.NaN | Special "not a number" value |
Number.NEGATIVE_INFINITY | Special negative infinite value; returned on overflow |
Number.POSITIVE_INFINITY | Special positive infinite value; returned on overflow |
Number.EPSILON | Difference between1 and the smallest value greater than1 that can be represented as aNumber (2.220446049250313e-16) |
Number.MIN_SAFE_INTEGER | Minimum safe integer in JavaScript (−2^53 + 1, or−9007199254740991) |
Number.MAX_SAFE_INTEGER | Maximum safe integer in JavaScript (+2^53 − 1, or+9007199254740991) |
| Method | Description |
|---|---|
Number.parseFloat() | Parses a string argument and returns a floating point number. Same as the globalparseFloat() function. |
Number.parseInt() | Parses a string argument and returns an integer of the specified radix or base. Same as the globalparseInt() function. |
Number.isFinite() | Determines whether the passed value is a finite number. |
Number.isInteger() | Determines whether the passed value is an integer. |
Number.isNaN() | Determines whether the passed value isNaN. More robust version of the original globalisNaN(). |
Number.isSafeInteger() | Determines whether the provided value is a number that is asafe integer. |
TheNumber prototype provides methods for retrieving information fromNumber objects in various formats. The following table summarizes the methods ofNumber.prototype.
| Method | Description |
|---|---|
toExponential() | Returns a string representing the number in exponential notation. |
toFixed() | Returns a string representing the number in fixed-point notation. |
toPrecision() | Returns a string representing the number to a specified precision in fixed-point notation. |
Math object
The built-inMath object has properties and methods for mathematical constants and functions. For example, theMath object'sPI property has the value of pi (3.141…), which you would use in an application as
Math.PI;Similarly, standard mathematical functions are methods ofMath. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56);Note that all trigonometric methods ofMath take arguments in radians.
The following table summarizes theMath object's methods.
| Method | Description |
|---|---|
abs() | Absolute value |
sin(),cos(),tan() | Standard trigonometric functions; with the argument in radians. |
asin(),acos(),atan(),atan2() | Inverse trigonometric functions; return values in radians. |
sinh(),cosh(),tanh() | Hyperbolic functions; argument in hyperbolic angle. |
asinh(),acosh(),atanh() | Inverse hyperbolic functions; return values in hyperbolic angle. |
| Exponential and logarithmic functions. | |
floor(),ceil() | Returns the largest/smallest integer less/greater than or equal to an argument. |
min(),max() | Returns the minimum or maximum (respectively) value of a comma separated list of numbers as arguments. |
random() | Returns a random number between 0 and 1. |
round(),fround(),trunc(), | Rounding and truncation functions. |
sqrt(),cbrt(),hypot() | Square root, cube root, Square root of the sum of square arguments. |
sign() | The sign of a number, indicating whether the number is positive, negative or zero. |
clz32(),imul() | Number of leading zero bits in the 32-bit binary representation. The result of the C-like 32-bit multiplication of the two arguments. |
Unlike many other objects, you never create aMath object of your own. You always use the built-inMath object.
BigInts
One shortcoming of number values is they only have 64 bits. In practice, due to using IEEE 754 encoding, they cannot represent any integer larger thanNumber.MAX_SAFE_INTEGER (which is 253 - 1) accurately. To solve the need of encoding binary data and to interoperate with other languages that offer wide integers likei64 (64-bit integers) andi128 (128-bit integers), JavaScript also offers another data type to representarbitrarily large integers:BigInt.
A BigInt can be defined as an integer literal suffixed byn:
const b1 = 123n;// Can be arbitrarily large.const b2 = -1234567890987654321n;BigInts can also be constructed from number values or string values using theBigInt constructor.
const b1 = BigInt(123);// Using a string prevents loss of precision, since long number// literals don't represent what they seem like.const b2 = BigInt("-1234567890987654321");Conceptually, a BigInt is just an arbitrarily long sequence of bits which encodes an integer. You can safely do any arithmetic operations without losing precision or over-/underflowing.
const integer = 12 ** 34; // 4.9222352429520264e+36; only has limited precisionconst bigint = 12n ** 34n; // 4922235242952026704037113243122008064nCompared to numbers, BigInt values yield higher precision when representing largeintegers; however, they cannot representfloating-point numbers. For example, division would round to zero:
const bigintDiv = 5n / 2n; // 2n, because there's no 2.5 in BigIntMath functions cannot be used on BigInt values; they only work with numbers.
Choosing between BigInt and number depends on your use-case and your input's range. The precision of numbers should be able to accommodate most day-to-day tasks already, and BigInts are most suitable for handling binary data.
Read more about what you can do with BigInt values in theExpressions and Operators section, or theBigInt reference.
Strings
JavaScript'sString type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.
String literals
You can declare strings in source code using either single or double quotes:
'foo'"bar"Within a string literal, most characters can be entered literally. The only exceptions are the backslash (\, which starts an escape sequence), the quote character being used to enclose the string, which terminates the string, and the newline character, which is a syntax error if not preceded by a backslash.
More advanced strings can be created using escape sequences:
Hexadecimal escape sequences
The number after \x is interpreted as ahexadecimal number.
"\xA9" // "©"Unicode escape sequences
The Unicode escape sequences require at least four hexadecimal digits following\u.
"\u00A9" // "©"Unicode code point escapes
With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to0x10FFFF. With the four-digit Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.
See alsoString.fromCodePoint() orString.prototype.codePointAt().
"\u{2F804}"// the same with simple Unicode escapes"\uD87E\uDC04"String object
You can call methods directly on a string value:
console.log("hello".toUpperCase()); // HELLOThe following methods are available onString values:
- Query: get the character or character code at a particular string index. Methods include
at(),charAt(),charCodeAt(), andcodePointAt(). - Search: get information about a substring that conforms to a pattern, or test if a particular substring exists. Methods include
indexOf(),lastIndexOf(),startsWith(),endsWith(),includes(),match(),matchAll(), andsearch() - Composition: combine strings into a longer string. Methods include
padStart(),padEnd(),concat(), andrepeat(). - Decomposition: break a string into smaller strings. Methods include
split(),slice(),substring(),substr(),trim(),trimStart(), andtrimEnd(). - Transformation: return a new string based on the current string's content. Methods include
toLowerCase(),toUpperCase(),toLocaleLowerCase(),toLocaleUpperCase(),normalize(), andtoWellFormed().
When working with strings, there are two other objects that provide important functionality for string manipulation:RegExp andIntl. They are introduced inregular expressions andinternationalization respectively.
Template literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Template literals are enclosed by backtick (grave accent) characters (`) instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}).
Multi-lines
Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:
console.log( "string text line 1\n\string text line 2",);// "string text line 1// string text line 2"To get the same effect with multi-line strings, you can now write:
console.log(`string text line 1string text line 2`);// "string text line 1// string text line 2"Embedded expressions
In order to embed expressions within normal strings, you would use the following syntax:
const five = 5;const ten = 10;console.log( "Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".",);// "Fifteen is 15 and not 20."Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:
const five = 5;const ten = 10;console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`);// "Fifteen is 15 and not 20."For more information, read aboutTemplate literals in theJavaScript reference.
- JavaScript
- Tutorials and guides
JavaScript Guide
- Introduction
- Grammar and types
- Control flow and error handling
- Loops and iteration
- Functions
- Expressions and operators
- Numbers and strings
- Representing dates & times
- Regular expressions
- Indexed collections
- Keyed collections
- Working with objects
- Using classes
- Using promises
- JavaScript typed arrays
- Iterators and generators
- Resource management
- Internationalization
- JavaScript modules
- References
Built-in objects
- AggregateError
- Array
- ArrayBuffer
- AsyncDisposableStack
- AsyncFunction
- AsyncGenerator
- AsyncGeneratorFunction
- AsyncIterator
- Atomics
- BigInt
- BigInt64Array
- BigUint64Array
- Boolean
- DataView
- Date
- decodeURI()
- decodeURIComponent()
- DisposableStack
- encodeURI()
- encodeURIComponent()
- Error
- escape()Deprecated
- eval()
- EvalError
- FinalizationRegistry
- Float16Array
- Float32Array
- Float64Array
- Function
- Generator
- GeneratorFunction
- globalThis
- Infinity
- Int8Array
- Int16Array
- Int32Array
- InternalErrorNon-standard
- Intl
- isFinite()
- isNaN()
- Iterator
- JSON
- Map
- Math
- NaN
- Number
- Object
- parseFloat()
- parseInt()
- Promise
- Proxy
- RangeError
- ReferenceError
- Reflect
- RegExp
- Set
- SharedArrayBuffer
- String
- SuppressedError
- Symbol
- SyntaxError
- TemporalExperimental
- TypedArray
- TypeError
- Uint8Array
- Uint8ClampedArray
- Uint16Array
- Uint32Array
- undefined
- unescape()Deprecated
- URIError
- WeakMap
- WeakRef
- WeakSet
Expressions & operators
- Addition (+)
- Addition assignment (+=)
- Assignment (=)
- async function expression
- async function* expression
- await
- Bitwise AND (&)
- Bitwise AND assignment (&=)
- Bitwise NOT (~)
- Bitwise OR (|)
- Bitwise OR assignment (|=)
- Bitwise XOR (^)
- Bitwise XOR assignment (^=)
- class expression
- Comma operator (,)
- Conditional (ternary) operator
- Decrement (--)
- delete
- Destructuring
- Division (/)
- Division assignment (/=)
- Equality (==)
- Exponentiation (**)
- Exponentiation assignment (**=)
- function expression
- function* expression
- Greater than (>)
- Greater than or equal (>=)
- Grouping operator ( )
- import.meta
- import()
- in
- Increment (++)
- Inequality (!=)
- instanceof
- Left shift (<<)
- Left shift assignment (<<=)
- Less than (<)
- Less than or equal (<=)
- Logical AND (&&)
- Logical AND assignment (&&=)
- Logical NOT (!)
- Logical OR (||)
- Logical OR assignment (||=)
- Multiplication (*)
- Multiplication assignment (*=)
- new
- new.target
- null
- Nullish coalescing assignment (??=)
- Nullish coalescing operator (??)
- Object initializer
- Operator precedence
- Optional chaining (?.)
- Property accessors
- Remainder (%)
- Remainder assignment (%=)
- Right shift (>>)
- Right shift assignment (>>=)
- Spread syntax (...)
- Strict equality (===)
- Strict inequality (!==)
- Subtraction (-)
- Subtraction assignment (-=)
- super
- this
- typeof
- Unary negation (-)
- Unary plus (+)
- Unsigned right shift (>>>)
- Unsigned right shift assignment (>>>=)
- void operator
- yield
- yield*
Regular expressions
- Backreference: \1, \2
- Capturing group: (...)
- Character class escape: \d, \D, \w, \W, \s, \S
- Character class: [...], [^...]
- Character escape: \n, \u{...}
- Disjunction: |
- Input boundary assertion: ^, $
- Literal character: a, b
- Lookahead assertion: (?=...), (?!...)
- Lookbehind assertion: (?<=...), (?<!...)
- Modifier: (?ims-ims:...)
- Named backreference: \k<name>
- Named capturing group: (?<name>...)
- Non-capturing group: (?:...)
- Quantifier: *, +, ?, {n}, {n,}, {n,m}
- Unicode character class escape: \p{...}, \P{...}
- Wildcard: .
- Word boundary assertion: \b, \B
Errors
- AggregateError: No Promise in Promise.any was resolved
- Error: Permission denied to access property "x"
- InternalError: too much recursion
- RangeError: argument is not a valid code point
- RangeError: BigInt division by zero
- RangeError: BigInt negative exponent
- RangeError: form must be one of 'NFC', 'NFD', 'NFKC', or 'NFKD'
- RangeError: invalid array length
- RangeError: invalid date
- RangeError: precision is out of range
- RangeError: radix must be an integer
- RangeError: repeat count must be less than infinity
- RangeError: repeat count must be non-negative
- RangeError: x can't be converted to BigInt because it isn't an integer
- ReferenceError: "x" is not defined
- ReferenceError: assignment to undeclared variable "x"
- ReferenceError: can't access lexical declaration 'X' before initialization
- ReferenceError: must call super constructor before using 'this' in derived class constructor
- ReferenceError: super() called twice in derived class constructor
- SyntaxError: 'arguments'/'eval' can't be defined or assigned to in strict mode code
- SyntaxError: "0"-prefixed octal literals are deprecated
- SyntaxError: "use strict" not allowed in function with non-simple parameters
- SyntaxError: "x" is a reserved identifier
- SyntaxError: \ at end of pattern
- SyntaxError: a declaration in the head of a for-of loop can't have an initializer
- SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
- SyntaxError: arguments is not valid in fields
- SyntaxError: await is only valid in async functions, async generators and modules
- SyntaxError: await/yield expression can't be used in parameter
- SyntaxError: cannot use `??` unparenthesized within `||` and `&&` expressions
- SyntaxError: character class escape cannot be used in class range in regular expression
- SyntaxError: continue must be inside loop
- SyntaxError: duplicate capture group name in regular expression
- SyntaxError: duplicate formal argument x
- SyntaxError: for-in loop head declarations may not have initializers
- SyntaxError: function statement requires a name
- SyntaxError: functions cannot be labelled
- SyntaxError: getter and setter for private name #x should either be both static or non-static
- SyntaxError: getter functions must have no arguments
- SyntaxError: identifier starts immediately after numeric literal
- SyntaxError: illegal character
- SyntaxError: import declarations may only appear at top level of a module
- SyntaxError: incomplete quantifier in regular expression
- SyntaxError: invalid assignment left-hand side
- SyntaxError: invalid BigInt syntax
- SyntaxError: invalid capture group name in regular expression
- SyntaxError: invalid character in class in regular expression
- SyntaxError: invalid class set operation in regular expression
- SyntaxError: invalid decimal escape in regular expression
- SyntaxError: invalid identity escape in regular expression
- SyntaxError: invalid named capture reference in regular expression
- SyntaxError: invalid property name in regular expression
- SyntaxError: invalid range in character class
- SyntaxError: invalid regexp group
- SyntaxError: invalid regular expression flag "x"
- SyntaxError: invalid unicode escape in regular expression
- SyntaxError: JSON.parse: bad parsing
- SyntaxError: label not found
- SyntaxError: missing : after property id
- SyntaxError: missing ) after argument list
- SyntaxError: missing ) after condition
- SyntaxError: missing ] after element list
- SyntaxError: missing } after function body
- SyntaxError: missing } after property list
- SyntaxError: missing = in const declaration
- SyntaxError: missing formal parameter
- SyntaxError: missing name after . operator
- SyntaxError: missing variable name
- SyntaxError: negated character class with strings in regular expression
- SyntaxError: new keyword cannot be used with an optional chain
- SyntaxError: nothing to repeat
- SyntaxError: numbers out of order in {} quantifier.
- SyntaxError: octal escape sequences can't be used in untagged template literals or in strict mode code
- SyntaxError: parameter after rest parameter
- SyntaxError: private fields can't be deleted
- SyntaxError: property name __proto__ appears more than once in object literal
- SyntaxError: raw bracket is not allowed in regular expression with unicode flag
- SyntaxError: redeclaration of formal parameter "x"
- SyntaxError: reference to undeclared private field or method #x
- SyntaxError: rest parameter may not have a default
- SyntaxError: return not in function
- SyntaxError: setter functions must have one argument
- SyntaxError: string literal contains an unescaped line break
- SyntaxError: super() is only valid in derived class constructors
- SyntaxError: tagged template cannot be used with optional chain
- SyntaxError: Unexpected '#' used outside of class body
- SyntaxError: Unexpected token
- SyntaxError: unlabeled break must be inside loop or switch
- SyntaxError: unparenthesized unary expression can't appear on the left-hand side of '**'
- SyntaxError: use of super property/member accesses only valid within methods or eval code within methods
- SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
- TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed
- TypeError: 'x' is not iterable
- TypeError: "x" is (not) "y"
- TypeError: "x" is not a constructor
- TypeError: "x" is not a function
- TypeError: "x" is not a non-null object
- TypeError: "x" is read-only
- TypeError: already executing generator
- TypeError: BigInt value can't be serialized in JSON
- TypeError: calling a builtin X constructor without new is forbidden
- TypeError: can't access/set private field or method: object is not the right class
- TypeError: can't assign to property "x" on "y": not an object
- TypeError: can't convert BigInt to number
- TypeError: can't convert x to BigInt
- TypeError: can't define property "x": "obj" is not extensible
- TypeError: can't delete non-configurable array element
- TypeError: can't redefine non-configurable property "x"
- TypeError: can't set prototype of this object
- TypeError: can't set prototype: it would cause a prototype chain cycle
- TypeError: cannot use 'in' operator to search for 'x' in 'y'
- TypeError: class constructors must be invoked with 'new'
- TypeError: cyclic object value
- TypeError: derived class constructor returned invalid value x
- TypeError: getting private setter-only property
- TypeError: Initializing an object twice is an error with private fields/methods
- TypeError: invalid 'instanceof' operand 'x'
- TypeError: invalid Array.prototype.sort argument
- TypeError: invalid assignment to const "x"
- TypeError: Iterator/AsyncIterator constructor can't be used directly
- TypeError: matchAll/replaceAll must be called with a global RegExp
- TypeError: More arguments needed
- TypeError: null/undefined has no properties
- TypeError: property "x" is non-configurable and can't be deleted
- TypeError: Reduce of empty array with no initial value
- TypeError: setting getter-only property "x"
- TypeError: WeakSet key/WeakMap value 'x' must be an object or an unregistered symbol
- TypeError: X.prototype.y called on incompatible type
- URIError: malformed URI sequence
- Warning: -file- is being assigned a //# sourceMappingURL, but already has one
- Warning: unreachable code after return statement