1
const add = (x=5, y=10) => console.log(x+y);

After we run the transpiler on this code, here is what the output would look like:

"use strict";
var add = function add() {
 var x = arguments.length <= 0 || arguments[0] === undefined ?
 5 : arguments[0];
 var y = arguments.length <= 1 || arguments[1] === undefined ?
 10 : arguments[1];
 return console.log(x + y);
};

I got this snippet from Learning react book. I have two question here

  1. Can arguments.length be negative?
  2. Does checking the second "||" condition be sufficient to check whether arguments[0] or arguments[1] is undefined?
5
  • 1
    I don't understand the second question. Sufficient for what?
    – deceze
    Commented Jul 24, 2018 at 12:50
  • 2
    1. No. 2. No. Why do you think so? Commented Jul 24, 2018 at 12:50
  • 1
    That's just defensive programming wrt to length being negative. It also enables short circuit evaluation.
    – HSchmale
    Commented Jul 24, 2018 at 12:52
  • Thank you @deceze, for checking whether argument is undefined. Commented Jul 24, 2018 at 12:54
  • @HenokTesfaye Yes you probably could, but JS engines don't like (read: don't optimise for) you to access arguments out of bounds.
    – Bergi
    Commented Jul 24, 2018 at 13:04

1 Answer 1

2

Can arguments.length be negative?

No. How could you call a function and put a negative number of things between ( and )?!

Does checking the second condition be sufficient?

No. The function might be called with only one argument.

1
  • Thank you @Quentin. Sorry for the 2nd question, I updated now. Commented Jul 24, 2018 at 13:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.