Skip to main content

Command Palette

Search for a command to run...

๐Ÿงฎ JavaScript's Math Object & If Statements! ๐Ÿš€

Published
โ€ข7 min readโ€ขView as Markdown
๐Ÿงฎ JavaScript's Math Object & If Statements! ๐Ÿš€

๐Ÿงฎ Math Object in JavaScript is Useful

  1. ๐Ÿ’ก Introduction to the Math Object

๐Ÿš€ Description: The Math object in JavaScript is a built-in tool providing handy properties and methods for mathematical operations.

// Common properties of Math object
console.log(Math.PI); // 3.141592653589793
console.log(Math.E);  // 2.718281828459045

๐Ÿ“˜ Explanation: Constants like Math.PI (ฯ€) and Math.E (Eulerโ€™s number) make math tasks a breeze.


  1. ๐Ÿ”ข Rounding Numbers
let x = 3.21;
console.log(Math.round(x));  // 3
console.log(Math.floor(x));  // 3
console.log(Math.ceil(x));   // 4
console.log(Math.trunc(x));  // 3

๐Ÿ“Š Explanation:

  • Math.round(): Nearest integer.

  • Math.floor(): Always rounds down.

  • Math.ceil(): Always rounds up.

  • Math.trunc(): Removes decimal part.


  1. ๐Ÿš€ Power & Roots
let x = 3;
let y = 2;
console.log(Math.pow(x, y));   // 9
console.log(Math.sqrt(81));    // 9

๐Ÿง  Explanation:

  • Math.pow(base, exponent): Raises a number to a power.

  • Math.sqrt(): Computes the square root.


  1. ๐Ÿ“ˆ Logarithms
let x = 10;
console.log(Math.log(x)); // โ‰ˆ 2.302585

๐Ÿ’ก Explanation:

  • Math.log(): Returns the natural logarithm (base e) of a number.

  1. ๐Ÿ“ Trigonometric Functions
let x = Math.PI / 4; // 45 degrees in radians
console.log(Math.sin(x));  // โ‰ˆ 0.707
console.log(Math.cos(x));  // โ‰ˆ 0.707
console.log(Math.tan(x));  // โ‰ˆ 1.0

๐Ÿ“ Explanation:

  • Math.sin(): Sine of an angle.

  • Math.cos(): Cosine of an angle.

  • Math.tan(): Tangent of an angle.


  1. ๐Ÿ”€ Absolute Value & Sign
let x = -3.21;
console.log(Math.abs(x));  // 3.21
console.log(Math.sign(x)); // -1

๐Ÿ“ Explanation:

  • Math.abs(): Absolute value, removing the negative sign.

  • Math.sign(): Indicates if a number is positive, negative, or zero.


  1. ๐Ÿ† Finding Max & Min Values
let x = 3, y = 2, z = 1;
console.log(Math.max(x, y, z)); // 3
console.log(Math.min(x, y, z)); // 1

๐Ÿ“Š Explanation:

  • Math.max(): Returns the largest value.

  • Math.min(): Returns the smallest value.


๐Ÿค” If Statements in JavaScript

  1. ๐Ÿ’ก Basic if Statement

๐Ÿš€ Description: An if statement checks a condition. If true, it runs the code; if false, it skips.

let age = 25;

if (age >= 18) {
    console.log("You are old enough to enter this site");
}

๐Ÿ“˜ Explanation:

  • Condition: If age >= 18, the message is printed.

  • If false, nothing happens.


  1. โ†”๏ธ if-else Statement

๐Ÿš€ Description: The else block runs if the if condition is false.

let age = 13;

if (age >= 18) {
    console.log("You are old enough to enter this site");
} else {
    console.log("You must be 18+ to enter this site");
}

๐Ÿ“˜ Explanation:

  • Condition: If age >= 18, print the first message.

  • Else: If not, print the second message.


  1. โž• else if Statement

๐Ÿš€ Description: Check multiple conditions with else if.

let age = 0;

if (age >= 100) {
    console.log("You are TOO OLD to enter this site");
} else if (age == 0) {
    console.log("You can't enter. You were just born.");
} else if (age >= 18) {
    console.log("You are old enough to enter this site");
} else if (age < 0) {
    console.log("Your age can't be below 0");
} else {
    console.log("You must be 18+ to enter this site");
}

๐Ÿ“˜ Explanation:

  • Conditions: Each else if checks more conditions.

  • Execution: First true conditionโ€™s block runs.


  1. โœ… Using if with Booleans

๐Ÿš€ Description: Boolean variables (true or false) can be directly used in if conditions.

let isStudent = false;

if (isStudent) {
    console.log("You are a student");
} else {
    console.log("You are not a student");
}

๐Ÿ“˜ Explanation:

  • isStudent directly controls which block runs.

  1. ๐Ÿ”„ Nested if Statements

๐Ÿš€ Description: Nest if statements inside each other for more complex logic.

let age = 18;
let hasLicense = true;

if (age >= 16) {
    console.log("You are old enough to drive");
    if (hasLicense) {
        console.log("You have your license");
    } else {
        console.log("You do not have your license yet");
    }
} else {
    console.log("You must be 16+ to have a license");
}

๐Ÿ“˜ Explanation:

  • Nested Conditions: First, checks age, then checks hasLicense.

  1. ๐Ÿ”„ Comparison Operators

๐Ÿš€ Description: Use operators like == to compare values.

let age = 0;

if (age == 0) {
    console.log("You can't enter. You were just born.");
}

