There are two ways we can try Javascript. Either using a Javascript REPL (REPL stands for read-eval-print loop, which means a 'shell' or 'console' like interface where you can write code line by line, and the interpreter interprets each line before you move to the next), or by writing a .js script file, and running it.
Originally, Javascript was a browser-only language. And all web browsers support executing Javascript. You have two options -
Open the console of your browser. The shortcut would be the following -
Browser | Windows / Linux | Mac OS |
---|---|---|
Firefox | Ctrl + Shift + K | Cmd + Shift + K |
Chrome | Ctrl + Shift + J | Cmd + Opt + J |
In a folder save two files - index.html
and script.js
In the index.html
file, write the following code -
<html>
<head>
<script src="script.js"></script>
</head>
</html>
Then write your Javascript code in the script.js
file, and then open the index.html
file in a browser. Open the Web console if you want to see the output of your code.
We can also use Node.JS to run Javascript directly on a computer without having to use a Browser. Once Nodejs is installed we can do one of the following
Just enter the following command in your terminal
node
And that would bring to you the NodeJS REPL.
Running a script with Nodejs is straight forward. Save your Javascript code in a script.js
file, and then, from the same folder, in a terminal run -
node server.js