0

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.

4
  • 1
    the comma operator doesn't do what you seem to think. Did you mean the logical "and" operator (&&) instead? Commented Feb 15, 2019 at 10:13
  • when i put && instead, it gives me only 3 and 5.. Commented Feb 15, 2019 at 10:19
  • 1
    Because the while loop stops at 15 because you asked it to Commented Feb 15, 2019 at 10:19
  • very thank you you helps me a lot!! Commented Feb 15, 2019 at 10:27

2 Answers 2

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)

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

3 Comments

!!The comma operator returns the result of the i++ < nums.length!!
just to clarify, .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).
@RobinZigmond Updated
2

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}.`);
  }
};

2 Comments

thanks very much! could you tell me how my code works??? i dont know why conditional expression doesn't catch the number more than 10
Note : you need to add a break into if statement to get the same of behaviour of while loop condition

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.