"Hello World!" in JavaScript

Write the first piece of code in JavaScript by printing "Hello World!".

Printing in JavaScript

Although JavaScript was made to interact with HTML and CSS elements or the DOM, it is essential to print values and variables in memory to the terminal. This is where the console.log command comes into play. As the name suggests, the function writes directly into the console and becomes handy while testing.

Making use of console.log

In the code below, see the syntax to print “Hello World!” directly into the console using console.log.

console.log("Hello World!"); //Prints Hello World! on console

Note: The trailing semicolon is unnecessary in JavaScript. Removing it won’t throw any error. But the semicolon allows you to write multi-line code within the same line, acting as a separator of code.

The statement is pretty straightforward. In the above code, we use the object console and call its method log to write onto console the argument "Hello World!".

The console object is a part of the DOM objects family available to the JavaScript language and the command console.log will print anything passed to it as an argument.

Notice that when using console.log to write into the console, you always end with a new line character at the end.

console.log("Hello World-1!"); // This should be on the first line
console.log("Hello World-2!"); // This should be on the second line

In the above example, you can see how two consecutive console.log statements end up in different lines without explicitly adding a new line character. This could be troublesome for some users. To solve this problem, use the process object instead.

Making use of process.stdout.write

In a Node.js environment, we can use the stdout (as in C/C++) child of the process object and call its write method to write into the console explicitly.

process.stdout.write("Hello World-1!");
process.stdout.write("Hello World-2!"); // This will be on the same line

In the above example, the process.stdout.write writes exactly what is told, giving us more control. In this lesson, we covered the console and process objects. There are many more global objects accessible in the language which enable us to do countless things.

We will use console.log as the default printing statement. One key thing to note is that the console object also uses the process object to log anything into the terminal.