-1

If you run the below code in browser's console:

function named_param(a, b=null, c=5) {
  console.log("a="+a);
  console.log("b="+b);
  console.log("c="+c);
}

named_param(3, c=10)

The output received is:

a=3
b=10
c=5

The output I am looking for, is:

a=3
b=null
c=10

I saw the below two URLs and tried a few workaround but it didn't work

Javascript Function Parameters Not Working

Named parameters in javascript

Let me know the steps I am doing wrong here. Tried the below codes but didn't work: A:

function named_param(a, {b=null, c=5}) {
  console.log("a="+a);
  console.log("b="+b);
  console.log("c="+c);
}

named_param(3, c=10)

B:

function named_param(a, {b=null, c=5}={}) {
  console.log("a="+a);
  console.log("b="+b);
  console.log("c="+c);
}

named_param(3, c=10)
Rahul Singh
  • 374
  • 4
  • 13
  • JavaScript does not have named parameters. Please try running `named_param(3, c=10)` in strict mode and you'll get an exception. – Bergi Jun 30 '19 at 18:24
  • The "*Javascript Function Parameters Not Working*" question has nothing to do with this. – Bergi Jun 30 '19 at 18:27

4 Answers4

1

You can skip parameter in between, so when you pass

named_param(3, c=10)
            |   |_____________ considered as `b`
            |_________________ considered as `a`

You can use object and destructuring

function named({a,b=null,c=3} = {}){
  console.log('a-->',a)
  console.log('b-->',b)
  console.log('c-->',c)
}

named({a:1,c:2})
named()
named({c:2})
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

When using the destructuring solution, you must pass an actual object. named_param(3, c=10) simply is invalid syntax (well, it's valid, but it's an assignment to a global c variable that is passed as the second argument - no naming).

function named_param(a, {b=null, c=5}={}) {
  console.log("a="+a);
  console.log("b="+b);
  console.log("c="+c);
}

named_param(3)
named_param(3, {b:"hi"})
named_param(3, {c:10})
named_param(3, {b:"hi", c:10})
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

What you can do is something using destructuring objects like:

function named_params({a = 4, b = null, c = 5} = {a:1, b: 2, c:3}) { console.log(a,b,c) }

then, the call for your function will be:

named_params({a: 3, c:10})
-1

Well, it's not an issue, it's just you trying to use named parameters where they are not supported at all.

To reach what you need, you should do like this:

function named_param({a, b, c}) {
  console.log("a="+a);
  console.log("b="+b);
  console.log("c="+c);
}

named_param({a:5, c:9}); 
// Output:
// a=5
// b=undefined
// c=9

At first I misunderstood your question and proposed to use destructuring assignment with arguments object.