Math.round(); Math.max(); Math.min(); Math.abs(); Math.pow(); Math.sqrt(); Math.sign(); Math.trunc(); teach me these function with examples
Let me walk you through these essential JavaScript Math functions with practical examples.
The Math.round()
function rounds a number to the nearest integer.
// Basic rounding
console.log(Math.round(4.3)); // 4
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.7)); // 5
// Negative numbers
console.log(Math.round(-4.3)); // -4
console.log(Math.round(-4.5)); // -4 (rounds toward positive infinity)
console.log(Math.round(-4.7)); // -5
The Math.max()
function returns the largest of the provided numbers.
// Finding maximum value
console.log(Math.max(5, 10, 15)); // 15
console.log(Math.max(-5, -10, -15)); // -5
// With arrays (using spread operator)
const numbers = [5, 10, 15, 20];
console.log(Math.max(...numbers)); // 20
// If no arguments are provided
console.log(Math.max()); // -Infinity
The Math.min()
function returns the smallest of the provided numbers.
// Finding minimum value
console.log(Math.min(5, 10, 15)); // 5
console.log(Math.min(-5, -10, -15)); // -15
// With arrays (using spread operator)
const numbers = [5, 10, 15, 20];
console.log(Math.min(...numbers)); // 5
// If no arguments are provided
console.log(Math.min()); // Infinity
The Math.abs()
function returns the absolute value of a number.
// Absolute values
console.log(Math.abs(5)); // 5
console.log(Math.abs(-5)); // 5
console.log(Math.abs(-3.14)); // 3.14
// Useful for calculating differences
const point1 = 10;
const point2 = 25;
const distance = Math.abs(point1 - point2);
console.log(distance); // 15
The Math.pow()
function returns the base to the exponent power.
// Basic powers
console.log(Math.pow(2, 3)); // 8 (2³)
console.log(Math.pow(5, 2)); // 25 (5²)
console.log(Math.pow(4, 0.5)); // 2 (square root of 4)
// Negative exponents
console.log(Math.pow(2, -2)); // 0.25 (1/2²)
// Note: Modern JavaScript also offers the ** operator
console.log(2 ** 3); // 8 (same as Math.pow(2, 3))
The Math.sqrt()
function returns the square root of a number.
// Square roots
console.log(Math.sqrt(9)); // 3
console.log(Math.sqrt(2)); // 1.4142135623730951 (√2)
console.log(Math.sqrt(0)); // 0
// Negative numbers return NaN
console.log(Math.sqrt(-4)); // NaN
The Math.sign()
function returns the sign of a number, indicating whether it's positive, negative, or zero.
// Sign of numbers
console.log(Math.sign(10)); // 1 (positive)
console.log(Math.sign(-10)); // -1 (negative)
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
// Non-number values
console.log(Math.sign('10')); // 1 (converts to number first)
console.log(Math.sign('hello')); // NaN
The Math.trunc()
function returns the integer part of a number by removing any fractional digits.
// Truncating numbers
console.log(Math.trunc(13.37)); // 13
console.log(Math.trunc(42.84)); // 42
console.log(Math.trunc(0.123)); // 0
// Negative numbers
console.log(Math.trunc(-13.37)); // -13
// Difference from Math.floor() with negative numbers
console.log(Math.trunc(-4.9)); // -4
console.log(Math.floor(-4.9)); // -5
Math.round()
rounds to the nearest integer, while Math.trunc()
simply removes the decimal part.Math.floor(-4.9)
returns -5, while Math.trunc(-4.9)
returns -4.Math.pow(x, 0.5)
is equivalent to Math.sqrt(x)
- both calculate the square root.Math.abs()
returns the magnitude of a number, while Math.sign()
only tells you if it's positive (1), negative (-1), or zero (0).I've created an interactive demo above where you can try out each of these functions with your own inputs!
Array() filter(); explain me this in chat with examples
The Array.filter()
method creates a new array containing elements that pass a test implemented by the provided function. It's one of the most useful array methods for extracting specific elements from an array based on certain conditions.
const newArray = array.filter(callback(element[, index[, array]])[, thisArg])
Where:
callback
: Function to test each element of the arrayelement
: The current element being processedindex
(optional): The index of the current elementarray
(optional): The array filter() was called uponthisArg
(optional): Value to use as this
when executing callbacktrue
, the element is included in the new arrayfalse
, the element is excludedLet's filter out numbers less than 10:
const numbers = [5, 12, 8, 130, 44];
const filtered = numbers.filter(num => num >= 10);
console.log(filtered); // Output: [12, 130, 44]
Filter strings with more than 5 characters:
const fruits = ["apple", "banana", "grape", "watermelon", "kiwi"];
const longFruits = fruits.filter(fruit => fruit.length > 5);
console.log(longFruits); // Output: ["banana", "watermelon"]
Filter objects based on a property:
const products = [
{ name: "Laptop", price: 1200, inStock: true },
{ name: "Phone", price: 800, inStock: true },
{ name: "Tablet", price: 650, inStock: false },
{ name: "Headphones", price: 300, inStock: true }
];
// Get only in-stock products
const availableProducts = products.filter(product => product.inStock);
console.log(availableProducts);
// Output: [
// { name: "Laptop", price: 1200, inStock: true },
// { name: "Phone", price: 800, inStock: true },
// { name: "Headphones", price: 300, inStock: true }
// ]
// Get products with price less than 1000
const affordableProducts = products.filter(product => product.price < 1000);
console.log(affordableProducts);
// Output: [
// { name: "Phone", price: 800, inStock: true },
// { name: "Tablet", price: 650, inStock: false },
// { name: "Headphones", price: 300, inStock: true }
// ]
Filter elements based on their position:
const numbers = [10, 20, 30, 40, 50];
const evenIndexedNumbers = numbers.filter((num, index) => index % 2 === 0);
console.log(evenIndexedNumbers); // Output: [10, 30, 50]
Remove all falsy values from an array:
const mixedArray = [0, 1, false, 2, '', 3, null, undefined, NaN];
const truthyValues = mixedArray.filter(Boolean);
console.log(truthyValues); // Output: [1, 2, 3]
Create an array with unique values (before Set was widely available):
const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = numbers.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(unique); // Output: [1, 2, 3, 4, 5]
Implementing a simple search filter:
const users = [
{ name: "John Smith", age: 28 },
{ name: "Jane Doe", age: 32 },
{ name: "John Doe", age: 40 },
{ name: "Mary Smith", age: 25 }
];
function searchUsers(query) {
return users.filter(user =>
user.name.toLowerCase().includes(query.toLowerCase())
);
}
console.log(searchUsers("john"));
// Output: [
// { name: "John Smith", age: 28 },
// { name: "John Doe", age: 40 }
// ]
console.log(searchUsers("smith"));
// Output: [
// { name: "John Smith", age: 28 },
// { name: "Mary Smith", age: 25 }
// ]
You can chain filter()
with other array methods like map()
or reduce()
:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers and double them
const doubledEvens = numbers
.filter(num => num % 2 === 0)
.map(num => num * 2);
console.log(doubledEvens); // Output: [4, 8, 12, 16, 20]
// Filter numbers greater than 5 and calculate their sum
const sumOfLargeNumbers = numbers
.filter(num => num > 5)
.reduce((sum, num) => sum + num, 0);
console.log(sumOfLargeNumbers); // Output: 40 (6+7+8+9+10)
filter()
always returns a new array and doesn't modify the original array 1filter()
does not execute the callback function for empty array elementsforEach()
, you can't break out of a filter()
operationThe filter()
method is a powerful tool for working with arrays in JavaScript, allowing you to extract exactly the data you need based on specific conditions.
how the memory alocation is there if in heap then is in date varaible there will address of that heap memory