简体   繁体   中英

The difference between console.log and return in javaScript

So I created two different functions to build triangles out of asterisks: buildTriangle and buildTriangle2. The makeLine function is just used to make the lines in the triangles. This is what my code looks like:

 function makeLine(length) { var line = ""; for (var j = 1; j <= length; j++) { line += "* " } return line + "\\n"; } // This is the build triangle function with the return key function buildTriangle(triWidth) { var y = "" for(var i = 0; i <= triWidth; i++) { y += makeLine(i) } return y; } console.log(buildTriangle(10)) // This is the build triangle function with console.log function buildTriangle2(triWidth) { for(var i = 0; i <= triWidth; i++) { console.log(makeLine(i)); } } buildTriangle2(10) 

The output looks like this: https://i.stack.imgur.com/QrHxO.png . First, I just had a quick question as to why there are spaces between each line in the second output and not in the first. Also, I just wanted to know why the the function with the return key needs to store the information in the variable first and then return it? Why is this not the case in the second function that uses the console.log? I am asking this question because I think these two functions illustrate the differences between console.log and return. Also, since I don't understand the difference between console.log and return I was hoping someone could explain it by using these functions. I also believe this will help other beginners besides for myself.

return doesn't do anything to the value, so you build what you want and you get exactly that.

console.log() is meant for outputting stuff (mainly for development purposes originally, but now with things like Node.js, also for general output).

In most environments, console.log() will always include a newline on it's own (similar to other languages println() functions).

That's why you need to have the \\n for the return, and not for console.log() , since it is basically adding one to each line for you. If you add an extra \\n yourself, you'll end up with a blank line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM