Day 8: Cracking Numbers and Math in JavaScript

WHAT TO KNOW - Sep 7 - - Dev Community

<!DOCTYPE html>





Day 8: Cracking Numbers and Math in JavaScript

<br> body {<br> font-family: sans-serif;<br> }<br> h1, h2, h3 {<br> margin-top: 2em;<br> }<br> pre {<br> background-color: #f0f0f0;<br> padding: 1em;<br> border-radius: 5px;<br> overflow-x: auto;<br> }<br> code {<br> font-family: monospace;<br> }<br>



Day 8: Cracking Numbers and Math in JavaScript



Welcome back to our JavaScript journey! Today, we dive into the realm of numbers and mathematical operations, a fundamental aspect of programming that allows us to work with data, solve problems, and build interactive applications. This exploration will equip you with the tools to manipulate numeric values and perform various calculations within your JavaScript programs.



Understanding Numbers in JavaScript



JavaScript represents numbers using the Number data type. This type encompasses both integers (whole numbers) and floating-point numbers (numbers with decimal points). Let's take a look at some examples:




let wholeNumber = 10; // Integer
let decimalNumber = 3.14; // Floating-point number



Number Literals



JavaScript provides various ways to represent numbers in your code, known as number literals:



  • Decimal Notation:
    The most common way, representing numbers as we usually write them (e.g., 10, 3.14).

  • Exponential Notation (Scientific Notation):
    Used for representing very large or very small numbers (e.g., 1e6 for 1,000,000, 1e-3 for 0.001).

  • Octal Notation:
    Represents numbers in base 8, prefixed with a zero (e.g., 010 for decimal 8).

  • Hexadecimal Notation:
    Represents numbers in base 16, prefixed with 0x (e.g., 0x10 for decimal 16).


Basic Mathematical Operations



JavaScript provides a set of operators for performing basic mathematical calculations:


















































Operator

Description

Example

Result

+

Addition


5 + 3



8


-

Subtraction


10 - 4



6


*

Multiplication


2 * 6



12


/

Division


15 / 3



5


%

Modulo (remainder)


13 % 5



3


**

Exponentiation


2 ** 3



8



Example: Calculating Area of a Circle




const radius = 5;
const area = Math.PI * radius ** 2;
console.log("Area of the circle:", area); // Output: Area of the circle: 78.53981633974483



Beyond the Basics: Math Object



JavaScript's built-in Math object offers a treasure trove of mathematical functions for advanced operations:
















































































Method

Description

Example

Result


Math.abs(x)


Returns the absolute value of

x

.


Math.abs(-5)



5



Math.ceil(x)


Rounds

x

up to the nearest integer.


Math.ceil(3.14)



4



Math.floor(x)


Rounds

x

down to the nearest integer.


Math.floor(3.14)



3



Math.round(x)


Rounds

x

to the nearest integer.


Math.round(3.5)



4



Math.sqrt(x)


Returns the square root of

x

.


Math.sqrt(16)



4



Math.pow(x, y)


Returns

x

raised to the power of

y

.


Math.pow(2, 3)



8



Math.min(x, y, ...)


Returns the smallest value from the arguments.


Math.min(5, 2, 8, 1)



1



Math.max(x, y, ...)


Returns the largest value from the arguments.


Math.max(5, 2, 8, 1)



8



Math.random()


Generates a random number between 0 (inclusive) and 1 (exclusive).


Math.random()



0.3456789...

(random value)


Math.PI


The mathematical constant pi (approximately 3.14159).


console.log(Math.PI);



3.141592653589793



Math.E


The mathematical constant e (Euler's number, approximately 2.71828).


console.log(Math.E);



2.718281828459045



Example: Generating Random Numbers within a Range




function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

const randomNumber = getRandomNumber(1, 10); // Generates a random number between 1 and 10 (inclusive)
console.log(randomNumber);




Working with Dates and Times



JavaScript provides the Date object for handling dates and times. Let's explore some key methods:



  • Date() Constructor:
    Creates a new Date object. You can use it with arguments to specify a specific date and time, or without arguments to represent the current date and time.

  • getDate()
    : Returns the day of the month (1-31).

  • getMonth()
    : Returns the month (0-11). Remember, January is 0, February is 1, and so on.

  • getFullYear()
    : Returns the four-digit year.

  • getHours()
    : Returns the hour (0-23).

  • getMinutes()
    : Returns the minutes (0-59).

  • getSeconds()
    : Returns the seconds (0-59).


Example: Displaying Current Date and Time




const now = new Date();

console.log("Current date and time:");
console.log("Year:", now.getFullYear());
console.log("Month:", now.getMonth() + 1); // Remember to add 1 to get the actual month
console.log("Day:", now.getDate());
console.log("Hour:", now.getHours());
console.log("Minutes:", now.getMinutes());
console.log("Seconds:", now.getSeconds());




Error Handling and Number Validation



Working with numbers often involves potential errors, like dividing by zero or trying to parse invalid input. JavaScript provides mechanisms to handle these situations:


  1. isNaN() Function

The isNaN() function checks if a value is Not a Number. It returns true if the value is not a number and false otherwise.


console.log(isNaN("hello")); // true
console.log(isNaN(10)); // false

  • isFinite() Function

    The isFinite() function determines if a value is a finite number. It returns true if the value is finite (not NaN, Infinity, or -Infinity) and false otherwise.

    
    console.log(isFinite(10)); // true
    console.log(isFinite(Infinity)); // false
    
    


  • parseInt() and parseFloat() Functions

    These functions are used to convert strings to numbers. parseInt() converts a string to an integer, while parseFloat() converts a string to a floating-point number.

    
    console.log(parseInt("10")); // 10
    console.log(parseInt("10.5")); // 10
    console.log(parseFloat("10.5")); // 10.5
    
    

    Best Practices for Working with Numbers

    • Use Type Coercion Carefully: JavaScript automatically converts data types in certain situations, but it's best to be explicit with type conversions to avoid unexpected behavior.
    • Handle Errors Gracefully: Implement error handling mechanisms, like isNaN() and isFinite(), to catch invalid or unexpected input.
    • Use Number Methods for Precision: Employ methods like toFixed() for controlling the number of decimal places when displaying or working with floating-point numbers.
    • Choose Appropriate Data Types: When working with large numbers, consider using the BigInt data type, which can represent integers beyond the limits of the standard Number type.
    • Document Your Code: Add comments to clarify your calculations and how you're handling numbers within your code.

    Conclusion

    Today, we've explored the foundation of numbers and mathematical operations in JavaScript. You've learned about number literals, basic operators, and the power of the Math object for advanced calculations. You can now use these tools to manipulate numeric data, perform calculations, generate random numbers, and work with dates and times in your JavaScript programs. Remember to be mindful of potential errors and to implement best practices for handling numbers effectively.

  • . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    Terabox Video Player