0

function diamond(n) {
  if (n % 2 == 0 || n < 1) return null
  var x = 0,
    add, diam = line(x, n);
  while ((x += 2) < n) {
    add = line(x / 2, n - x);
    diam = add + diam + add;
  }
  return diam;
}
function repeat(str, x) {
  return Array(x + 1).join(str);
}
function line(spaces, stars) {
  return repeat(" ", spaces) + repeat("*", stars) + "\n";
}
console.log(diamond(5));

The code prints the diamond shape using asterisks.
I was trying to understand this code (other person's code).
I thought the result would look like

  *
 ***
*****
*****
*****
 ***
  *

But it worked perfectly well, and I realized the part while ((x +=2) < n) did make difference.
So my question is: what is the difference between while ((x += 2) < n) { ... } and while (x < n) { ... x += 2 }?

2 Answers 2

2
 ((x+=2) < n)

x+=2 is a shorthand for x=x+2;

if x=0 initially the condition that would be checked would be 2 < n

(x < n) {...x += 2}

if x=0 initially the condition that would be checked would be 0 < n

Main difference is you are incrementing first and then checking the condition in first one while in second one you check and then increment x.

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

3 Comments

Oh, so the statements in while loop have been looped through only two times?
I totally get it. Thanks so much !
Glad I was able to help:)
2

So your question is what's the difference between...

while ((x+=2) < n) {}

AND

while(x < n) { x+=2 }

The main difference is that in the first example, the x gets the 2 added on and is then compared to the value of n, whereas in the second example, x is compared to n before the 2 has been added and will therefore most likely run 1 more loop than you would expect

Comments

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.