Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

React
  • One Request, Two Answers: the Same Post as an HTML Page and as JSON
  • A Blog Design from a Prompt: Downloading Figma Make Code and Reading App.tsx and BlogCard.tsx
  • How a Web Page Works: HTML Tags, Elements and Attributes
  • Semantic HTML: header, nav, main, aside and footer as Page Landmarks
  • HTML Forms: Labels, Names, Input Types and Where the Data Goes (GET vs POST)
  • CSS Basics: Selectors, Which Rule Wins, and the Box Model
  • CSS Flexbox vs Grid: A Nav Bar, a Card Row and a Dashboard
  • Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
  • JavaScript for People Who Already Code: Syntax, Modules and Five Surprises
  • JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries
  • Async JavaScript: Promises, async/await, fetch and Promise.all
  • JavaScript in the Page: the DOM, querySelector and Events
  • npm, package.json and Vite: What npm install Fetches and How Vite Serves and Builds Your Page
  • TypeScript Essentials: Types Checked, Then Erased (Interfaces, Unions, Generics)
  • Why React, JSX and Components: The Page as a Function of Data
  • React Props and Composition: Data Down, Calls Up, Children in the Slot
  • Routing With React Router: One Page, Many Addresses
  • React Component Tests With Vitest and Testing Library: Test What the User Sees
  • End-to-End Tests for a React App With Playwright: A Full Dress Rehearsal
  • Why AI-Built Websites All Look the Same, and Four Levels That Fix It
  • Visual Hierarchy, Spacing and the 8-Point Grid: Tell the Eye What to Read First
  • Colour, Contrast and Dark Palettes: 60-30-10, Semantic Tokens and Ratios You Can Compute
  • Typography That Sells: Type Scale, Line Length and Free Font Pairings
  • The UI Element Catalogue: Buttons to Toasts, Their Jobs, States and shadcn/ui Names
  • Design Tokens: Primitive and Semantic Tokens, from Figma to CSS to Tailwind
  • Tailwind CSS 4 in React: Utility Classes, Responsive Prefixes, Hover and Dark Mode
  • shadcn/ui in React: Components You Own, Edit and Commit
  • Design Tokens to a Tailwind Theme: Light and Dark Mode with @theme inline
  • Motion in React: Entrance, Hover, Exit and Layout Animations
  • A React Dashboard: Stat Cards, a Recharts Line Chart and a Sortable Table
  • Accessibility in Practice: Dialogs, Menus and the Keyboard in React
  • Reference-Driven Design: Extract a DESIGN.md From a Site You Admire and Build From It
  • Components, Variants and Variables: One Design System in Figma and in CSS
  • Figma MCP Server: Build a React Component From a Frame, Then Write It Back
  • Claude Design: From a Brief to a Clickable Prototype, Then Hand It Off to Claude Code
  • Critiquing AI-Generated UI: Six Checks for Every Screen
  • The AI Design Landscape: Prompt to UI, Prompt to App, and Design to Code
  • Your Brand Rules Folder: One Folder Every AI-Built Page Follows
  • The Best-Practice UI Prompt: Plain Sentences That Beat the Average AI Page
  • UI Ideas From Figma Make, Google Stitch and ChatGPT: One Prompt, Three Designs
  • Google Stitch From a Sketch or Screenshot: Show the Layout, Say What to Keep
  • Stitch to Figma to Code: Turn a Stitch Screen Into Code That Uses Your Tokens
  • Figma Make: Prompt to Prototype With a Four-Part Prompt
  • Upgrade a Dated UI From One Screenshot (or a Reference Image)
  • States and Feedback: Make Every Click Get an Answer
  • A Design-Loop Skill: Claude Screenshots, Scores and Fixes Its Own UI
  • Copy Without the AI Tells: A Copy Pass on a Landing Page
  • React State, Events, Lists and Conditional Rendering: Follow One Click
  • React useEffect: When It Runs, What Cleanup Is For, and When You Don't Need One
  • Lifting State Up, Refs and React DevTools: Put State Where It Is Needed
  • Forms and Actions in React 19: Controlled Inputs, Form Actions, useActionState and useFormStatus
  • React Context and Custom Hooks: Share One Value, Reuse the Logic
  • Server State With TanStack Query: One Key, One Request, One Cache
  • Mutations and Optimistic Updates in TanStack Query: Change Data, Then Tell the Cache
  • Generate TypeScript Types, Query Hooks and Zod From an OpenAPI Spec With Orval
  • A Mock Backend in the Browser With Mock Service Worker, Generated From the Spec
  • A React Client for a FastAPI API: The CORS Wall, CORSMiddleware and the Vite Proxy
  • Forms With React Hook Form and Zod: The API's Rules in the Browser, the Server's Errors Under the Field
  • JWT Auth in a React Client With a FastAPI Backend: Log In, Carry the Token, Let the Server Decide
  1. Blog
  2. /
  3. React
  4. /
  5. Fundamentals

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Fundamentals

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:

Spread: a new empty object is created, every property of task is copied in, then done: true overwrites the copied false. task and finished are two separate objects. task title: 'Write report'done: falseowner: 'Emma' ...task copy each finished (a NEW object) title: 'Write report'done: trueowner: 'Emma' done: true written last, wins task.done is still false, and finished === task is false
Spread copies into a brand new object; the key written last wins.

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

IdeaOne line
Running a filenode file.js from the file's folder; compare with EXPECTED OUTPUT
const / letconst by default, let when it changes, no var
Arrow functionwithout braces it returns its expression
Destructuringnames must match the object's keys; arrays go by position
Spreadcopies into a new object; the last key wins
Modulesonly 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in React · 9 of 59

Previous
Responsive CSS: Viewport, Mobile-First Media Queries, clamp() and Dark Mode with Tokens
Next post
JavaScript Arrays the Functional Way: map, filter, reduce, find, sort and Object.entries

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.

On this page

  • One language, two places to run it
  • const and let
  • Functions and arrow functions
  • Destructuring and spread
  • Modules: export and import
  • Five surprises
  • 1. What an if treats as true
  • 2. == or ===
  • 3. this is decided by the call
  • 4. A module runs only once
  • 5. Why timeout prints last
  • Putting it together
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.