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

225
Visualizações
How can javascript skip passing a parameter for a method?

Recently I've been learning node.js, and I've found two code fragments like this:

Fragment 1:

const fs = require('fs')
fs.readFile("content.txt", "utf8", (err, msg) => {
    console.log(msg);
})

Fragment 2:

const fs = require('fs')
fs.readFile("content.txt", (err, msg) => {
    console.log(msg);
})

They have only one difference that Fragment 1 passed 'utf8' as the second parameter while Fragment 2 skips to pass it. And although they have different results, both of them can function normally without a syntax error.

So I wonder how a javascript method is able to skip to pass the parameter? And how can I define a method/function like this?

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

0

You can achieve this effect in your own code by determining the arity within your method. This might be as simple as just checking the number of arguments, or it might be that you need to check the type of each/some argument(s)

An example:

function myArityAwareFunction(){
    if(arguments.length == 2)
        console.log("2 arguments", ...arguments)
    else if(arguments.length == 3)
        console.log("3 arguments", ...arguments)
    else
        throw ("This method must be called with 2 or 3 arguments");
}


myArityAwareFunction("foo","bar");
myArityAwareFunction("foo","bar","doo");
myArityAwareFunction("This will fail");

about 4 years ago · Juan Pablo Isaza Relatório

0

With arrow function:

const fn = (...args) => {
  console.log(args.length);
  if (args.length < 2) {
    throw Error('missing arguments');
  } else if (args.length === 2) {
    /* ... */
  } else if (args.length === 3) {
    /* ... */
  } else {
    /* ... */
  }
};

or with switch block

const fn = (...args) => {
  console.log(args.length);
  switch(args.length) {
    case 0: /* ... */ break;
    case 1: /* ... */ break;
    /* ... */
    default: /* ... */ break;
  }
};

But it's much better to validate argument type rather than do something depend on args.length

So for your example with the fs code could look like this:

const readFile = (...args) => {
  if (typeof args[0] === 'string') {
    /* ... */
  } else {
    throw TypeError('Path must be a string');
  }
  if (typeof args[1] === 'string') {
    /* ... */
    if (typeof args[2] === 'function') {
      /* ... */
    } else {
      throw TypeError('Callback must be a function');
    }
  } else if (typeof args[1] === 'function') {
    /* ... */
  } else {
    throw TypeError('Callback must be a function');
  }
};
readFile({}); // TypeError: path must be a string
readFile('test.txt', 'utf-8', {}); // TypeError: Callback must be a function
readFile('test.txt', {}); // TypeError: Callback must be a function

readFile('test.txt', () => {}); // success
readFile('test.txt', 'utf-8', () => {}); // success
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