skip to Main Content
const rows = 3;

for (let i = rows - 1; i > 0; i--) {
  let space = '';
  for (let j = 1; j <= i; j++) {
    space += ' ';
  }
  for (let k = 0; k < rows; k++) {
    let str = '';
    for (let l = 0; l <= k; l++) {
      str += '*';
    }
  }
  console.log(space + str);
}

4

Answers


  1. Move your variable within the proper scope.

    const rows = 3;
    
    for (let i = rows - 1; i > 0; i--) {
      let space = '';
      let str = ''; // Move here, now it works outside of the k-loop.
    
      for (let j = 1; j <= i; j++) {
        space += ' ';
      }
    
      for (let k = 0; k < rows; k++) {
        for (let l = 0; l <= k; l++) {
          str += '*';
        }
      }
    
      console.log(space + str);
    }
    
    Login or Signup to reply.
  2. Your ‘str’ variable isn’t defined in the context where your console.log is. Quickest way would be to move ‘let str = "" ‘ up to where you declare ‘space’

    Login or Signup to reply.
  3. You’re defining str inside the second inner for loop, so it will only be accessible within that loop. You can define it within the outer loop and then reset it within the inner loop, then your print statement will be able to access it.

    const rows = 3;
    
    for (let i = rows - 1; i > 0; i--) {
      let space = '';
      let str = '';
      for (let j = 1; j <= i; j++) {
        space += ' ';
      }
      for (let k = 0; k < rows; k++) {
        str = '';
        for (let l = 0; l <= k; l++) {
          str += '*';
        }
      }
      console.log(space + str);
    }
    
    Login or Signup to reply.
  4. I’m guessing this is what you’re looking for.
    In your case, the log function did not ‘see’ the str variable because it was used outside the third for-loop (for (let k = 0;...).

    const rows = 3;
    
    for (let i = rows - 1; i > 0; i--) {
      let space = '';
      for (let j = 1; j <= i; j++) {
        space += ' ';
      }
      for (let k = 0; k < rows; k++) {
        let str = '';
        for (let l = 0; l <= k; l++) {
          str += '*';
        }
        console.log(space + str);
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search