In JavaScript, numbers are a primitive data type used to represent numeric values. Here are some important things to know about working with numbers in JavaScript:
- Creating Numbers
You can create a number in JavaScript simply by assigning a numeric value to a variable:
let num = 42;
- Math Operations
JavaScript supports various math operations on numbers, including addition, subtraction, multiplication, and division:
let a = 10;
let b = 5;
console.log(a + b); // Outputs: 15
console.log(a - b); // Outputs: 5
console.log(a * b); // Outputs: 50
console.log(a / b); // Outputs: 2
JavaScript also has built-in functions for performing more advanced math operations, such as exponentiation, square roots, and trigonometric functions.
- NaN
If a math operation or function in JavaScript cannot be performed, the result will be NaN
, which stands for “Not a Number”:
let num = 10 / "hello";
console.log(num); // Outputs: NaN
4.Infinity and -Infinity JavaScript also supports the concepts of positive and negative infinity, which represent values that are larger or smaller than any other number:
console.log(1 / 0); // Outputs: Infinity
console.log(-1 / 0); // Outputs: -Infinity
- Number Methods
JavaScript provides several built-in methods for working with numbers. Here are some commonly used ones:
toFixed()
: rounds a number to a specified number of decimal places and returns a string
let num = 3.14159;
console.log(num.toFixed(2)); // Outputs: "3.14"
toPrecision()
: rounds a number to a specified number of significant digits and returns a string
let num = 123.456;
console.log(num.toPrecision(4)); // Outputs: "123.5"
parseInt()
: converts a string to an integer
let numStr = "42";
console.log(parseInt(numStr)); // Outputs: 42
parseFloat()
: converts a string to a floating-point number
let numStr = "3.14";
console.log(parseFloat(numStr)); // Outputs: 3.14
Understanding how to work with numbers in JavaScript is essential for many web development tasks. By understanding basic math operations, special values like NaN and infinity, and built-in number methods, you can build powerful and accurate applications that perform complex calculations and data manipulation.