๐Ÿ“˜ Explanation:

  • Comparison: age == 0 checks if the value is exactly equal to 0.

  1. ๐Ÿ“‹ Handling HTML Form Data

๐Ÿš€ Description: Use if statements with user input from HTML forms.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My website</title>
</head>
<body>
    <label>Enter your age:</label><br>
    <input type="text" id="myText"><br>
    <button type="submit" id="mySubmit">Submit</button>
    <p id="resultElement"></p>

    <script>
    const myText = document.getElementById("myText");
    const mySubmit = document.getElementById("mySubmit");
    const resultElement = document.getElementById("resultElement");

    mySubmit.onclick = function() {
        let age = Number(myText.value);

        if (age >= 100) {
            resultElement.textContent = "You are TOO OLD to enter this site";
        } else if (age == 0) {
            resultElement.textContent = "You can't enter. You were just born.";
        } else if (age >= 18) {
            resultElement.textContent = "You are old enough to enter this site";
        } else if (age < 0) {
            resultElement.textContent = "Your age can't be below 0";
        } else {
            resultElement.textContent = "You must be 18+ to enter this site";
        }
    }
    </script>
</body>
</html>

๐Ÿ“˜ Explanation:

  • Form Interaction: Takes user input, processes it, and displays a message based on conditions.

โœ… Checked Property in JavaScript

  1. ๐Ÿ’ก Basic Usage of checked

๐Ÿš€ Description: The checked property helps you find whether a checkbox or radio button is selected (true) or not (false).

<input type="checkbox" id="myCheckbox">
<button onclick="checkStatus()">Check Status</button>

<script>
function checkStatus() {
    let isChecked = document.getElementById("myCheckbox").checked;
    if (isChecked) {
        console.log("Checkbox is checked");
    } else {
        console.log("Checkbox is NOT checked");
    }
}
</script>

๐Ÿ“˜ Explanation:

  • checked property: Returns true if the checkbox is selected, false otherwise.

  1. ๐Ÿ”„ Dynamically Changing Checked State

๐Ÿš€ Description: You can change the checked property dynamically with JavaScript.

<input type="checkbox" id="myCheckbox">
<button onclick="toggleCheckbox()">Toggle Checkbox</button>

<script>
function toggleCheckbox() {
    let checkbox = document.getElementById("myCheckbox");
    checkbox.checked = !checkbox.checked;
}
</script>

๐Ÿ“˜ Explanation:

  • Toggle Logic: The code flips the checked state each time the button is clicked.

  1. ๐Ÿ“ Handling Form Data with Checked Property

๐Ÿš€ Description: Use the checked property to handle form submission data based on whether checkboxes or radio buttons are selected.

<form id="myForm">
    <input type="checkbox" id="subscribe"> Subscribe to Newsletter <br>
    <button type="button" onclick="submitForm()">Submit</button>
</form>

<script>
function submitForm() {
    let subscribe = document.getElementById("subscribe").checked;
    if (subscribe) {
        console.log("Form submitted with subscription");
    } else {
        console.log("Form submitted without subscription");
    }
}
</script>

๐Ÿ“˜ Explanation:

  • Form Interaction: The form processes the subscription status based on whether the checkbox is selected or not.

  1. ๐Ÿ”„ Using checked with Radio Buttons

๐Ÿš€ Description: Radio buttons also utilize the checked property for selecting options.

<form>
    <input type="radio" name="gender" value="male" id="male"> Male <br>
    <input type="radio" name="gender" value="female" id="female"> Female <br>
    <button type="button" onclick="checkRadio()">Submit</button>
</form>

<script>
function checkRadio() {
    let isMale = document.getElementById("male").checked;
    let isFemale = document.getElementById("female").checked;

    if (isMale) {
        console.log("Selected gender: Male");
    } else if (isFemale) {
        console.log("Selected gender: Female");
    } else {
        console.log("No gender selected");
    }
}
</script>

๐Ÿ“˜ Explanation:

  • Radio Buttons: Only one button can be selected, and checked will return true for that button.

  1. ๐Ÿ‘๏ธ Visual Feedback for User Selections

๐Ÿš€ Description: Provide immediate visual feedback based on the checked property.

<input type="checkbox" id="showMessage"> Show Message <br>
<p id="message" style="display: none;">Hello! You checked the box.</p>
<button onclick="toggleMessage()">Toggle Message</button>

<script>
function toggleMessage() {
    let checkbox = document.getElementById("showMessage");
    let message = document.getElementById("message");

    if (checkbox.checked) {
        message.style.display = "block";
    } else {
        message.style.display = "none";
    }
}
</script>

๐Ÿ“˜ Explanation:

  • Dynamic Visibility: The paragraph is shown or hidden based on whether the checkbox is checked.

  1. ๐Ÿ“‹ Managing Multiple Checkboxes

๐Ÿš€ Description: Work with multiple checkboxes, like a "Select All" feature.

<input type="checkbox" id="selectAll" onclick="selectAllCheckboxes(this)"> Select All <br>
<input type="checkbox" class="option"> Option 1 <br>
<input type="checkbox" class="option"> Option 2 <br>
<input type="checkbox" class="option"> Option 3 <br>

<script>
function selectAllCheckboxes(selectAll) {
    let checkboxes = document.getElementsByClassName("option");
    for (let checkbox of checkboxes) {
        checkbox.checked = selectAll.checked;
    }
}
</script>

๐Ÿ“˜ Explanation:

  • Select All Logic: When "Select All" is clicked, it checks/unchecks all other options.

More from this blog

Learning In Public

7 posts