Learning Javascript functions, and having trouble with the problem below.
Modify this function so that if it’s called with 1 or 0 arguments, it returns null
.
function divide(num1, num2) {
return num1 / num2;
}
let num1 = null;
let num2 = null;
let answer = divide(1,1)
console.log(answer);
Assuming we only need to apply a straight forward modification, I would avoid too much syntactical sugar and just write it this way:
function divide(num1, num2) {
if (arguments.length < 2) {
return null;
}
return num1/num2;
}
If we want to make it simple and elegant, I would write it this way (requires ES6 features):
const divide = (...args) => args.length < 2 ? null : args[0] / args[1];
function divide(num1, num2) {
if (arguments.length < 2) {
return null;
}
return num1/num2;
}
While this is a great solution for the problem there are a downsides to it, if you wanted to switch to arrow function arguments
object doesn't appear.
?
which is best suitable for simple if
statementsfunction divide(num1,num2) {
return arguments.length < 2 ? null : num1 / num2;
}
...
can be used to either collect items into an array known as rest, or expand an array known as spread. function divide(...args) {
return args.length < 2 ? null : args[0] / args[1];
}
JavaScript will collect all the arguments passed to the function and put them into an array called args
, I like this better since the reader can see where is args
defined.
const divide = (...args) => args.length < 2 ? null : args[0] / args[1];
On a final note all the previous solutions has a downside that we are only checking for length of arguments but not contents of arguments, lets assume that someone sent undefined
into one of the first two arguments, you'll have 2 arguments but one of them is kinda missing and you'll get NaN
since number of arguments is 2.
function divide(num1, num2) {
if (num1 === undefined || num2 === undefined) {
return null;
}
return num1/num2;
}
Demo
function divide1(num1, num2) {
if (arguments.length < 2) {
return null;
}
return num1/num2;
}
function divide2(num1,num2) {
return arguments.length < 2 ? null : num1 / num2;
}
function divide3(...args) {
return args.length < 2 ? null : args[0] / args[1];
}
const divide4 = (...args) => args.length < 2 ? null : args[0] / args[1];
const test = (cb) => {
console.log("-------->" + cb.name)
console.log(cb());
console.log(cb(1));
console.log(cb(1, 2));
console.log(cb(1, undefined));
console.log(cb(1, null));
console.log(cb(1, 2, 3));
};
test(divide1);
test(divide2);
test(divide3);
test(divide4);
Peep this.
function divide(num1, num2) {
if(arguments.length < 2) return null;
return num1 / num2;
}
The arguments object is available in all (non-arrow) function and represents all the arguments passed into the function. It has a length property that tells you how many arguments there are.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With