Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda