DEV Community

Charlie @ 90-10.dev
Charlie @ 90-10.dev

Posted on • Originally published at 90-10.dev on

Running JS in the Browser Console and Node

There are several ways to run JavaScript with the most popular being running JS inside a web page. Here we'll be looking at two other ways:

Run JavaScript in the Browser Console

All mainstream web browsers will include a powerful tool, the browser console, that allows developers to debug and troubleshoot issues on web pages by providing a way to interact with the web page's JavaScript code and examine the page's Document Object Model (DOM). This tool is especially useful for web developers who need to test and debug their code as they build web applications.

The browser console can be used to input JavaScript line-by-line and evaluate expressions in a CLI-like style.

Enable Browser Console

Here are the steps to enable your browser console - follow the steps for your browser:

  1. Google Chrome: Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac) to open the console. Alternatively, right-click on any element on the page and select "Inspect". This will open the console at the bottom of the browser window.
  2. Mozilla Firefox: Press Ctrl + Shift + K (Windows) or Cmd + Option + K (Mac) to open the console. Alternatively, right-click on any element on the page and select "Inspect Element". This will open the console at the bottom of the browser window.
  3. Microsoft Edge: Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac) to open the console. Alternatively, right-click on any element on the page and select "Inspect Element". This will open the console at the bottom of the browser window.
  4. Safari: Press Cmd + Option + C to open the console. Alternatively, go to Safari -> Preferences -> Advanced tab and check the box next to "Show Develop menu in menu bar". Then, right-click on any element on the page and select "Inspect Element". This will open the console at the bottom of the browser window.

Using the console

Once the console is open, you can start typing JavaScript right away - here is an example using the Google Chrome Browser Console.


Using the Google Chrome Browser Console

Notice that Chrome also provides auto-completion so make running JS easier.

Run JavaScript in Node.js

The second way of running JavaScript outside an HTML page is inside node.js. Once installed, open a terminal and type node. You will get a prompt allowing the input of JavaScript:

~ % node
Welcome to Node.js v16.19.0.
Type ".help" for more information.
> 

Enter fullscreen mode Exit fullscreen mode

Terminal

Each JavaScript expression will be evaluated as is entered:

> var theAnswer = 42
undefined
> console.log(theAnswer)
42
undefined
> 

Enter fullscreen mode Exit fullscreen mode

Terminal

Top comments (0)