This blog will demonstrate the ways to run the code written in JavaScript.
How to Run JavaScript Code?
To run your code written in JavaScript, use the following ways/solutions:
Solution 1: Run JavaScript Code on Browser Console
You can run your JavaScript code on the browser console. To do so, press the “F12” key or the “Ctrl + Shift + I”:
Enter your code and press the “Enter” key. Let’s see an example, to run the code on the browser console.
Create a variable “message” and store a string in it:
Print the message by calling the “console.log()” method:
After executing the above code, the output will be as follows:
You can also perform arithmetic operations in JavaScript on the console. Create two variables “x” and “y” and store values “25” and “5” respectively:
var y = 5;
Multiply “x” and “y” using the operator “*” and store the result in the variable “product”:
Print the resultant value on the console:
Output
Note: If you have a JavaScript code file with “.js” extension, then move to the second solution.
Solution 2: Run JavaScript Code Linking with HTML File
You can also run the JavaScript code by linking it with the HTML file using the <script> tag with the “src” attribute in the <head> tag:
We have written the following code in the “JSfile.js” and linked it in a <head> tag of an HTML file.
For printing message on the console:
console.log(message);
For finding the product of two numbers “25” and “5”:
var x = 25;
var y = 5;
var product = x * y;
console.log("Product of 25 and 5 is " + product);
It can be seen that the code has been successfully executed by linking the JS file with the HTML file:
Note: You can also run your JavaScript code using different frameworks and also you can run it from the “Node.js” command-line interface.
Conclusion
To run the JavaScript code, you can use online editors, such as “CodePen” or also use the browser console. You can link or attach your JavaScript file with the HTML file or use the “Node.js” command-line interface. This blog demonstrated different ways to run JavaScript code.