A JavaScript Developer Must know these Number & Maths Methods

A JavaScript Developer Must know these Number & Maths Methods

Number in JavaScript

When learning or working with JavaScript, familiarity with number-related methods and mathematical operations proves invaluable. This article will explore key methods in this domain.

To define a Number the most simple syntax is

const score = 400
console.log(score);

In this part of the code:

  • const score: Declares a constant variable named score.

  • = 400: Assigns the value 400 to the score variable.

  • console.log(score): Prints the value of the score to the console. In this case, it will print 400.

So, score is a primitive data type (number) and is assigned a literal value of 400.

const balance = new Number(100)
console.log(balance);

In this part of the code:

  • const balance: Declares a constant variable named balance.

  • new Number(100): Creates a new Number object with an initial value of 100 and assigns it to the balance variable.

  • console.log(balance): Prints the value of balance to the console. In this case, it will print the Number object, not just the primitive value.

Now, let's understand the difference between the two codes:

  1. Primitive vs. Object:

    • In Code 1, score is a primitive number type. Primitives are immutable and passed by value.

    • In Code 2, balance is an instance of the Number object created using the new keyword. Objects are mutable and passed by reference.

  2. Value Representation:

    • When you log score, it directly prints the primitive value 400.

    • When you log balance, it prints the entire Number object, which might look like: [Number: 100].

  3. Usage:

    • Primitives (like score) are generally used for simple values and operations.

    • Objects (like balance) are used when you need to work with methods and properties associated with the data type, or if you need to pass around mutable references.

Methods that we get with Numbers

In JavaScript, a "Number" is a basic thing for handling numbers. It can be a regular number, like 42, or a special "Number" object. Here are some tricks (methods) you can do with numbers:

  1. Turning Numbers into Text:

    • .toString(): Imagine you have the number 42, and you want to treat it like words. This method makes it "42" in text form.

    •         const num = 42;
              const strNum = num.toString(); // Result: "42"
      
  2. Controlling Decimals:

    • .toFixed(digits): If you have a number like 3.14159 and you only want two digits after the dot, this trick turns it into "3.14".

    •         const num = 3.14159;
              const formattedNum = num.toFixed(2); // Result: "3.14"
      
  3. Scientific Notation:

    • .toExponential(digits): For really big or really small numbers, like 12345, this trick makes it look like "1.23e+4".

    •         const num = 12345;
              const expNum = num.toExponential(2); // Result: "1.23e+4"
      
  4. Fancy Precision:

    • .toPrecision(digits): If you want control over how many significant digits (important numbers) to show, this helps. For example, "12345.6789" could become "12345.7". And returns value in string format.

    •         const otherNumber = 12345.6789;
              console.log(num.toPrecision(6)); // Result: "12345.7"
      
              const otherNumber = 123.8966;
              console.log(otherNumber.toPrecision(3)); //Result: 124
      
              const otherNumber = 1123.8966;
              console.log(otherNumber.toPrecision(3)); //Result: 1.12e+3
      
  5. Getting the Basic Number Back:

    • .valueOf(): If you've been playing with a special "Number" object, this gets you back to the simple number. If you had new Number(42), this gets you just 42.

    •         const numObj = new Number(42);
              const primitiveValue = numObj.valueOf(); // Result: 42
      
  6. Checking If It's Not a Number (NaN):

    • isNaN(): Checks if a value is NaN (Not a Number).

    •         isNaN(42);     // Result: false
              isNaN("foo");  // Result: true
      
  7. Checking If It's a Real Number:

    • isFinite(): If you want to know if a number isn't something weird like infinity (too big) or not a number at all, this helps.

    •         isFinite(42);     // Result: true
              isFinite(Infinity);  // Result: false
      
  8. Reading Numbers From Text:

    • parseInt("42") and parseFloat("3.14"): If you have numbers hiding in text, these tricks can find them and turn them into real numbers.

    •         parseInt("42");      // Result: 42
              parseFloat("3.14");  // Result: 3.14
      
  9. Representing Numbers in Some Country-Specific Systems

    • toLocalString(): Returns a string with a language-sensitive representation of the number.
    const hundreds = 1000000;
    console.log(hundreds.toLocaleString("en-IN")); //Result: 10,00,000
    console.log(hundreds.toLocaleString("en-US")); //Result: 1,000,000

Maths in JavaScript

In JavaScript, the Math object provides a set of properties and methods for performing mathematical operations.

Mathematical Constants:

console.log(Math.PI);          // Pi (π)
console.log(Math.E);           // Euler's number (e)

Basic Mathematical Operations:

javascriptCopy codeconsole.log(Math.abs(-5));     // Absolute value
console.log(Math.round(4.7));   // Round to the nearest integer
console.log(Math.floor(4.7));   // Round down to the nearest integer
console.log(Math.ceil(4.2));    // Round up to the nearest integer
console.log(Math.max(1, 2, 3)); // Maximum of a list of values
console.log(Math.min(1, 2, 3)); // Minimum of a list of values

Exponential and Logarithmic Functions:

javascriptCopy codeconsole.log(Math.pow(2, 3));    // Exponentiation: 2^3
console.log(Math.sqrt(9));      // Square root: √9
console.log(Math.exp(2));       // Exponential function: e^2
console.log(Math.log(8));       // Natural logarithm: loge(8)
console.log(Math.log10(100));   // Base-10 logarithm: log10(100)

Trigonometric Functions:

javascriptCopy codeconsole.log(Math.sin(Math.PI / 2));   // Sine of π/2
console.log(Math.cos(Math.PI));       // Cosine of π
console.log(Math.tan(Math.PI / 4));   // Tangent of π/4
console.log(Math.asin(1));            // Arcsine, returns radians
console.log(Math.acos(0));            // Arccosine, returns radians
console.log(Math.atan(1));            // Arctangent, returns radians

Random Number Generation:

javascriptCopy codeconsole.log(Math.random());         // Random number between 0 (inclusive) and 1 (exclusive)
console.log(Math.floor(Math.random() * 10) + 1);  // Random integer between 1 and 10

What if we want a random number between minimum and maximum value

const min = 10
const max = 20

console.log(Math.floor(Math.random() * (max - min + 1)) + min) //Result Any random numver between 10 and 20

Degrees to Radians and Radians to Degrees:

javascriptCopy codeconst degrees = 45;
const radians = (degrees * Math.PI) / 180;
console.log(radians);  // Conversion from degrees to radians

const radiansValue = Math.PI / 4;
const degreesValue = (radiansValue * 180) / Math.PI;
console.log(degreesValue);  // Conversion from radians to degrees

Did you find this article valuable?

Support Subham Kumar by becoming a sponsor. Any amount is appreciated!