What are different ways to create pure functions in JavaScript. Give examples.
Answer: In JavaScript, pure functions are functions that, given the same input, will always return the same output and have no side effects. Creating pure functions ensures predictability and reliability in code. Here are different ways to create pure functions with examples:Pure functions often perform simple mathematical operations.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // Output: 5
console.log(add(2, 3)); // Output: 5
Pure functions can also handle string manipulations.
function toUpperCase(str) {
return str.toUpperCase();
}
console.log(toUpperCase('hello')); // Output: HELLO
console.log(toUpperCase('hello')); // Output: HELLO
Pure functions can be used to transform arrays without modifying the original array.
function doubleArray(arr) {
return arr.map(num => num * 2);
}
const numbers = [1, 2, 3];
console.log(doubleArray(numbers)); // Output: [2, 4, 6]
console.log(numbers); // Output: [1, 2, 3] (original array remains unchanged)
Pure functions can also handle transformations on objects.
function addProperty(obj, key, value) {
return { ...obj, [key]: value };
}
const person = { name: 'Alice' };
const updatedPerson = addProperty(person, 'age', 25);
console.log(updatedPerson); // Output: { name: 'Alice', age: 25 }
console.log(person); // Output: { name: 'Alice' } (original object remains unchanged)
Ensuring that data structures are not mutated helps maintain purity.
function incrementAge(person) {
return { ...person, age: person.age + 1 };
}
const person = { name: 'Bob', age: 30 };
const olderPerson = incrementAge(person);
console.log(olderPerson); // Output: { name: 'Bob', age: 31 }
console.log(person); // Output: { name: 'Bob', age: 30 } (original object remains unchanged)
Combining pure functions to create new functions also results in pure functions.
const add = (a, b) => a + b;
const multiply = (a, b) => a * b;
function compose(f, g) {
return function(x, y) {
return f(g(x, y));
};
}
const addThenMultiply = compose(multiply, add);
console.log(addThenMultiply(2, 3)); // Output: 25 ((2 + 3) * (2 + 3))
Ensure the function does not alter external state or perform any I/O operations.
function getFullName(firstName, lastName) {
return '${firstName} ${lastName}';
}
console.log(getFullName('John', 'Doe')); // Output: John Doe
console.log(getFullName('Jane', 'Smith')); // Output: Jane Smith
Avoid using global variables within functions to maintain purity.
const taxRate = 0.2; // Global variable used immutably
function calculateTax(amount) {
return amount * taxRate;
}
console.log(calculateTax(100)); // Output: 20
console.log(calculateTax(200)); // Output: 40
Pure functions can also be recursive, as long as they maintain the same principles.
function factorial(n) {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5)); // Output: 120
console.log(factorial(5)); // Output: 120
These examples illustrate various ways to create pure functions in JavaScript. The key is to ensure that the function's output is determined solely by its input values and that it does not produce any side effects.
Wednesday, February 19, 2025
JavaScript, Different ways to create pure functions in JavaScript
Subscribe to:
Post Comments (Atom)
Hot Topics
-
Objectives To provide detailed information about ListBox Types of ListBox Using ListBox in VBA applications Please read the post till end...
-
In JavaScript, innerHTML and innerText are both properties used to get or set the content inside an HTML element, but they behave differentl...
-
JavaScript was created in 1995 by a programmer named Brendan Eich for Netscape Communications Company. Brendan Eich worked in the same comp...
No comments:
Post a Comment