Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
how passing argument mechanism works in javascript?

can you explain how arguments are passed automatically in callback functions?

1. const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2. arr.sort(comFunc); 
3. /* how arugments 'a' and 'b' are passed inside comFunc in sort() function */
4. function comFunc(a, b){
5.    return b - a;
6. }
7. arr.forEach((item)=>{
8. console.log(item);
9. })

In the code above I'm confused how a and b are automatically passed as an argument inside sort()? can you explain the 2nd line in the code that how comFunc get his arguments?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The Array.prototype.sort function will iterate through the array, passing the values at the current index(a) and the next index(b) to the callback function you have provided.

As per your example above it should make the following calls per iteration

0: a = 1; b = 2  
1: a = 2; b = 3  
2: a = 3; b = 4
...
about 4 years ago · Juan Pablo Isaza Relatório

0

Your comFunc is a variable with Function type. It will get called later by sort method internally and they take care of passing the parameters with appropriate values.

Here is a simpler example since sort is a bit complicated. Let's look at Array.filter function instead:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

We can implement such function like this:

function filter(arr, filterFunction) {
    const result = [];

    for (let item of arr) {
        if (filterFunction(item)) {
            result.push(item);
        }
    }

    return result;
}

When creating the function, you do not know what "end-developer" want to filter with. Therefore, you let developer pass a function, and it's developer's job to make sure it's a function that accept an item and return a boolean-like result. Our job is to pass the item and act accordingly to the result. For example:

const arr = [1,10,5,3,2];
const filteredArr = filter(arr, require5OrMore);

function require5OrMore(item) {
    return item >= 5;
}

// filterArr now contains only items that are >= 5 (10 and 5)

Note that in reality, the above code can be simplified using anonymous and/or arrow function:

const filteredArr = filter(arr, item => item >= 5);

Now if you still cannot understand why it is happening, you can put some breakpoint in the above filter function and require5OrMore function and check the values as the code runs through it.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda