JavaScript provides various ways to work with numbers. Here are some common operations and use cases:
Basic Arithmetic Operations: You can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
javascriptlet a = 5; let b = 3; let sum = a + b; let difference = a - b; let product = a * b; let quotient = a / b;
Increment and Decrement: JavaScript provides shorthand notations for incrementing and decrementing variables.
javascriptlet counter = 0;
counter++; // Increment by 1
counter--; // Decrement by 1
Exponential Notation:
You can use the exponentiation operator (**
) for raising a number to a power.
javascriptlet result = 2 ** 3; // 2 raised to the power of 3 (2^3)
Modulus Operator:
The modulus operator (%
) returns the remainder of a division operation.
javascriptlet remainder = 10 % 3; // Result: 1 (remainder of 10 divided by 3)
Math Object:
JavaScript provides a Math
object with many built-in methods for more advanced mathematical operations.
javascriptlet x = Math.sqrt(25); // Square root
let y = Math.random(); // Random number between 0 and 1
let z = Math.floor(3.14); // Round down to the nearest integer
Conversion:
You can convert strings to numbers using parseInt()
or parseFloat()
.
javascriptlet numString = "42";
let num = parseInt(numString); // Converts to integer
Number Methods:
Numbers in JavaScript are primitive values, but you can use methods on number literals by converting them to objects using the Number
constructor.
javascriptlet num = 123;
let numObject = new Number(num);
let decimalString = numObject.toFixed(2); // Rounds to 2 decimal places
NaN (Not a Number):
You can use isNaN()
to check if a value is not a number.
javascriptlet value = "Hello";
let isNotANumber = isNaN(value); // true
These are just a few examples of how you can use numbers in JavaScript. Depending on your specific needs, you may encounter various other scenarios where numbers play a crucial role.