Getting Started
Running a file, printing, template literals, and the two module systems.
Run a file
Save a file and hand it to node:
console.log("Hello from Node");There is no compile step and no main function. The file runs top to bottom.
node with no arguments opens a REPL, which is useful for checking one expression:
nodeconsole.log
It takes any number of values and separates them with spaces:
console.log("a", "b", 1, true);Objects and arrays print structurally, without you formatting them:
console.log({ name: "ada", age: 36 });
console.log([1, 2, 3]);console.error writes to stderr instead of stdout, so it survives a > redirect:
console.log("plain");
console.error("to stderr");Template literals
Backticks interpolate with ${}, and the expression inside can be any JavaScript:
const name = "ada";
const age = 36;
console.log(`${name} is ${age}`);
console.log(`next year: ${age + 1}`);A backtick string can also span lines, keeping its own indentation:
const msg = `Dear ada,
your build passed.
Thanks.`;
console.log(msg);Semicolons are optional
The parser inserts them for you, so this runs:
const a = 1
const b = 2
console.log(a + b)The rule is not “end of line” — a line starting with [ or ( continues the previous
statement:
const x = 5
const value = x
[1, 2].forEach((n) => console.log(n))Comments
// A line comment.
/* A block comment
over two lines. */
const data = await Promise.resolve("ready")
console.log(data).mjs vs .cjs
JavaScript has two module systems, and the extension decides which one a file gets.
.mjs is ESM — import and export:
export function greet(name) {
return `hello ${name}`
}import { greet } from "./greet.mjs"
console.log(greet("ada")).cjs is CommonJS — require and module.exports, the older system Node shipped with:
function greet(name) {
return `hello ${name}`
}
module.exports = { greet }const { greet } = require("./greet.cjs")
console.log(greet("linus"))Mixing the keywords fails. require in an ESM file:
const fs = require("node:fs")And import in a CommonJS file:
import { greet } from "./greet.cjs"A plain .js file is CommonJS by default. "type": "module" in package.json makes it
ESM — the export below would be a SyntaxError without it:
{
"type": "module"
}export function add(a, b) {
return a + b
}
console.log(add(2, 3))Strict mode
A module is always in strict mode — you never write "use strict". Assigning to an
undeclared name is an error:
count = 10The same two lines in a CommonJS file silently create a global instead:
count = 10
console.log("assigned without declaring:", count)Its other changes are mostly about this, and land in chapter 5.