Hello, World! Your First JavaScript Programs

The following is a short extract from our new book, JavaScript: Novice to Ninja, 2nd Edition, written by Darren Jones. It’s the ultimate beginner’s guide to JavaScript. SitePoint Premium members get access with their membership, or you can buy a copy in stores worldwide.
It is a tradition when learning programming languages to start with a “Hello, world!" program. This is a simple program that outputs the phrase "Hello world!" to announce your arrival to the world of programming. We’re going to stick to this tradition and write this type of program in JavaScript. It will be a single statement that logs the phrase "Hello, world!" to the console.
To get started, you’ll need to open up your preferred console (either the Node REPL, browser console, or ES6 Console on the web). Once the console has opened, all you need to do is enter the following code:
console.log(‘Hello world!’);

Then press Enter. if all went to plan you should see an output of "Hello, world!" displayed; similar to the screenshot below.

Congratulations, you’ve just written your first JavaScript program! It might not look like much, but a wise person once said that every ninja programmer’s journey begins with a single line of code (or something like that, anyway!).
JavaScript in the Browser
JavaScript is an interpreted language and needs a host environment to run. Because of its origins, the main environment that JavaScript runs in is the browser, although it can be run in other environments; for example, our first program that we just wrote ran in the Node REPL. Node can also be used to run JavaScript on a server. By far the most common use of JavaScript is still to make web pages interactive. Because of this, we should have a look at what makes up a web page before we go any further.
Three Layers of the Web
Nearly all web pages are made up of three key ingredients ― HTML, CSS and JavaScript. HTML is used to mark up the content. CSS is the presentation layer, and JavaScript adds the interactivity.
Each layer builds on the last. A web page should be able to function with just the HTML layer ― in fact, many websites celebrate “naked day” when they remove the CSS layer from their site. A website using just the HTML layer will be in its purest form and look very old school, but should still be fully functional.

Keep These Layers Separate

It is widely considered best practice to separate the concerns of each layer, so each layer is only responsible for one thing. Putting them altogether can lead to very complicated pages where all of the code is mixed up together in one file, causing “tag soup” or “code spaghetti”. This used to be the standard way of producing a website and there are still plenty of examples on the web that do this.

Unobtrusive JavaScript
When JavaScript was initially used, it was designed to be inserted directly into the HTML code, as can be seen in this example that will display a message when a button is clicked: