How to run JavaScript code-snippets from Google Chrome DevTools

  • Favourite
Average Star Rating is 5 from the Total 3 Ratings

Sometimes when you see a piece of JavaScript code on a blog or on an online tutorial and wonder how can you quickly test the code on your browser! Well, the longest process is to create an HTML file and put the JavaScript code within the <script></script> tag and run the html file on a browser to see the output. (This output could be on the webpage or on the console), most cases, it may output on the console. Now to see the output you need to right click on the html page (while it is open in the browser) and select inspect and then click on the console to see the output. Well as you see, this is a long process, but what if you just want to run and test the code directly on the browser's console without going through all these previously explained steps?

Well, you are in for luck! Google Chrome DevTools allows you to create a code snippet on the browser on the go! you can even save a piece of code with a name and it will be there even if you close the browser (until you remove them permanently). In this tutorial I will show you how to:

Let's consider below-given sample JavaScript code: On this code, I have a demo function called sayHello(), once called, this function will print the word "Hello" on the console. Line 1-3 is the function definition and Line 5 is the function call. Now let's try to run this code snippet on the Google Chrome browser, I will explain it in Steps.

function sayHello(){


Step-1: Open a new Tab on your browser

Step-2: Let's use Google's home page for testing, so type

Step-3: right-click the page and select Inspect.




Step-4: Select Sources 

Step-5: Under Snippets click on New Snippets and give a name (This case I have named it testCode) and press enter.

Step-6: Now, Click on testCode, you will see a window for code in the side, paste your testing code here (see step 4 on below image)

Step-7: Now right click on the testCode snippet (see step 5 on below image) and click on 'Run' from the menu, you will see the output (Hello) on the output window below   (see step 6 on below image). 




Note: Besides the word "Hello" you also see "SW registered" above it, ignore it, this is to do with a built-in feature called Service Workers. Also below the "Hello" you will see "undefined", this is due to the default return-type of the function console.log() itself, this function returns nothing (or say it returns void), in JavaScript if a function returns nothing (void) then the default return-type is "undefined". So you can ignore this too. As you can see this is nothing to do with your code error or anything like that. Hope this will help you in the future to quickly run and test a sample code!


Be the first to make a comment!