- The NodeJS runtime
- First program (hello world)
- What Happened
A JavaScript program is just a collection of (one or more) text files, that contain commands to be executed by a JavaScript runtime.
The names of these text files usually end with a
.js file extension, like my_script.js, my_program.js etc.The commands they contain are written in the JavaScript programming language.
A JavaScript runtime is a special program that executes these files.
The NodeJS runtime
The most common JavaScript runtime is NodeJS.
Your IDE might already include it, or you might need to download it from the official website.
The download page will provide you with instructions for all three of the major OSs (Operating Systems): Windows, Linux and MacOS. It assumes you know how to open a terminal in your OS.
Since NodeJS is available for all three OSs, the programs that you write will be able to be executed on all of them (barring some edge cases).
This means you can, for example, write a simple videogame in JavaScript on your Windows PC and pass it to your friend to run it on his Mac.
First program (hello world)
Traditionally, when studying a programming language, the first program one writes consists in printing "hello world!" to the console.
Create a directory called
my_js_code/, with inside a file called main.js (these names are arbitrary).Open the directory with your code editor.
Write this code into your file:
console.log("hello world!")
Open a terminal and execute this command to run the program:
node main.js
The result should be
hello world!
What Happened
In JavaScript, everything is an "object".
console is an object, which is used to debug the program.console.log is the most used method of the console. It just prints whatever arguments you pass to it.You pass arguments to
console.log using the round brackets ().So for example, if you wanted to print the number
1000, you'd just writeconsole.log(1000)
Then execute it by running
node main.js
in your terminal (from now on, this course will assume that you know this is how you execute a program).
This should print
1000
You can pass multiple things, like
console.log(16, 8, 1993)
This will print
16 8 1993