JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
The JavaScript you use every day, for people who already know another language: running files with Node, const and let, arrows, destructuring, spread, modules, and the five things that surprise almost everyone. Every output is from a real run.
What you will learn
- Run a JavaScript file with Node and check it against its expected output
- Use const, let, arrow functions, default values, destructuring and spread
- Share code between files with export and import
- Avoid five common surprises: truthiness, == vs ===, this, module caching and the event loop order
Before you start
- Programming basics in any language (Python is fine)
If you already write Python or Java, you don't need to learn JavaScript from zero. You need the syntax you'll meet every day and a short list of places where JavaScript behaves differently from what you'd guess. This article covers both, one small file at a time.
One language, two places to run it
JavaScript runs in the browser, where it makes a page react to clicks and forms; you can type console.log("hi") into the DevTools console and see it print. It also runs on your computer with Node.js, with no browser at all. The language is the same in both places. Node is just the quickest way to run a file.
You need Node and npm (npm comes with Node). Check both in a terminal; each prints a version number. On the course machine these were Node v22.19.0, an LTS (long-term support) release, and npm 10.9.3.
node -v
npm -v
Here's the smallest example file, hello.js:
// Node reads this file from top to bottom.
const name = "Emma";
console.log(`Hello, ${name}!`);
// The second line prints after the first one.
console.log("2 + 3 =", 2 + 3);
// BREAK IT: run it from the parent folder
// -> Error: Cannot find module
// EXPECTED OUTPUT:
// Hello, Emma!
// 2 + 3 = 5
node hello.js
Hello, Emma!
2 + 3 = 5
Node reads the file top to bottom, so the lines print in order. Notice the comment at the bottom: every example file in this course ends with an EXPECTED OUTPUT block, and often a BREAK IT note with one common mistake. Run the file, compare, and you know it works. If you run it from the wrong folder you get Error: Cannot find module, so cd into the file's folder first. (Projects with a package.json need one npm install first; that's covered in npm, packages and Vite.)
const and let
// const: this name keeps its value for good
const course = "JS for coders";
// let: this name can get a new value later
let doneCount = 0;
doneCount = doneCount + 1;
console.log(course, doneCount);
// var leaks out of its block, let stays inside
for (var i = 0; i < 2; i++) {}
for (let j = 0; j < 2; j++) {}
console.log(typeof i, typeof j);
JS for coders 1
number undefined
Think of a name as a tag with an arrow pointing to a value. With const the arrow is locked: add course = "Other"; after line 2 and Node stops with TypeError: Assignment to constant variable. With let the arrow may move, so doneCount = doneCount + 1 reads 0, works out 1 and points the name at the new value.
The second line of output is the surprise. A var inside a for loop leaks out into the whole file, so typeof i is number. A let lives only inside its curly braces, so outside the loop j doesn't exist and typeof j is undefined. Use const by default, let when the value must change, and skip var.
Functions and arrow functions
// a classic function: name, parameters, return
function total(price, qty) {
return price * qty;
}
// the same job as an arrow function
const totalArrow = (price, qty) => price * qty;
console.log(total(4, 3), totalArrow(4, 3));
// map runs the arrow once for every name
const names = ["Emma", "Liam", "Sofia"];
const upper = names.map(name => name.toUpperCase());
console.log(upper, names);
// the default is used when nothing is passed
const greet = (name = "friend") => `Hello, ${name}!`;
console.log(greet("Sofia"), greet());
12 12
[ 'EMMA', 'LIAM', 'SOFIA' ] [ 'Emma', 'Liam', 'Sofia' ]
Hello, Sofia! Hello, friend!
The classic function and the arrow (price, qty) => price * qty do the same job. An arrow with no curly braces returns its expression by itself. Put braces around it, (price, qty) => { price * qty }, and it becomes a block that needs return; without one you get undefined.
map runs the arrow once per name and collects the results into a new array, leaving names untouched. (Array methods get their own article: map, filter and reduce.) And name = "friend" is a default value, used when the argument is missing.
Destructuring and spread
// one task: an object with three properties
const task = {
title: "Write report",
done: false,
owner: "Emma",
};
// destructuring: copy two values into variables
const { title, owner } = task;
console.log(title, owner);
// spread: copy every property into a NEW object
const finished = { ...task, done: true };
console.log(finished);
console.log(task.done, finished === task);
Write report Emma
{ title: 'Write report', done: true, owner: 'Emma' }
false false
const { title, owner } = task is destructuring. JavaScript finds the keys named inside the braces and copies their values into new variables. done isn't named, so it's left out. Ask for a key that doesn't exist, like colour, and there's no error; you just get undefined.
{ ...task, done: true } is spread, and it's worth taking slowly:
The braces create a new empty object. The three dots copy every property of task into it. Then done: true, written after the spread, overwrites the copied false. Write it the other way round and the copied false would win. The last line proves the original is untouched and that they are two different objects. You'll see this "copy with one change" pattern constantly, especially in React.
Arrays destructure too, by position rather than name:
// arrays destructure by position, not by name
const days = ["Mon", "Tue", "Wed"];
const [first, ...rest] = days;
console.log(first);
console.log(rest);
console.log(days.length);
Mon
[ 'Tue', 'Wed' ]
3
Here the same three dots gather instead of spread: ...rest collects what's left into a new array, and days keeps all three. The rest element must come last, or you get SyntaxError: Rest element must be last element.
Modules: export and import
A module is a file that shares some names. format.mjs exports two:
// export: other files may use these names
export const appName = "Task List";
export function label(task) {
const box = task.done ? "[x]" : "[ ]";
return `${box} ${task.title}`;
}
// import exactly the names we need
import { appName, label } from "./format.mjs";
const report = { title: "Write report", done: false };
const invoice = { title: "Send invoice", done: true };
console.log(appName);
console.log(label(report));
console.log(label(invoice));
Task List
[ ] Write report
[x] Send invoice
Only exported names cross files; box stays private inside label. The backtick string is a template string, and each ${...} drops a value in. The ./ in "./format.mjs" means "in this same folder". Drop it and Node thinks format.mjs is an installed package and fails with Cannot find package. Your own files always start with ./.
Five surprises
1. What an if treats as true
// Boolean(x) shows what an if would decide
console.log(Boolean(0), Boolean("0"), Boolean([]));
console.log(Boolean(""), Boolean(null));
false true true
false false
The falsy values are only false, 0, the empty string, null, undefined and NaN. Everything else is truthy, including the text "0" and an empty array. Python developers, note that last one: an empty list is falsy in Python but an empty array is truthy here.
2. == or ===
// == converts the types first, === does not
console.log(5 == "5");
console.log(5 === "5");
true
false
== converts the string to a number first, so 5 equals "5". === checks the type first and stops: number against string is false. Use ===.
3. this is decided by the call
const timer = {
name: "Pomodoro",
show() { return this.name; },
};
console.log(timer.show());
const lost = timer.show;
try { lost(); } catch (e) { console.log(e.message); }
const kept = timer.show.bind(timer);
console.log(kept());
Pomodoro
Cannot read properties of undefined (reading 'name')
Pomodoro
this is the object before the dot at the moment the function is called. timer.show() has timer before the dot. lost() has nothing, so this is undefined and reading name throws. bind(timer) locks this to timer. This bites most often when you pass a method as a callback.
4. A module runs only once
// the same module, imported twice
await import("./counter.mjs");
await import("./counter.mjs");
console.log("imported twice");
counter loaded
imported twice
counter.mjs prints "counter loaded" when it runs. The first import runs it and Node keeps it in its module cache; the second import gets the same cached module, so nothing runs again.
5. Why timeout prints last
setTimeout(() => console.log("timeout"), 0);
Promise.resolve().then(() => console.log("promise"));
console.log("sync");
sync
promise
timeout
The timer callback waits in the timers queue and the promise callback waits in the promises queue. Plain code runs first, so "sync" prints. When the stack is empty, promise callbacks go before timers, so even a timer of 0 comes last. Async JavaScript takes this much further.
Putting it together
// the whole lecture in one small program
const tasks = [
{ title: "Write report", done: false },
{ title: "Send invoice", done: true },
{ title: "Book travel", done: false },
];
const open = tasks.filter(t => !t.done);
const titles = open.map(({ title }) => title);
console.log(`${open.length} open:`, titles.join(", "));
2 open: Write report, Book travel
filter keeps the tasks where !t.done is true, map uses destructuring right in its parameter to keep just the title, and the template string prints the count and the joined titles.
Quick recap
| Idea | One line |
|---|---|
| Running a file | node file.js from the file's folder; compare with EXPECTED OUTPUT |
const / let | const by default, let when it changes, no var |
| Arrow function | without braces it returns its expression |
| Destructuring | names must match the object's keys; arrays go by position |
| Spread | copies into a new object; the last key wins |
| Modules | only exported names cross files; own files start with ./; a module runs once |
| Surprises | "0" and [] are truthy, use ===, this is the object before the dot, promises before timers |
Try it yourself
In app.mjs, change !t.done to t.done and predict the output before you run it. Then add an owner to each task and print "title (owner)" using destructuring in the map parameter.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
One Request, Two Answers: the Same Post as an HTML Page and as JSON
Ask a Django blog for the same post twice: once as a 12,731-byte HTML page built by a template, once as 2,976 bytes of JSON built by a serializer. Compare the headers, see who builds the page, and why the server still owns every write.
A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
Make a blog design from a prompt in Figma Make, download src.zip, unzip it with Python's zipfile module, and read the two files that matter: App.tsx with its selectedPost state and BlogCard.tsx with its props.
How a Web Page Works: HTML Tags, Elements and Attributes
A web page is a text file full of labelled pieces. Learn tags, attributes and nesting with three tiny pages, and see what breaks when an attribute or a closing tag is wrong.
Semantic HTML: header, nav, main, aside and footer as Page Landmarks
The same page written as div soup and with semantic tags looks identical, but only one gives screen readers and search engines landmarks and an outline. Plus tables, div, span and the one-main rule.
