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? 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. 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. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Quentin. Sorry for the 2nd question, I updated now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.