JavaScript syntax is the set of rules that defines how JavaScript programs are constructed by the programmer and interpreted by the browser or runtime.
Statements and Semicolons
A JavaScript statement is a command told to the engine:
javascriptlet x = 10;
let y = 20;
let z = x + y;
console.log(z); // 30
Note on Semicolons: Semicolons separate JavaScript statements. While Automatic Semicolon Insertion (ASI) permits omitting them in many cases, writing explicit semicolons prevents tricky parsing edge-cases.
Case Sensitivity & Naming Conventions
JavaScript is strictly case-sensitive:
- The variables
myVariableandmyvariableare entirely distinct. - Standard convention for variables and functions is lowerCamelCase (
getUserProfile). - Classes and Constructor functions use UpperCamelCase (
DeveloperProfile). - Constants use UPPER_SNAKE_CASE (
MAX_RETRY_COUNT).
Comments
javascript// Single line comment
/*
Multi-line block comment
useful for long descriptions or documentation
*/
Strict Mode ("use strict";)
Strict mode prevents silent errors, forbids accidental globals, and prohibits problematic language features:
javascript"use strict";
x = 3.14; // Uncaught ReferenceError: x is not defined (not declared with let/const)
Interactive Quiz: Syntax
<div class=“interactive-quiz” data-answer=“2”> <div class=“quiz-question”>Which naming convention is standard for functions and variables in JavaScript?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-syn” value=“0”> <span>snake_case</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-syn” value=“1”> <span>kebab-case</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-syn” value=“2”> <span>lowerCamelCase</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-syn” value=“3”> <span>SCREAMING_SNAKE_CASE</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
In JavaScript, variables are containers for storing values. Modern JavaScript (ES6+) provides three keywords to declare variables: const, let, and the legacy var.
const vs let vs var
| Keyword | Scope | Can be Reassigned? | Can be Redeclared? | Hoisting Behavior |
|---|---|---|---|---|
const |
Block {} |
No | No | Temporal Dead Zone |
let |
Block {} |
Yes | No | Temporal Dead Zone |
var |
Function | Yes | Yes | Hoisted (initialized as undefined) |
javascript// Prefer const by default
const API_URL = "https://www.oldlane17.com";
// Use let when the value will change
let currentCount = 0;
currentCount += 1;
// Avoid var in modern code
Primitive Data Types
JavaScript has 7 primitive data types plus object:
number: Both integers and floats (e.g.,42,3.14).string: Sequence of characters ("hello",'world',`template ${val}`).boolean:trueorfalse.undefined: A declared variable that has not been assigned a value.null: Explicit representation of “no value”.bigint: Integers of arbitrary length (9007199254740991n).symbol: Unique and immutable identifier (Symbol("id")).
javascriptlet title = "Old Lane 17";
console.log(typeof title); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (historic JS quirk!)
Interactive Quiz: Variables
<div class=“interactive-quiz” data-answer=“1”> <div class=“quiz-question”>What error is thrown when trying to reassign a variable declared with ‘const’?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-var” value=“0”> <span>ReferenceError</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-var” value=“1”> <span>TypeError (Assignment to constant variable)</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-var” value=“2”> <span>SyntaxError</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-var” value=“3”> <span>No error, it reassigns silently</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
JavaScript includes a rich set of operators for performing mathematical calculations, logical assertions, and object inspections.
Strict Equality (===) vs Loose Equality (==)
Always prefer strict equality (===) over loose equality (==):
===(Strict): Checks both value and type without coercion.==(Loose): Coerces types before comparison, leading to unexpected results.
javascriptconsole.log(5 === "5"); // false (number !== string)
console.log(5 == "5"); // true (string coerced to number)
console.log(0 === false); // false
console.log(0 == false); // true
Modern Safe Operators: ?. and ??
Modern JavaScript (ES2020+) introduced two operators for safely handling null and undefined:
1. Optional Chaining (?.)
Safely accesses nested object properties without throwing TypeError: Cannot read properties of undefined:
javascriptconst user = { profile: { name: "Alice" } };
// Without optional chaining: would crash if profile were null/undefined
console.log(user?.profile?.name); // "Alice"
console.log(user?.settings?.theme); // undefined (safe!)
2. Nullish Coalescing Operator (??)
Returns the right-hand operand only if the left-hand operand is null or undefined (unlike || which also falls back on 0, "", or false):
javascriptconst userScore = 0;
// Logical OR (||) treats 0 as falsy!
const displayA = userScore || 10;
console.log(displayA); // 10 (Incorrect: 0 was a valid score!)
// Nullish Coalescing (??) preserves 0 and empty string
const displayB = userScore ?? 10;
console.log(displayB); // 0 (Correct!)
Logical Assignment Operators
javascriptlet count = 0;
count ||= 5; // count becomes 5 (since 0 is falsy)
let title = null;
title ??= "Default Title"; // title becomes "Default Title"
Interactive Quiz: Operators
<div class=“interactive-quiz” data-answer=“2”> <div class=“quiz-question”>What is the output of: null ?? ‘Fallback’ vs false || ‘Fallback’?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-ops” value=“0”> <span>‘Fallback’ and false</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-ops” value=“1”> <span>null and ‘Fallback’</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-ops” value=“2”> <span>‘Fallback’ and ‘Fallback’</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-ops” value=“3”> <span>null and false</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
Conditional statements are used to perform different actions based on different conditions.
if, else if, and else
javascriptconst hour = new Date().getHours();
let greeting;
if (hour < 12) {
greeting = "Good morning";
} else if (hour < 18) {
greeting = "Good afternoon";
} else {
greeting = "Good evening";
}
console.log(greeting);
The Ternary Operator (? :)
A clean one-liner for assigning conditional values:
javascriptconst age = 19;
const canVote = age >= 18 ? "Eligible to vote" : "Too young to vote";
console.log(canVote);
The switch Statement
When evaluating a single variable against multiple strict matching cases:
javascriptconst role = "editor";
switch (role) {
case "admin":
console.log("Full system access");
break;
case "editor":
console.log("Can edit and publish articles");
break;
case "viewer":
console.log("Read-only access");
break;
default:
console.log("Guest access");
}
Warning: Always include
break;at the end of each case; otherwise, execution will fall through to the next case automatically!
Interactive Quiz: Conditionals
<div class=“interactive-quiz” data-answer=“1”> <div class=“quiz-question”>In a switch statement, what happens if you forget to write a ‘break’ statement in a matched case?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-cond” value=“0”> <span>A SyntaxError is thrown immediately</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-cond” value=“1”> <span>Execution falls through to the next case block</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-cond” value=“2”> <span>The switch statement re-runs from the beginning</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-cond” value=“3”> <span>The default block runs instead</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
Loops execute a block of code a number of times as long as a specified condition is true.
1. The Standard for Loop
javascriptfor (let i = 0; i < 5; i++) {
console.log(`Iteration: ${i}`);
}
2. for...of (Best for Arrays and Iterables)
for...of loops over values of an iterable (Arrays, Strings, Sets, Maps):
javascriptconst frameworks = ["Vanilla JS", "Node.js", "Cloudflare Workers"];
for (const fw of frameworks) {
console.log(`Building with ${fw}`);
}
3. for...in (Best for Inspecting Object Properties)
for...in iterates over the enumerable property keys of an object:
javascriptconst serverConfig = {
host: "www.oldlane17.com",
port: 443,
ssl: true
};
for (const key in serverConfig) {
console.log(`${key}: ${serverConfig[key]}`);
}
4. Modern Array Iteration Methods
In modern JavaScript, array methods like .forEach(), .map(), and .filter() are commonly used:
javascriptconst numbers = [1, 2, 3, 4, 5];
// Map creates a new array transformed
const doubled = numbers.map(n => n * 2);
// Filter returns elements that pass test
const evens = numbers.filter(n => n % 2 === 0);
Interactive Quiz: Loops
<div class=“interactive-quiz” data-answer=“2”> <div class=“quiz-question”>Which loop structure directly iterates over the VALUES of an Array?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-loop” value=“0”> <span>for…in</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-loop” value=“1”> <span>switch…case</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-loop” value=“2”> <span>for…of</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-loop” value=“3”> <span>while…each</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
Functions are the fundamental building blocks in JavaScript. A function is a reusable procedure that takes input, performs computation, and returns a value.
Function Declarations vs Expressions
javascript// Function Declaration (hoisted)
function add(a, b) {
return a + b;
}
// Function Expression (not hoisted)
const multiply = function(a, b) {
return a * b;
};
Arrow Functions (=>)
Introduced in ES6, arrow functions offer a concise syntax and do not bind their own this:
javascript// Standard arrow function
const subtract = (a, b) => {
return a - b;
};
// Implicit return for single expressions
const square = x => x * x;
// Returning an object literal directly requires wrapping parentheses ({})
const makeUser = (name, role) => ({ name, role });
Rest Parameters & Default Values
javascript// Default parameter value
function formatMessage(msg, prefix = "INFO") {
return `[${prefix}] ${msg}`;
}
// Rest parameters: collects extra arguments into a real Array
function sumAll(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
console.log(sumAll(10, 20, 30)); // 60
Closures in JavaScript
A closure is the combination of a function bundled together with references to its surrounding lexical environment:
javascriptfunction createCounter(initialValue = 0) {
let count = initialValue;
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
}
const counter = createCounter(10);
console.log(counter.increment()); // 11
console.log(counter.increment()); // 12
console.log(counter.getValue()); // 12
Interactive Quiz: Functions
<div class=“interactive-quiz” data-answer=“1”> <div class=“quiz-question”>How does an arrow function handle the ‘this’ keyword compared to regular functions?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-fn” value=“0”> <span>It binds ‘this’ dynamically to the caller</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-fn” value=“1”> <span>It lexically inherits ‘this’ from the enclosing execution scope</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-fn” value=“2”> <span>It always sets ‘this’ to null</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-fn” value=“3”> <span>It creates a new global ‘this’</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
Objects in JavaScript are collections of key-value pairs where keys are strings (or Symbols) and values can be any data type.
Object Literals & Shorthand
javascriptconst name = "Old Lane 17";
const year = 2026;
// Property shorthand
const site = {
name,
year,
// Method shorthand
describe() {
return `${this.name} (${this.year})`;
}
};
console.log(site.describe());
Destructuring & Spread Syntax
javascriptconst config = { host: "localhost", port: 8788, ssl: false, debug: true };
// Object Destructuring with default values
const { host, port, protocol = "http" } = config;
// Spread syntax for shallow copying and merging
const productionConfig = {
...config,
host: "www.oldlane17.com",
ssl: true
};
ES6 Classes
ES6 classes provide a clean, syntax-sugar layer over JavaScript’s prototype-based inheritance:
javascriptclass Article {
constructor(title, author) {
this.title = title;
this.author = author;
this.likes = 0;
}
like() {
this.likes += 1;
return this.likes;
}
}
class TutorialArticle extends Article {
constructor(title, author, language) {
super(title, author);
this.language = language;
}
getSummary() {
return `"${this.title}" (${this.language}) by ${this.author}`;
}
}
const post = new TutorialArticle("Python Decorators", "Old Lane 17", "Python");
console.log(post.getSummary());
Interactive Quiz: Objects
<div class=“interactive-quiz” data-answer=“2”> <div class=“quiz-question”>Which syntax extracts the ‘title’ property from an object ‘article’ into a local variable?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-obj” value=“0”> <span>const [title] = article;</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-obj” value=“1”> <span>const title <- article;</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-obj” value=“2”> <span>const { title } = article;</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-obj” value=“3”> <span>const title = extract(article);</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>
Welcome to the Old Lane 17 JavaScript Tutorial. JavaScript is the programming language of the Web. It powers dynamic user interfaces in the browser, modern server runtimes via Node.js, and desktop/mobile applications.
Why Learn JavaScript?
- Ubiquitous: Every modern browser runs JavaScript natively without plugins.
- Full Stack Capability: Use JavaScript on both client (frontend) and server (Node.js / Cloudflare Workers).
- Vast Ecosystem: Access millions of open-source packages via npm.
javascript// Modern JavaScript (ES6+)
const greet = (name) => {
return `Hello, ${name}! Welcome to Old Lane 17.`;
};
const users = ["Alice", "Bob", "Charlie"];
users.forEach(user => console.log(greet(user)));
Tutorial Curriculum Overview
Navigate through the core foundations using the sidebar on the left:
| Topic | What You Will Learn |
|---|---|
| Syntax | Semicolons, statements, identifiers, comments, and strict mode |
| Variables & Types | const, let, var, primitives (string, number, boolean, symbol, bigint) |
| Operators | Arithmetic, comparison, strict equality ===, nullish coalescing ?? |
| Conditionals | if, else, ternary ? :, and switch statements |
| Loops | for, while, for...of, for...in, and functional iteration |
| Functions | Declarations, expressions, arrow functions, closures, and scope |
| Objects & Classes | Object literals, destructuring, spread syntax, prototypes, and ES6 classes |
Interactive Quiz
Test your JavaScript foundations:
<div class=“interactive-quiz” data-answer=“1”> <div class=“quiz-question”>Which keyword should be your default choice for declaring variables that do not get reassigned in modern JavaScript?</div> <div class=“quiz-options”> <label class=“quiz-option”><input type=“radio” name=“quiz-js-intro” value=“0”> <span>var</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-intro” value=“1”> <span>const</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-intro” value=“2”> <span>let</span></label> <label class=“quiz-option”><input type=“radio” name=“quiz-js-intro” value=“3”> <span>def</span></label> </div> <button class=“btn quiz-check-btn” type=“button”>Check Answer</button> <div class=“quiz-feedback” aria-live=“polite”></div> </div>