Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

JavaScript Dictionary

  1. Home
  2. JavaScript Dictionary
  3. Creating and Running .js Files

Creating and Running .js Files

This page explains how to save JavaScript code as a text file and run it. The file itself is simply a plain text file saved with a .js extension.

How to write a .js file

Write your JavaScript code in a text editor and save the file with a .js extension. Save the file using the UTF-8 character encoding.

var name = 'Ayanami Rei';
var age = 14;

console.log('Name: ' + name);
console.log('Age: ' + age);

if (age >= 18) {
    console.log('Adult.');
} else {
    console.log('Minor.');
}

Write JavaScript code directly in the text file and save it like this.

How to write comments

You can write comments (notes) in a .js file. Comments are ignored by the JavaScript engine, so they are useful for leaving descriptions or notes about the code.

SyntaxDescription
// commentA single-line comment. Write it with one space after //. Everything from // to the end of the line is a comment.
/* comment */A multi-line comment. Everything from /* to */ is a comment.
// A script that displays user information.

function greet(name, age) {
    // Receives name and age as arguments and displays the information.
    console.log('Name: ' + name);
    console.log('Age: ' + age);
}

greet('Ikari Shinji', 14);

Single-line comments (//) can be used from the middle of a line. Use /* */ for multi-line comments.

How to run (Node.js)

With Node.js, you can run .js files directly from the terminal without using a browser.

node hello.js
Output
Name: Ayanami Rei
Age: 14
Minor.

If Node.js is not installed, see Setup.

How to run (browser)

To use a .js file in a browser, load it from inside an HTML file using a <script> tag.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample</title>
</head>
<body>
    <h1>Sample Page</h1>

    <script src="hello.js"></script>
</body>
</html>

Use <script src="filename.js"></script> to load the .js file. Opening index.html in a browser will execute the JavaScript.

To check the output, use the browser developer tools. Open developer tools with F12 on Windows or Command + Option + I on macOS, then select the Console tab. The output from console.log() will be displayed there.

Summary

A .js file is simply a plain text file. You can create one by writing JavaScript code in a text editor and saving it with a .js extension. No special tools are needed.

There are two ways to run the code. With Node.js you can run it directly from the terminal; in a browser, you load it with the HTML <script> tag. Choose the approach that fits your purpose.

For recommended editors and Node.js installation instructions, see Setup.

If you find any errors or copyright issues, please .