<!DOCTYPE html>
Day 8: Cracking Numbers and Math in JavaScript
<br> body {<br> font-family: sans-serif;<br> line-height: 1.6;<br> margin: 20px;<br> }</p> <div class="highlight"><pre class="highlight plaintext"><code> h1, h2, h3 { margin-top: 30px; } code { background-color: #eee; padding: 5px; font-family: monospace; } pre { background-color: #eee; padding: 10px; overflow-x: auto; font-family: monospace; } </code></pre></div> <p>
Day 8: Cracking Numbers and Math in JavaScript
Welcome to Day 8 of our JavaScript journey! Today, we'll dive into the world of numbers and mathematical operations. JavaScript provides a powerful set of tools for working with numerical data, allowing you to perform calculations, manipulate values, and build complex algorithms.
Understanding Number Types
In JavaScript, numbers are represented using the Number
data type. This type encompasses both integers (whole numbers) and floating-point numbers (numbers with decimal points). Here's a breakdown:
- Integers
Integers are whole numbers without any decimal part. Examples:
let age = 25;
let numberOfCars = 3;
Floating-point numbers represent numbers with decimal points. Examples:
let temperature = 25.5;
let price = 19.99;
Mathematical Operations
JavaScript offers a rich set of operators for performing mathematical calculations:
Operator | Description | Example |
---|---|---|
+
|
Addition |
5 + 3 = 8
|
-
|
Subtraction |
10 - 4 = 6
|
*
|
Multiplication |
2 * 6 = 12
|
/
|
Division |
15 / 3 = 5
|
%
|
Modulo (remainder) |
10 % 3 = 1
|
**
|
Exponentiation |
2 ** 3 = 8
|
Example: Calculating the Area of a Triangle
let base = 10;
let height = 5;
let area = (base * height) / 2;
console.log("The area of the triangle is:", area);
Built-in Math Objects
JavaScript provides a built-in Math
object that offers a wide range of mathematical functions:
Method | Description | Example |
---|---|---|
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.max(x, y, ...)
|
Returns the maximum value among the arguments |
Math.max(5, 10, 2) = 10
|
Math.min(x, y, ...)
|
Returns the minimum value among the arguments |
Math.min(5, 10, 2) = 2
|
Math.random()
|
Returns a random number between 0 (inclusive) and 1 (exclusive) |
Math.random() // Output: 0.54321 (random value)
|
Example: Generating Random Numbers
let randomNumber = Math.floor(Math.random() * 10) + 1; // Generate random number between 1 and 10
console.log(randomNumber);
Number Formatting
Often, you'll need to format numbers for display purposes, such as adding commas to large numbers or controlling decimal precision. JavaScript provides the Number.toLocaleString()
method for this.
Example: Formatting Currency
let price = 12345.67;
let formattedPrice = price.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
console.log(formattedPrice); // Output: $12,345.67
Number Conversion
Sometimes, you'll need to convert values between different number types. JavaScript provides the following methods:
Method | Description | Example |
---|---|---|
parseInt(str, radix)
|
Parses a string into an integer |
parseInt("10", 10) = 10
|
parseFloat(str)
|
Parses a string into a floating-point number |
parseFloat("3.14") = 3.14
|
Number(value)
|
Converts a value to a number |
Number("10") = 10
|
Number Properties
JavaScript numbers have several useful properties:
-
Number.MAX_VALUE
: Represents the largest possible number in JavaScript. -
Number.MIN_VALUE
: Represents the smallest possible positive number in JavaScript. -
Number.NaN
: Stands for "Not a Number" and represents an invalid numeric value. -
Number.POSITIVE_INFINITY
: Represents positive infinity. -
Number.NEGATIVE_INFINITY
: Represents negative infinity.
Handling Errors
When working with numbers, it's important to handle potential errors, such as division by zero or invalid number conversions. JavaScript provides the isNaN()
function to check if a value is not a number.
Example: Division by Zero
let result;
let divisor = 0;
if (divisor !== 0) {
result = 10 / divisor;
console.log(result);
} else {
console.log("Error: Cannot divide by zero!");
}
Conclusion
Understanding numbers and mathematical operations is crucial for building robust and dynamic JavaScript applications. We've explored the fundamental concepts, operators, built-in functions, and error handling techniques involved in number manipulation. By applying these concepts, you can confidently perform calculations, work with numerical data, and enhance your JavaScript skills.
Remember to continue practicing these concepts and explore the vast possibilities that JavaScript offers for working with numbers.