Home >Web Front-end >JS Tutorial >JavaScript Fundamentals – The Pure Function
Once we start building our first algorithms, comes the desire and the need to write more maintainable code. This is where pure function comes into play.
This is a function that will not generate any side effects; that is to say, it will not modify anything outside its scope.
Examples:
It is more readable, predictable (reduces errors) and easy to test and debug. With the same parameters it returns the same result.
Let's take the following example to calculate an average:
const calculateAverage = (numbers) => { if (numbers.length === 0) return 0 const totalSum = numbers.reduce((sum, num) => sum + num, 0) return totalSum / numbers.length } const scores = [80, 90, 75, 85, 95] const average = calculateAverage(scores) console.log(average) // 85
But without knowing it you are probably already using pure functions thanks to JavaScript methods like .toUppercase() which does not modify the original string, but returns a new uppercase string:
const text = "hello" const upperText = text.toUpperCase() console.log(upperText) // "HELLO" console.log(text) // "hello" > la chaîne d'origine n'a pas été modifiée
And There you go, you know everything about pure functions :)
The above is the detailed content of JavaScript Fundamentals – The Pure Function. For more information, please follow other related articles on the PHP Chinese website!