JavaScript Introduction
JavaScript is the programming language that makes web pages interactive. Where HTML gives a page structure and CSS gives it style, JavaScript gives it behavior: it reacts to clicks, validates forms, updates content without reloading, fetches data from servers, and even powers entire applications on the server through Node.js. It is one of the most widely used programming languages in the world, and it is the only language that runs natively inside every major web browser.
This lesson introduces what JavaScript is, where it runs, how the engine underneath actually executes your code, and gets you writing your first real statements.
Overview / How It Works
JavaScript was created in 1995 by Brendan Eich at Netscape, originally in just ten days, to add scripting ability to web pages. Despite the name, it has no direct relationship to Java — the name was a marketing decision. The language is standardized under the name ECMAScript (ES) by a body called TC39, which is why you will often see version names like ES5, ES6 (ES2015), and so on. Modern JavaScript is commonly called “ES6+” and includes features like let/const, arrow functions, template literals, classes, and async/await.
JavaScript is a high-level, interpreted, dynamically-typed language. Let’s unpack each of those words, because they explain a lot of behavior you’ll see later:
- High-level means you don’t manage memory addresses or CPU registers yourself; the engine handles that for you.
- Interpreted (with JIT compilation) means your code doesn’t need a separate build step before running. In practice, modern engines like V8 (used in Chrome and Node.js) parse your code into an intermediate form and then use a Just-In-Time (JIT) compiler to turn frequently-run code into fast machine code on the fly, so “interpreted” today is really “compiled just before it runs.”
- Dynamically-typed means a variable’s type is determined at runtime and can change. The same variable can hold a number, then later a string, without declaring a type up front.
JavaScript can run in two main environments:
- The browser — every modern browser (Chrome, Firefox, Safari, Edge) has a built-in JavaScript engine (V8, SpiderMonkey, JavaScriptCore) that runs script embedded in or linked from an HTML page. Here, JavaScript can access the DOM (Document Object Model), the browser’s live representation of the page, letting it read and change what’s on screen.
- Node.js — a runtime that takes the V8 engine out of the browser and lets it run on a server or your own machine, with access to the file system, networking, and other system resources instead of the DOM. This is why JavaScript can power both a webpage’s button clicks and a backend API.
Internally, when a JavaScript engine executes your script, it does two important things you should know about from day one: it is single-threaded (it runs one line of your code at a time, in order, on one call stack) and it uses an event loop to handle things that take time — like network requests or timers — without freezing everything else. You’ll explore the event loop in depth in a later lesson, but knowing it exists now will make asynchronous code (like fetch or setTimeout) far less mysterious when you get there.
Syntax
A JavaScript program is simply a sequence of statements, usually ending in a semicolon. Here is the general shape of a few core building blocks you’ll use constantly:
let variableName = value; // a variable that can change later
const constantName = value; // a variable that cannot be reassigned
function functionName(parameter1, parameter2) {
// code to run
return result;
}
console.log(value); // prints a value to the console
| Piece | Meaning |
|---|---|
let / const |
Declares a variable. Use const by default; use let only when the value must change. |
function |
Defines a reusable block of code that can accept inputs (parameters) and produce an output (return). |
console.log() |
Prints output, most commonly to the browser’s DevTools console or the terminal in Node.js. |
; |
Ends a statement. JavaScript has “Automatic Semicolon Insertion” that can add these for you, but relying on it is a common source of bugs, so most style guides recommend writing them explicitly. |
Examples
Example 1: Your First Script
console.log("Hello, JavaScript!");
let language = "JavaScript";
console.log(`Welcome to the world of ${language}.`);
Output:
Hello, JavaScript!
Welcome to the world of JavaScript.
This example shows two core ideas: console.log() to display output, and a template literal (the text inside backticks) which lets you embed a variable directly inside a string using ${...}, instead of gluing strings together with +.
Example 2: Functions and Dynamic Typing
function describe(name, yearCreated) {
const age = 2026 - yearCreated;
return `${name} is a programming language that is ${age} years old.`;
}
let message = describe("JavaScript", 1995);
console.log(message);
message = 42;
console.log(typeof message);
Output:
JavaScript is a programming language that is 31 years old.
number
Notice that message first holds a string, then is reassigned to a number. This is what “dynamically-typed” means in practice — the same let variable can hold any type of value, and typeof tells you what type it currently holds.
Example 3: A More Realistic Program
const students = [
{ name: "Ava", score: 92 },
{ name: "Liam", score: 78 },
{ name: "Noah", score: 85 }
];
for (const student of students) {
const status = student.score >= 80 ? "Pass" : "Needs Improvement";
console.log(`${student.name}: ${student.score} (${status})`);
}
const average = students.reduce((sum, s) => sum + s.score, 0) / students.length;
console.log(`Average score: ${average.toFixed(2)}`);
Output:
Ava: 92 (Pass)
Liam: 78 (Needs Improvement)
Noah: 85 (Pass)
Average score: 85.00
This combines an array of objects, a for...of loop, a ternary operator (condition ? a : b), and the array method reduce() to compute a total. This is the kind of small, self-contained logic you’ll write constantly once you move beyond single statements — it’s real JavaScript, just at a slightly larger scale.
How It Works Step by Step (Under the Hood)
When a browser or Node.js runs your script, roughly this happens:
- 1. Parsing: The engine reads your source code as text and converts it into a tree-like structure called an Abstract Syntax Tree (AST), checking along the way that the syntax is valid. If it isn’t, you get a
SyntaxErrorbefore a single line runs. - 2. Compilation: Engines like V8 compile the AST into bytecode, and a JIT compiler watches which functions run often (“hot” code) and compiles those into optimized machine code for speed.
- 3. Execution: The engine executes your code top to bottom on a single call stack, one statement at a time. Variable declarations are processed first in a phase called hoisting, which is why function declarations can be called before they appear later in the file.
- 4. Handling async work: When your code calls something like
setTimeoutorfetch, the engine hands that work off to the browser or Node.js runtime, keeps executing the rest of your script, and only comes back to run the callback once the main script is finished and the event loop picks it up from a queue. This is why JavaScript can juggle many pending operations while still being single-threaded.
Common Mistakes
Mistake 1: Using var and being surprised by scope. Older code uses var, which is function-scoped instead of block-scoped, and this can cause a classic bug in loops:
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 0);
}
Output:
4
4
4
Because var is shared across every loop iteration, by the time the callbacks run, the loop has already finished and i is 4. The fix is to use let, which creates a fresh binding of i for each iteration:
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 0);
}
Output:
1
2
3
Mistake 2: Confusing == with ===. The == operator performs type coercion before comparing, which produces results many beginners don’t expect:
console.log(0 == "0");
console.log(0 === "0");
console.log(null == undefined);
console.log(null === undefined);
Output:
true
false
true
false
== converts the string "0" to the number 0 before comparing, so it matches. === (strict equality) never converts types, so a number and a string are never equal. Prefer === almost always, so comparisons only succeed when both the value and the type match.
Best Practices
- Default to
constfor every variable; switch toletonly when you know the value must be reassigned. Avoidvarin new code. - Use
===and!==instead of==and!=to avoid unexpected type coercion. - Use template literals (
`${value}`) instead of string concatenation with+for readability. - Give variables and functions descriptive names; JavaScript doesn’t require type annotations, so a clear name is your main documentation.
- Run your code often in small pieces while learning — use your browser’s DevTools console or run files with
node filename.jsto see results immediately. - Read error messages carefully.
SyntaxErrormeans the parser couldn’t understand your code at all; other errors likeTypeErrorhappen while the code is running.
Practice Exercises
- Exercise 1: Declare a
constvariable holding your name and aletvariable holding your current age. Use a template literal to log a sentence combining both. - Exercise 2: Write a function
square(n)that returnsnmultiplied by itself. Call it with three different numbers and log each result. - Exercise 3: Create an array of three of your favorite foods. Use a
for...ofloop to log each one with its position in the list, e.g."1: Pizza".
Summary
- JavaScript is the language that adds behavior to web pages, standardized as ECMAScript, and also runs outside the browser via Node.js.
- It is high-level, dynamically-typed, and executed by an engine that parses, compiles, and runs your code, using an event loop to manage asynchronous work while staying single-threaded.
- Use
constby default,letwhen reassignment is needed, and avoidvarin modern code. - Prefer strict equality (
===) to avoid unexpected type coercion bugs. - Template literals, functions, and array methods like
reduce()are everyday tools you’ll use in almost every script you write.
