Search code examples
javascriptfunctionreturnconsole.log

Console.logging and then returning the console.log within a javascript function


Apologies, I'm sure this has been asked before, but I can't seem to phrase it correctly to find an answer. I was trying to learn Javascript from Udemy and there's a question where you have to return this triangle made from asterisks where the first line is 1 asterisk, 2nd line is 2, 3rd line is 3 etc up until 10 lines of asterisks. see this link if I'm not clear enough

I can console.log the triangle, but I can't seem to return it once I have console logged it. Please can someone explain where I need to place the return. I've tried everything I can think of and keep getting undefined or no answer once I add in the return for the "buildTriangle function".

    
   /*
     * Programming Quiz: Build A Triangle (5-3)
 */

// creates a line of * for a given length
function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
   
}

// your code goes here.  Make sure you call makeLine() in your own code.
function buildTriangle(length){
    var tri='';
    for(i=0;i<=length;i++){
        tri=console.log(makeLine(i));
    }
    return tri;
    
}


// test your code by uncommenting the following line
buildTriangle(10);


Solution

  • When you call the console.log() method it will return undefined (which you can see in the console spec). Instead, you need to add the return of makeLine(i) onto your tri string (using +=) every time your loop iterates (to build it up into one large triangle). Then, once you're done, return that built-up string.

    In addition to this, you should use var/let in front of your declarations in your loop and start the loop at i=1 as you don't want a line of zero stars in your resulting string:

    /*
     * Programming Quiz: Build A Triangle (5-3)
     */
    
    // creates a line of * for a given length
    function makeLine(length) {
      let line = "";
      for (let j = 1; j <= length; j++) {
        line += "* ";
      }
      return line + "\n";
    
    }
    
    // your code goes here.  Make sure you call makeLine() in your own code.
    function buildTriangle(length) {
      let tri = '';
      //   \/ -- add let/var here (doesn't effect output in this case) and initialize it to 1
      for (let i = 1; i <= length; i++) {
        tri += makeLine(i); // call makeLine(i) which returns a string
      }
      return tri; // return the triangle string
    }
    
    
    // test your code by uncommenting the following line
    console.log(buildTriangle(10)); // log the string