Quiver
Quiver

Reputation: 47

Javascript - Problem with passing arguments to functions: passing them in diffrent order returns wrong values

I know it may be a silly question but I know how to pass information to functions like this:

function test1(a, b) {
  alert("TEST1 a: " + a + " (should be: 2)")
  alert("TEST1 b: " + b + " (should be: 1)")
  }
test1(b = 2, a = 1)


// but if i switch the order when passing arguments
// like here:


function test2(a, b) {
  alert("TEST2 a: " + a + " (should be: 2)")
  alert("TEST2 b: " + b + " (should be: 1)")
  }
test2(a = 1, b = 2);
The problem is that if I switch "a" and "b" and pass the information in the diffrent order, my intended values will also change as shown above.

My function wont recognise the difference and will read "a" as 2 and "b" as 1. Is there a way to prevent this from happening? Or is there a better method? Or should I pass the information as an object? I'm not sure if passing "arguments" in an object is the right way to do it.

Upvotes: 0

Views: 164

Answers (2)

Callam
Callam

Reputation: 11539

The function and the order in which you should pass the arguments is fixed. You can pass an object instead, and use object destructuring to mimic the arguments.

function test({ a, b }) {
  console.log("TEST a: " + a + " (should be: 1)")
  console.log("TEST b: " + b + " (should be: 2)")
}

test({ a: 1, b: 2 });
test({ b: 2, a: 1 });

If you care about the order in which the keys are passed:

function test(arguments) {
  Object.keys(arguments).forEach(key => {
    console.log(`TEST ${key}: ${arguments[key]}`);
  })
}

test({ a: 1, b: 2 });
test({ b: 2, a: 1 });

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You changed order of parameters passed to function call not at the function definition.

One way to achieve what you're trying to achieve is using object and destructuring.

function test(input) {
  const {a , b} = input
  console.log("TEST1 a: " + a + " (should be: 2)")
  console.log("TEST1 b: " + b + " (should be: 1)")
  }
  
test({b : 2,a : 1})
test({a : 2,b : 1});

Upvotes: 0

Related Questions