In this JavaScript tutorial, we are going to learn the different ways to run our JavaScript program. And in the previous tutorial, we saw that JavaScript is widely used to build applications so we can run JavaScript in several ways:
- Using the browsers console tab
- Using Node.js
- By creating Web Pages
1. Using the browsers console tab
Almost every popular web browsers have built-in JavaScript engines. Where you can run JavaScript on a browser. To run JavaScript on browsers follow these steps:
i) Open your web browser (I'm using Google Chrome).
ii) Right-click on the display and select Inspect. (F12 shortcut).
iii) Now on the developer tools select the Console tab and then start writing your javascript code.
2. Using Node.js
Node is a back-end run-time environment for executing JavaScript. To run JavaScript using Node.js, follow these steps:
i) Install the latest version of Node.js on your machine.
ii) Install any IDE or Text editor like Visual Studio Code(VS Code).
iii) Create a file (index.js) and save it with the '.js' extension.
iv) Now open the terminal/command prompt and navigate to the file location.
v) Now type node index.js and press enter.
3. By Creating Web Pages
As we discussed in previous tutorials that initially JavaScript was created to make web pages. So we use HTML to run JavaScript.
And in HTML we can use JavaScript in two ways
- The first one is writing JavaScript within <script> </script> tags.
- Writing an external .js file.
Now, let's see how we can run JavaScript in an HTML document within <script> tag:
i) Open any code editor and create a file index.js
ii) Write HTML boilerplate code.
iii) Write <script> </script> before the </body> tag.
iv) Now write JavaScript code within the <script> </script>.
v) Open the index.html file in the browser.
OR
i) Open any code editor and create a file index.html and another main.js.
ii) Write HTML boilerplate code.
iii) Write <script src="main.js"> </script> before the </body> tag.
iv) Now write JavaScript code within in the main.js file.
v) Open index.html file in the browser.