Can someone explain how this works to create a square out of +'s?

function generateShape(int) {  
  var ans = '';
  for (var i = 0; i < int; ++i) {
    for (var j = 0; j < int; ++j) {
      ans += '+';
    }
    if (i != int - 1) {
      ans += '\n';
    }
  }
  return ans;
}

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

Hi @bry954!

Due to the lack of context for your problem, I am going to make a few comments here and I hope it might help with your current problem.

I do not recommend to use “int” for the parameter because int is a reserved keyword for other programming languages. It is okay to use it but it might confuse others when they read your code.

I recommend using an array (ans) instead of string concatenation (+=) for better efficiency.

function generateShape(size) {  
  let ans = [];

  for (let i = 0; i < size; i++) {
    let row = '';
    for (let j = 0; j < size; j++) {
      row += '+';
    }
    ans.push(row); 
  }

  return ans.join('\n'); 
}

I don’t think there is an appreciable efficiency difference between dynamically allocating an array instead of dynamically allocating a string. And each row is still a dynamically allocated string. I wouldn’t try to chase micro optimizations or recommend them to others really. Overall designs decisions will pay off more.

I suggest to use VS Code debugging feature to understand in detail

YT Search “debugging in vscode javascript”