I give conditional test to my while-loop but it doesn't seem working. I think it's because of increment operator. but I couldn't find out why
const nums = [3, 5, 15, 7, 5];
let n, i = 0;
while ((n = nums[i]) < 10, i++ < nums.length) {
console.log(`Number less than 10: ${n}.`);
};
expected [3, 5, 7, 5]
actual result [3, 5, 15, 7, 5]
I don't know why 15 came out.
I want to know why while-loop works like this.
Update:
This problem is from the book 'learning javascript 3rd'
and , comma operator doesn't work like I thought it should.
2 Answers 2
The while is shortcut when you get to 15 if you correct the , to an &&
The comma operator returns the result of the i++ < nums.length
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
You really want to look into ES5/ES6 and filter
let smallNums = [3, 5, 15, 7, 5].filter((n) => n<10)
console.log(smallNums)
Same without the ES6 arrow:
let smallNums = [3, 5, 15, 7, 5].filter(function(n) { return n<10; })
console.log(smallNums)
3 Comments
.filter is in ES5. The arrow function is ES6 (but can easily be replaced by an ordinary anonymous function declaration if you have to support very old browsers like IE).Here. You should make a condition inside the while loop since if the condition is false then the whole loop will be terminated.
const nums = [3, 5, 15, 7, 5];
let n, i = 0;
while (i < nums.length) {
if ((n = nums[i++]) < 10) {
console.log(`Number less than 10: ${n}.`);
}
};
Explore related questions
See similar questions with these tags.
&&) instead?