javascripttriangle-count

JavaScript triangle with single function


I'm playing around with making triangles in Javascript and normally I've had to use 2 functions to make one. I recently tried to create one with a single function though, and it worked perfectly. But I'm not sure why or how it starts a new line after running through the for loop each time since I never mentioned " \n " anywhere in the code for the single function. Could anyone explain why it still works? Thanks.

    function tri(num){
  var star = '';
  for(var i = 1; i <= num; i++){
    var star = star + " *";
    console.log(star)
  }
}
tri(10)

Here's how I did it with 2 functions

    function horiztonal(num){
  var star = "";
  for(var i = 0; i <= num; i++){
    var star = star + " *"
  }
  console.log(star)
}


function buildTri(num){
  var star = "";
  for(var i = 0; i < num; i++){
    var star = star + horiztonal(i)
  }
  console.log(star)
}

buildTri(10)

There's also a string of repeating "undefined" after running the 2 function attempt, so if anyone could explain that as well I'd really appreciate it. Thanks again.


Solution

  • The reason why you're getting "undefined" printed, is you're confusing between a function that returns a string and a function that writes to the console.log(). If you study, horizontal() carefully, you see that it's writing to the console... There is no return value. However, if you study the tri() function carefully, you'll see that it expects horizontal() to be returning a string. i.e. the two assumptions are at odds. So, the behaviour you're getting is the outputs to the console.log as well as the concatenation of undefined because your function didn't return any value.

    I've made the following rectifications:

    function horiztonal(num) {
      var stars = "";
      for (var i = 0; i <= num; i++) {
        stars = stars + " *"
      }
      return stars;
    }
    
    
    function buildTri(num) {
      var stars = "";
      for (var i = 0; i < num; i++) {
        stars = stars + horiztonal(i) + "\n";
      }
      console.log(stars)
    }
    
    buildTri(10);