What is numeric literal in JavaScript?

What is numeric literal in JavaScript?
Photo by Francesco Ungaro / Unsplash

A numeric literal in JavaScript is a direct representation of a number in the code. It is a fixed value (constant) that represents a number without requiring any computation or processing. Numeric literals can represent different types of numbers, including:

  1. Integer literals: Whole numbers without any fractional or decimal part.

Example: 42, 0, -100

  1. Floating-point literals: Numbers that have a fractional part, written with a decimal point.

Example: 3.14, 0.5, -2.718

  1. Exponential notation: A way to represent very large or very small numbers using a base and exponent (scientific notation).

Example: 1e3 (represents 1000), 2.5e-4 (represents 0.00025)

Examples of numeric literals:

  • Integer: 100
  • Negative integer: -50
  • Floating-point: 12.34
  • Exponential: 5e6 (equivalent to 5000000)

Special Cases:

  • Hexadecimal (base 16): Numbers starting with 0x represent hexadecimal values.
    • Example: 0xFF (255 in decimal)
  • Binary (base 2): Numbers starting with 0b represent binary values.
    • Example: 0b1010 (10 in decimal)
  • Octal (base 8): Numbers starting with 0o represent octal values.
    • Example: 0o77 (63 in decimal)

Numeric literals are different from number objects, which are created using the Number constructor (e.g., new Number(5)), though typically you use numeric literals in most cases for efficiency.

Is 1. numeric literal?

In JavaScript, 1. is considered a numeric literal. It represents the number 1, with the dot . indicating that the number can have a fractional part. Although 1. is equivalent to 1, the trailing dot ensures that JavaScript understands it as a floating-point number.

In this context, the dot doesn't change the value, but it allows for calling methods like toString() directly on the number. The second dot, as in 1..toString(), is used to call the method.

So, 1. is a valid numeric literal, and it's a shorthand way to write the floating-point number 1.0. You can also use 1.0 or simply 1 to represent the same value.

Hope it helps.

Support Us

Subscribe to Buka Corner

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe