generate christmas tree in javascript

To generate a Christmas tree in JavaScript, we can use nested loops and string concatenation to create the pattern of the tree. Here's an example code:

index.tsx
// set the height of the tree
const height = 5;

// loop through each row of the tree
for (let i = 0; i < height; i++) {
  let treeRow = '';

  // add spaces to center the tree
  for (let j = 0; j < height - i; j++) {
    treeRow += ' ';
  }

  // add asterisks for the tree branches
  for (let k = 0; k < i * 2 + 1; k++) {
    treeRow += '*';
  }

  // log the row to the console
  console.log(treeRow);
}

// add the tree trunk to the bottom of the tree
for (let i = 0; i < 2; i++) {
  let treeRow = '';

  // add spaces to center the tree trunk
  for (let j = 0; j < height - 1; j++) {
    treeRow += ' ';
  }

  // add asterisks for the tree trunk
  treeRow += '|';

  // log the row to the console
  console.log(treeRow);
}
729 chars
37 lines

In this code, we set the height of the tree to 5. We then loop through each row of the tree, adding spaces to center the row, and asterisks for the branches. We log each row to the console using console.log(). Finally, we add the tree trunk to the bottom of the tree by looping through two more rows and adding spaces and a single asterisk for the trunk. When this code is executed, it will print out a Christmas tree in the console.

gistlibby LogSnag