Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 30 - JavaScript Math Object

The JavaScript Math object allows you to perform mathematical operations. It provides properties and methods for constants, rounding, random number generation, and more.


Explanation

  • The Math object is a built-in object with static properties and methods.
  • It includes constants like Math.PI and functions like Math.round().

Example 1: Math Constants & Rounding

console.log("PI:", Math.PI); // 3.141592653589793

console.log("Round 4.7:", Math.round(4.7)); // 5
console.log("Floor 4.7:", Math.floor(4.7)); // 4
console.log("Ceil 4.1:", Math.ceil(4.1)); // 5
  • Uses constants and rounding methods.

Example 2: Random Numbers & Min/Max

let randomNum = Math.random(); // Random between 0 and 1
console.log("Random Number:", randomNum);

let scaledRandom = Math.floor(Math.random() * 100); // Between 0 and 99
console.log("Scaled Random:", scaledRandom);

console.log("Max of [4, 9, 2]:", Math.max(4, 9, 2)); // 9
console.log("Min of [4, 9, 2]:", Math.min(4, 9, 2)); // 2
  • Demonstrates random number generation and finding min/max values.

Example 3: Math Functions

console.log("Square Root of 16:", Math.sqrt(16)); // 4
console.log("2 to the Power of 3:", Math.pow(2, 3)); // 8
console.log("Absolute of -7:", Math.abs(-7)); // 7
  • Uses mathematical functions for square root, power, and absolute values.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson30-math.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Lesson 31 - Math Object</title>
      </head>
      <body>
      <h2>Random Number Generator</h2>
      <button onclick="generateRandom()">Generate Random Number</button>
      <p id="randomNum"></p>
      
      <script>
         function generateRandom() {
             let random = Math.floor(Math.random() * 100) + 1;
             document.getElementById("randomNum").innerText = "Random Number: " + random;
         }
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open it in a Browser to See the Output.


Experiment

  1. Create a dice roller that generates random numbers between 1 and 6.
  2. Build a simple calculator that uses Math.pow() and Math.sqrt().
  3. Display the value of Pi up to 5 decimal places.

Key Takeaways

  • Math object provides mathematical constants and functions.
  • Use Math.random() for random number generation.
  • Math.round(), Math.ceil(), and Math.floor() help with rounding.