You already know how to write simple single-line JavaScript programs that output a line of text to the console. This is an achievement in itself, but real programs contain many lines—from tens to hundreds for small scripts to several thousand for larger projects. After completing this topic, you will know how to print several lines of text to the console.
Example
Let's start with an example of such scripts. The following code prints three lines of text, each on a new line:
console.log("I");
console.log("know");
console.log("JavaScript");A line break can also be inserted using the \n symbol:
console.log("I\nknow\nJavaScript");The output of these two code samples will be the same:
I
know
JavaScriptTry running these statements in your browser console to verify that they produce the same output.
Empty line
The console.log function also allows you to output an empty string without any information in it or call the function without an argument. Then, the function will only output a newline:
console.log("I");
console.log("");
console.log("know");
console.log();
console.log("JavaScript");Here's the output:
I
know
JavaScriptNotice that both () and ("") produce the same result.
One last thing: inserting an empty line in your code doesn't change the output:
console.log("What")
console.log("about")
console.log("you?")The above code prints:
What
about
you?Conclusion
In this topic, we learned how to split text into lines using different methods. One way is by using console.log() for each line. Another way is by inserting \n inside a single console.log() call to create multiple lines. Knowing these techniques is essential because, in larger projects, they help us organize code more effectively and improve our code's readability. However, programming is not limited to creating text outputs. In the upcoming topics, we will explore more advanced multi-line programming techniques in JavaScript.