How to pass specified parameters in Javascript

Viewed 29

I would like to pass value to specified parameters and use default value by optional parameters for the rest.

A sample is made as below.

Current result is 'b23'.

But I would like to obtain the result of '1b3'.

function runThis() {
    test(b='b');
}
function test(a='1',b='2',c='3'){
    console.println(a+b+c);
}

I also try to run test({b:'b'}) and test({b:='b'}), resulting SyntaxError.

Thank you for your help.

3 Answers

The syntax is slightly different:

> function test({a=1, b=2, c=3}) { console.log(a+b+c); }
undefined
> test({b:"b"})
1b3
undefined

Parameters are positional in javascript - the first parameter will always be 'a', the second 'b' and so on.

One way to achieve named parameters would be to change the signature of the function test to accept an object:

function test(obj) {
    const { a='1', b='2', c='3' } = obj
    console.log(a + b + c)
}

Calling this with

test({ b: 'b' })

will yield '1b3'

Keyword arguments are not supported in JS, arguments are resolved by their position in JS.

You could instead pass in an object and destructure the properties from it and also assign default values.

function runThis() {
  test({ b: "b" });
}

function test(inputObj) {
  const { a = "1", b = "2", c = "3" } = inputObj;
  console.log(a + b + c);
}

runThis();

You could also do the destructuring more succinctly, as shown below:

function test({ a = "1", b = "2", c = "3" }) {
  console.log(a + b + c);
}

Also, console.println is not a thing in JS, you can use console.log instead.

Related