-1

I've seen an example giving wrong output when I try to run it. I don't understand why I get the wrong result while it is supplied in order. At the last call, I expect a=7, b=10. What's wrong?

"use strict";

function f(a=1, b=2){ return(`a=${a}, b=${b}`) }
f() // a=1, b=2
f(a=5) // a=5, b=2
f(a=7, b=10) // a=7, b=10
f(b=10, a=7) // Order is required: a=10, b=7
  • 1
    JavaScript doesn't have keyword arguments. – jonrsharpe Jan 30 '21 at 18:07
  • Does this answer your question? [passing javascript method params as object literal](https://stackoverflow.com/questions/21453464/passing-javascript-method-params-as-object-literal) – Filip Seman Jan 30 '21 at 18:10
  • @FilipSeman no. – jslearner Jan 30 '21 at 18:11
  • 1
    To clarify the specific behaviour here, `a=7` and `b=10` are *assignments*, which are expressions evaluating to the value assigned. Nothing to do with the names of the parameters defined in the function, you could do `f(foo=1, bar=2)` and it would still be the same as `f(1, 2)`. – jonrsharpe Jan 30 '21 at 18:16
  • Does this answer your question? [why order of parameter remain same even arguments are passed as named arguments? in javascript](https://stackoverflow.com/questions/51259580/why-order-of-parameter-remain-same-even-arguments-are-passed-as-named-arguments) – jonrsharpe Jan 30 '21 at 18:21
  • @jonrsharpe so, what's going on in detail if we do `b=10` as in the example? – jslearner Jan 30 '21 at 18:38
  • The thing I said in my comment above, an assignment. – jonrsharpe Jan 30 '21 at 18:38

1 Answers1

2

Parameters provided are handled in the order defined in the function. To achieve something similar, you can use an object parameter:

function f(prmObj){ return(`a=${prmObj.a}, b=${prmObj.b}`) }

f({b: 10, a: 7})  // a=7, b=10
Neil W
  • 7,670
  • 3
  • 28
  • 41
  • Is there any technical definition of _"Parameters provided are handled in the order"_ such as on mozilla developer platorm? – jslearner Jan 30 '21 at 18:13
  • [MDN functions reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions) – David784 Jan 30 '21 at 18:18
  • 1
    @jslearner the MDN docs cover functions in e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions. Parameter order *must* be maintained, otherwise functions would be unusable. – jonrsharpe Jan 30 '21 at 18:19