Home >Web Front-end >JS Tutorial >Understanding Higher-Order Functions in JavaScript

Understanding Higher-Order Functions in JavaScript

DDD
DDDOriginal
2024-11-20 11:39:461026browse

Razumevanje funkcija višeg reda (Higher-Order Functions) u JavaScript-u

If you're learning JavaScript, you've probably come across the term Higher-Order Functions. Although it sounds complicated, it is not that complicated. JavaScript, as a functional programming language, allows the use of these functions, which are crucial in function-based programming.

Functional Programming

Functional programming implies the creation and use of functions as primary building blocks. In this approach, functions can be passed as parameters to other functions or returned as results. This way of thinking allows for organized and efficient code writing.

First Class Features

JavaScript treats functions as "first class citizens". This means that functions are objects — a specific type of object that can be assigned to variables, passed as parameters, and used in different contexts, such as numbers or strings.

Example:

function pozdrav() {
  console.log('Zdravo, svete!');
}
pozdrav();  // Ispisuje 'Zdravo, svete!'

// Dodavanje svojstva funkciji
pozdrav.jezik = 'srpski';
console.log(pozdrav.jezik); // Ispisuje 'srpski'

Assigning Functions to Variables

In JavaScript, functions can be assigned to variables:

const kvadrat = function(x) {
  return x * x;
};
console.log(kvadrat(5));  // Ispisuje 25

Passing Functions as Parameters

One of the main features of first-class functions is the ability to pass them as arguments to other functions:

function formalniPozdrav() {
  console.log("Kako ste?");
}
function neformalniPozdrav() {
  console.log("Šta ima?");
}
function pozdravVrsta(vrsta, formalan, neformalan) {
  if (vrsta === 'formalan') {
    formalan();
  } else if (vrsta === 'neformalan') {
    neformalan();
  }
}
pozdravVrsta('neformalan', formalniPozdrav, neformalniPozdrav);  // Ispisuje 'Šta ima?'

Higher Order Functions

Higher Order Functions are functions that accept other functions as arguments or return them as results. This allows for more elegant and concise code writing. Examples include the map, filter, and reduce.

methods

map Method

map creates a new array by calling a function on each element of the existing array:

No map method:

const arr1 = [10, 20, 30, 40, 50];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
  arr2.push(arr1[i] * 2);
}
console.log(arr2);  // [20, 40, 60, 80, 100]

With map method:

const arr1 = [10, 20, 30. 40, 50];
const arr2 = arr1.map(item => item * 2);
console.log(arr2);  // [20, 40, 60, 8-, 100]

filter Method

The

filter creates a new array with all elements that satisfy the given condition:

const osobe = [
  { ime: 'Pera', godine: 13 },
  { ime: 'Mika', godine: 18 },
  { ime: 'Laza', godine: 64 },
  { ime: 'Ana', godine: 10 },
];
const punoletni = osobe.filter(osoba => osoba.godine >= 18);
console.log(punoletni);  // [ { ime: 'Mika', godine: 18 }, { ime: 'Laza', godine: 64 } ]

reduce Method

reduce performs a function on each member of the array and returns a unique value:

Example with reduce:

const arr = [4, 6, 10, 5, 25];
const suma = arr.reduce((akumulator, vrednost) => akumulator + vrednost, 0);
console.log(suma);  // 50

Creating a Higher Order Function

Imagine if JavaScript didn't have a built-in map method. We can create it ourselves:

function mapiraj(arr, fn) {
  const noviNiz = [];
  for (let i = 0; i < arr.length; i++) {
    noviNiz.push(fn(arr[i]));
  }
  return noviNiz;
}
const duzine = mapiraj(['JavaScript', 'Python'], item => item.length);
console.log(duzine);  // [10, 6]

Conclusion

Higher-order functions enable flexibility and simplicity of code in JavaScript. By using these features, our code becomes more concise, organized, and maintainable.

The above is the detailed content of Understanding Higher-Order Functions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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