Reputation: 627
I have this simple question where I pass an input made of several numbers to the my function, and want it to output the smallest number.
question7 = function(input){
minimum = Math.min(input);
console.log(minimum);
}
question7(5,-2,0,1);
Why does the console output 5?
Upvotes: 2
Views: 594
Reputation: 5443
You are only passing 5
to Math.min because that is the first parameter you're calling the question7
function with. You want to pass all the arguments
or parameters to Math.min
In this case you could leverage apply
.
var question7 = function() {
var minimum = Math.min.apply(Math, arguments);
console.log(minimum)
}
question7(5,-2,0,1);
apply
takes an array like object and spreads it out into individual arguments and applies them to this
argument, in this case Math
So for this example it takes everything you call question7
with and applies them to Math.min
function.
In Javascript arguments
is a reserved keyword/variable which holds all the parameters which a function was called with.
Upvotes: 3
Reputation: 16384
In your code you have passed only 5
, because your function accepts only one argument. Try this:
question7 = function(input) {
var minimum = Math.min(...input);
console.log(minimum);
}
question7([5, -2, 0, 1]);
Here i'm passing an array of numbers and then, in var minimum = Math.min(...input);
row i have used the spread syntax ...
before the argument.
For more info about ...
: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Spread_operator
Upvotes: 3