Hello guys,
I’m learning Javascript on FCC and having EloquentJs as additional resourse.
as I’m doing one of the exercise on Eloquent, I bump into a bit of confusion.
so the exercise is:
To write a range
function that takes two arguments, start
and end
, and returns an array containing all the numbers from start
up to (and including) end
.
it was fine. I could solve it, until I try to do the bonus assignment which is:
modify your range
function to take an optional third argument that indicates the “step” value used when building the array. If no step is given, the elements go up by increments of one, corresponding to the old behavior. The function call range(1, 10, 2)
should return [1, 3, 5, 7, 9]
. Make sure it also works with negative step values so that range(5, 2, -1)
produces [5, 4, 3, 2]
.
this is my code:
function range(start,end,step){
let array=[];
if (step == 0) {
for(let i = start; i<= end; i++) {
array.push(i);
}}else if(step > 0 ) {
for(let i = start; i<= end; i+=step) {
array.push(i);
}} else if(step <0) {
for(let i = start; i>= end; i+=step){
array.push(i);
}}
return array;
}
with this code, it actually works in a sense that it would shows the correct result with any input on “step” like below
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
So now the problem is, when I did not input anything on “step” argument. nothing is showing. it would just turn out an empty array like this:
console.log(range(1, 10))
// → []
There’s a solution code and I’ve read through it. but I would like to understand why my code isn’t working when I didn’t input the third argument inside the range.
looking forward for your explanation soon