Pass only the second argument in javascript
Asked Answered
C

4

35

I'm trying to make a function in which I pass only the second argument of my function.

I would like it to work this way:

function test (a,b) { 
    // ...
};
// pass only the second parameter 
test( ... , b);

My current idea is to pass the second argument as a de facto dynamic default parameter as following:

var defaultVar = "something";
    
function test (a, b=defaultVar) {
    // ...
}

...then change the defaultVar value according to my needs.

var defaultVar = modification; 

In fact, I'm using the Google drive API, and I'm trying to make it such that I can enter a string value for the second parameter to make a callback. This callback would take the role of verifying whether the return file is effectively the file searched (by making a boolean verification on name value).

Hence, the idea to me is to automate the process of getting a file on Google drive by passing his name and retrieving the file data in this way.

I hope this precision will be useful.

Here is my quickstart.js :

// (...Google authentication and all) ; 

var filename = "";
// enter a filename in the function by the way of filename
function listFiles (auth, filename =  filename) {
  const drive = google.drive({version: 'v3', auth});
  drive.files.list({
    pageSize: 50,
    fields: 'nextPageToken, files(id, name)',
  }, (err, {data}) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = data.files;
    if (files.length) {
      console.log('Files:');
      files.map((file) => {
        console.log(`${file.name} (${file.id})`);

        // check if the file returns match the filename wished 
        displayFile(file);
        if(`${file.name}` == filename ){
          console.log("name found !");
          const fileData = {
            name : `${file.name}`,
            id : `${file.id}`
          };
          return fileData;
        }
      });
    } else {
      console.log('No files found.');
    }
  });
}

listFiles(undefined, "test.md")

Any improving ideas are welcome.

Continuate answered 28/5, 2018 at 15:11 Comment(5)
Hi! I'm afraid it's not at all clear what you're asking here. Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the [<>] toolbar button; here's how to do one).Ovida
You can't pass two arguments to a function without passing some value as the first argument.Sallust
can you use bind or call?, It could be useful developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Bridgework
Maybe test(b) ?Flin
thanks all for your useful and even quick answers, I have completed my question, hope my precision will be useful, in the meanwhile I will test your suggestions.Continuate
O
48

With default parameter values added in ES2015, you can declare default values for the parameters, and when making the call, if you pass undefined as the first parameter, it will get the default:

function test(a = "ay", b = "bee") {
  console.log(`a = ${a}, b = ${b}`);
}
test();             // "a = ay, b = bee"
test(1);            // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2);         // "a = 1, b = 2"

You can do something similar yourself manually in a pre-ES2015 environment by testing for undefined:

function test(a, b) {
  if (a === undefined) {
    a = "ay";
  }
  if (b === undefined) {
    b = "bee";
  }
  console.log("a = " + a + ", b = " + b);
}
test();             // "a = ay, b = bee"
test(1);            // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2);         // "a = 1, b = 2"
Ovida answered 28/5, 2018 at 15:17 Comment(2)
...if that's what you're asking. :-)Ovida
thanks T.J. Crowder, I think it will be okay with all that, I think finally I was very near to the answer I seek for. The only thing I got to do finally it's to modify the value of filename according to body.req.name now. ThanksContinuate
A
24

If you are OK with a change to the number of arguments that your function takes, you could pass the arguments via object properties. Then you can let the caller decide which property (or properties) to specify during the call.

The other properties can take default values through object destructuring in the function's parameter specification:

function test({a = 1, b = 2}) {
    console.log(`a = ${a}, b = ${b}`);
};

test({b:42}); // only specify what b is
Anticholinergic answered 17/3, 2019 at 15:58 Comment(1)
Amazing answer! Your answer should be the accepted one!Manilla
P
1

You can pass any falsly value to an argument that you want to "bypass"...

function test (a,b) { 
    // ...
};
// pass only the second parameter 
test( null , b);
test( 0, b);
test( undefined, b);

***note: Whenever you want to use this argument inside your function, make sure that it is truely. I assume that this is not a Boolean argument

Paphlagonia answered 27/10, 2021 at 8:3 Comment(0)
R
0

You can use objects for this issue:

const test = (value) => {
  defaultValue = {a: 'me default', b: false};
  tmp = Object.assign(defaultValue, value)

  console.log(tmp.a)
  console.log(tmp.b)
};

test({ a: true })

With this approach You will dot't have to pass unnecessary parameters.

Rugging answered 13/6, 2022 at 13:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.