How to Print Hello World in JavaScript
Print Hello World in JavaScript three ways: in the browser console, on a web page, and in Node.js. Each takes under a minute.
JavaScript runs in two places: the browser and Node.js. Here is the shortest working example for each, plus the one-liner every tutorial starts with.
Print to the browser console
Open any web page, press F12 (or Cmd+Option+J on a Mac) to open the developer console, and type:
console.log("Hello, World!");
Press Enter. The text appears directly below your command. console.log is the tool you will use most for checking values while you code.
Print to a web page
Create a file called index.html and paste this in:
<!doctype html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello, World!";
</script>
</body>
</html>
Double-click the file to open it in your browser. The script finds the paragraph by its id and sets its text. This is the same pattern every web app uses to put content on screen: find an element, change it.
Print with Node.js
If you have Node.js installed, create a file called hello.js containing:
console.log("Hello, World!");
Then run it from your terminal:
node hello.js
The same console.log that wrote to the browser console now writes to your terminal. That is the whole idea of Node.js: the same language, outside the browser.
Which one should you use? Use the browser console to try things quickly. Use the web page version when you want to see output in an actual page. Use Node.js when you are writing scripts, servers, or anything that does not need a browser.
More Coding how-tos
- How to Add a .gitignore File
- How to Check Which Node.js Version Is Installed
- How to Check Which Python Version Is Installed
- How to Clone a Git Repository
- How to Create a New Git Branch
- How to Create a Python Virtual Environment
- How to Install Node.js with nvm
- How to Make a Script Executable in the Terminal
- How to Print Hello World in Python
- How to Run a Local Web Server in One Command
- How to Undo the Last Git Commit