Home > Web Front-end > JS Tutorial > JavaScript Fundamentals – The Pure Function

JavaScript Fundamentals – The Pure Function

DDD
Release: 2025-01-15 18:30:49
Original
514 people have browsed it

Les fondamentaux de JavaScript - La fonction pure

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.


What is a so-called “pure” function?

This is a function that will not generate any side effects; that is to say, it will not modify anything outside its scope.
Examples:

  • no modification of global variables,
  • no modification of objects passed as arguments,
  • no changes in the user interface,
  • no network calls, etc.

It is more readable, predictable (reduces errors) and easy to test and debug. With the same parameters it returns the same result.


Examples of pure functions

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

Copy after login

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
Copy after login



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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template