What is JavaScript?
JavaScript is the programming language of the web. It runs in your browser and makes websites interactive.
In simple terms
What is JavaScript?
Imagine a website is like a house. HTML builds the walls and rooms. CSS paints and decorates it. But JavaScript is what makes the lights turn on, the doors open, and the TV remote actually work!
JavaScript is a programming language that lives inside your web browser. Every time you click a button and something happens, or a countdown timer ticks, or a form tells you "hey, fill in your email!" - that's JavaScript doing its job.
Here's a tiny taste of what JavaScript looks like:
alert("Hello! I am JavaScript! ");
If you put that in a webpage and open it, a little popup box will say hello. That's your first JavaScript program!
JavaScript can also do maths:
console.log(2 + 2); // prints 4
Or remember things:
let myName = "Alex"; console.log("Hi, " + myName + "!");
JavaScript runs right inside your browser - no special programs needed. Open any webpage, press F12, click "Console", and you can type JavaScript right now!
Deep dive
JavaScript: Technical Overview
JavaScript (officially ECMAScript) is a high-level, interpreted, dynamically-typed, prototype-based, multi-paradigm programming language. It is one of the three core technologies of the web alongside HTML and CSS.
Key Characteristics
- Interpreted / JIT-compiled: Modern engines (V8 in Chrome/Node, SpiderMonkey in Firefox) use Just-In-Time compilation for near-native performance. There is no separate compile step for the developer.
- Dynamic typing: Variable types are resolved at runtime. A variable can hold a string, then a number, then an object.
- Prototype-based inheritance: Unlike classical OOP languages, JavaScript objects inherit directly from other objects via the prototype chain.
- First-class functions: Functions are values - they can be assigned to variables, passed as arguments, and returned from other functions.
- Single-threaded with an event loop: JavaScript runs on one thread but handles asynchronous operations (I/O, timers, network) via the event loop and callback queue.
- Multi-paradigm: Supports imperative, object-oriented, and functional programming styles.
Where JavaScript Runs
- Browser (client-side): Manipulates the DOM, handles events, communicates with APIs. Each browser ships its own JS engine.
- Server (Node.js): V8 engine extracted from Chrome, runs JS outside the browser for backend services, CLIs, and tooling.
- Edge / Serverless: Cloudflare Workers, Deno Deploy, and similar platforms run JS at network edge nodes.
- Native apps: React Native, Electron, and NativeScript use JS to build desktop and mobile applications.
ECMAScript Versions
The language is standardised by ECMA International as ECMAScript. Major milestones include ES5 (2009), ES6/ES2015 (arrow functions, classes, modules), and annual releases from ES2016 onward. MDN Web Docs is the definitive reference: MDN JavaScript.
The Event Loop
JavaScript's concurrency model is built around an event loop. The call stack executes synchronous code. Asynchronous callbacks (setTimeout, fetch, etc.) are placed in the task queue or microtask queue and processed when the call stack is empty. This is why JavaScript can handle network requests without blocking the UI thread.
Challenge
Challenge: Your JavaScript Fingerprint
Open the editor below and write JavaScript that does all three of the following:
- Stores your name in a variable called
myName. - Stores your favourite number in a variable called
favouriteNumber. - Prints a sentence to the console using both variables, like: "Hi, I'm Alex and my favourite number is 7!"
Use console.log() to print.
Summary
- JavaScript is the programming language of the web - it makes pages interactive and dynamic.
- It runs directly in the browser with no installation needed; every browser ships a JS engine.
- JavaScript is also used on servers (Node.js), in mobile apps, and on the desktop.
- The language is standardised as ECMAScript and updated annually with new features.
- JavaScript is single-threaded but handles async work through the event loop and callback/microtask queues.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Your First Program
Every programmer starts somewhere. Let's write your first JavaScript program and understand exactly what's happening.
In simple terms
Your First Program
Every programmer in history had a "first program". Yours starts right now!
The most famous first program is called "Hello, World!". It just prints those words. Simple, but it proves the machine is listening.
In JavaScript, we use console.log() to print things:
console.log("Hello, World!");
Think of console.log like a walkie-talkie. You speak into it, and the browser's console (a special secret panel) hears you and repeats what you said.
You can print numbers too:
console.log(100); console.log(3.14);
Or do maths directly:
console.log(10 + 5); // 15 console.log(20 - 8); // 12 console.log(6 * 7); // 42
The // part is called a comment. JavaScript ignores everything after // on that line. It's like a sticky note for you or other programmers.
You can also use alert() to pop up a message box in the browser:
alert("I just wrote JavaScript!");
But programmers mostly use console.log() because it doesn't interrupt the user.
Deep dive
console.log(), Comments, and Program Structure
The Console Object
console is a globally available object in both browser and Node.js environments. Its most-used method is console.log(), which writes output to the developer console. Other useful methods include:
console.error() - outputs to stderr, styled red in DevTools. console.warn() - outputs a warning with a yellow indicator. console.table() - renders arrays or objects as a table. console.time() / console.timeEnd() - measures execution time. console.group() / console.groupEnd() - groups related output.
Reference: MDN Console API.
Statements and Semicolons
JavaScript programs are made up of statements - instructions executed one at a time, top to bottom. Statements are separated by semicolons (;). JavaScript has Automatic Semicolon Insertion (ASI), meaning semicolons are optional in many cases, but omitting them can cause subtle bugs. Best practice is to always include them.
Comments
JavaScript supports two comment styles:
// Single-line comment - everything after // is ignored /* Multi-line comment spans multiple lines used for longer explanations */
Comments are stripped by the JS engine before execution and have zero performance impact. Use them to explain why, not what - the code itself shows what it does.
Strict Mode
Adding "use strict"; at the top of a script or function opts into strict mode, which disables some legacy behaviours (e.g., using undeclared variables throws a ReferenceError instead of silently creating a global). ES6 modules are strict by default.
"use strict"; x = 5; // ReferenceError: x is not defined
Challenge
Challenge: Console Calculator
Using only console.log(), print the answers to all five of these calculations:
- 100 plus 250
- 1000 minus 337
- 12 multiplied by 12
- 144 divided by 12
- 2 to the power of 10 (hint: use
**)
Add a comment above each line explaining what the calculation is.
Summary
console.log() is the primary tool for printing output during development. - JavaScript programs execute statements top to bottom; semicolons separate statements.
- Single-line comments use
//; multi-line comments use /* ... */. - The console object has many methods beyond log: error, warn, table, time, and more.
- "use strict" enables stricter parsing and error handling - a good habit for all scripts.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Variables
Variables store information so your program can remember and reuse it.
In simple terms
Variables: Boxes for Your Data
Imagine your brain is a bedroom with lots of labelled boxes. You put things in boxes so you can find them later. In JavaScript, variables are those boxes!
You create a variable with let or const:
let age = 10; const planet = "Earth";
Now age holds the number 10, and planet holds the word "Earth".
The difference:
- let - you can change the value later (like a whiteboard )
- const - the value is locked forever (like engraving in stone )
let score = 0; score = 5; // fine - let allows changes score = 10; // still fine const pi = 3.14159; pi = 3; // ERROR - const cannot be changed
Variable names must start with a letter, $, or _. No spaces! Use camelCase for names with multiple words:
let myFavouriteColour = "blue"; let numberOfCats = 3;
Use const by default. Only switch to let if you know the value needs to change.
Deep dive
Variables: let, const, and var
let
let declares a block-scoped variable that can be reassigned. It is not accessible before its declaration in the code (the temporal dead zone).
let count = 0; count = count + 1; // reassignment is allowed
const
const declares a block-scoped binding that cannot be reassigned. Note: for objects and arrays, the binding is immutable but the contents are mutable:
const user = { name: "Alice" }; user.name = "Bob"; // mutating the object is fine user = {}; // TypeError: Assignment to constant variable
var (legacy)
var is function-scoped (not block-scoped), is hoisted to the top of its scope, and can be re-declared. These behaviours cause subtle bugs and var is avoided in modern code. Always prefer let or const. Reference: MDN var.
Hoisting
var declarations are hoisted and initialised to undefined. let and const are hoisted but remain in the temporal dead zone (TDZ) - accessing them before declaration throws a ReferenceError.
Naming Conventions
- Use camelCase for variables and functions:
totalPrice, getUserName. - Use UPPER_SNAKE_CASE for true constants:
MAX_RETRIES. - Use PascalCase for classes and constructors:
UserProfile. - Identifiers may contain letters, digits,
$, and _, but cannot start with a digit.
Block Scope
{ let x = 10; const y = 20; } console.log(x); // ReferenceError - x is not defined outside the block
Challenge
Challenge: Student Report Card
Create a mini report card using variables:
- Use
const to store a student's name. - Use
let to store their score (start it at 0). - Update the score to 87.
- Use
const to store the subject name. - Print a sentence like: "Alice scored 87 in Mathematics."
Summary
let creates a block-scoped variable that can be reassigned. const creates a block-scoped binding that cannot be reassigned - prefer it by default. var is function-scoped, hoisted, and should be avoided in modern JavaScript. - For objects declared with
const, the reference is locked but properties can still be mutated. - Use camelCase for variable names; keep names descriptive and meaningful.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Data Types
JavaScript has several built-in data types. Understanding them is fundamental to writing correct code.
In simple terms
Data Types: Different Kinds of Information
Not everything is the same! A name is different from a number, which is different from yes/no. JavaScript knows this - it has different data types for different kinds of information.
The main ones you'll use every day:
- Number - any number:
42, 3.14, -100 - String - text in quotes:
"hello", 'world' - Boolean - just true or false:
true, false - Undefined - a variable exists but has no value yet
- Null - intentionally empty / "nothing here"
- Object - a collection of related data
- Array - a list of items (technically an object)
let age = 25; // Number let name = "Jordan"; // String let isLoggedIn = true; // Boolean let score; // Undefined (no value assigned) let pet = null; // Null (deliberately empty)
You can check what type something is with typeof:
console.log(typeof 42); // "number" console.log(typeof "hello"); // "string" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined"
JavaScript figures out types automatically - you don't have to label them. This is called dynamic typing.
Deep dive
JavaScript's Type System
Primitive Types (7 total)
Primitives are immutable values stored directly on the stack. They are compared by value.
- Number: IEEE 754 double-precision float. All numbers share one type: integers and floats. Range: -(253-1) to 253-1 for safe integers (
Number.MAX_SAFE_INTEGER). Special values: Infinity, -Infinity, NaN. - BigInt: Arbitrary-precision integers. Append
n: 9007199254740993n. - String: Immutable sequence of UTF-16 code units.
- Boolean:
true or false. - Undefined: A variable that has been declared but not assigned.
- Null: Explicitly assigned to represent "no value".
typeof null === "object" is a historical bug in the spec. - Symbol: Unique, immutable identifier. Used for object property keys to avoid collisions:
Symbol("id").
Object Type
Objects (including arrays, functions, dates, maps, sets, etc.) are stored on the heap. Variables hold a reference to the object - two variables can point to the same object.
const a = { x: 1 }; const b = a; b.x = 99; console.log(a.x); // 99 - same object in memory
typeof Operator
typeof returns a string describing the type. Notable quirks: typeof null === "object" and typeof function(){} === "function" (functions are objects but get their own typeof result). Reference: MDN typeof.
Type Checking Beyond typeof
Array.isArray(value) - reliable array check. value instanceof Constructor - checks prototype chain. Object.prototype.toString.call(value) - most precise type tag.
Challenge
Challenge: Type Detective
Declare one variable for each of the following types and use console.log(typeof ...) to confirm the type:
- A whole number
- A decimal number
- A piece of text (your city name)
- A boolean
- A variable you declare but never assign
- A variable explicitly set to
null
Print each variable and its type together, like: "city is of type string".
Summary
- JavaScript has 7 primitive types: Number, BigInt, String, Boolean, Undefined, Null, and Symbol.
- Objects (including arrays and functions) are reference types - stored on the heap.
typeof returns a string label for a value's type, with the quirk that typeof null === "object". - JavaScript is dynamically typed - a variable can hold any type and change type at runtime.
- Use
Array.isArray() to reliably detect arrays, as typeof [] returns "object".
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Strings & String Methods
Strings hold text. JavaScript gives you a rich set of built-in methods to search, transform, and manipulate them.
In simple terms
Strings: Working with Text
A string is just a piece of text. You wrap it in quotes - single ', double ", or backticks `:
let greeting = "Hello!"; let name = 'Alice'; let sentence = `The sky is blue.`;
You can join (concatenate) strings with +:
let full = "Hello, " + "World!"; console.log(full); // Hello, World!
Strings have superpowers called methods. Think of them as tools built into every string:
let word = "javascript"; console.log(word.length); // 10 console.log(word.toUpperCase()); // JAVASCRIPT console.log(word.includes("java")); // true console.log(word.slice(0, 4)); // java
Some more handy ones:
let message = " hello world "; console.log(message.trim()); // "hello world" console.log(message.replace("world","JS")); // " hello JS " console.log("apple,banana,cherry".split(",")); // ["apple","banana","cherry"]
Strings also have indexes - each character has a position starting at 0:
let s = "cat"; console.log(s[0]); // c console.log(s[1]); // a console.log(s[2]); // t
Deep dive
Strings: Deep Dive
String Primitives vs String Objects
String literals are primitives, but when you access a method, JavaScript auto-boxes them into a temporary String wrapper object, executes the method, then discards the wrapper. This is transparent to the developer. Avoid new String() - it creates an object, not a primitive, causing unexpected equality results.
Immutability
Strings are immutable. Methods return new strings; they never modify the original:
const s = "hello"; s.toUpperCase(); // returns "HELLO" but s is still "hello"
Essential String Methods
str.length - number of UTF-16 code units (be careful with emoji/surrogate pairs). str.charAt(i) / str[i] - character at index. str.indexOf(sub) / str.lastIndexOf(sub) - first/last occurrence, returns -1 if not found. str.includes(sub) - boolean, ES2016+. str.startsWith(sub) / str.endsWith(sub) - position-aware checks. str.slice(start, end) - extracts substring; negative indices count from end. str.substring(start, end) - similar to slice but treats negatives as 0. str.toUpperCase() / str.toLowerCase() - case conversion. str.trim() / str.trimStart() / str.trimEnd() - remove whitespace. str.replace(search, replacement) - replaces first match (or all with regex /g). str.replaceAll(search, replacement) - replaces all occurrences (ES2021). str.split(separator) - splits into array. str.padStart(len, char) / str.padEnd(len, char) - pad to a target length. str.repeat(n) - repeat the string n times. str.at(i) - like bracket notation but supports negative indices (ES2022).
Template Literals
Backtick strings allow embedded expressions and multi-line content:
const name = "Alice"; const msg = `Hello, ${name}! You have ${3 + 2} messages.`;
Reference: MDN String.
Challenge
Challenge: String Transformer
Given the string " Learn JavaScript with CodeHub! ":
- Trim the whitespace from both ends.
- Convert the result to uppercase.
- Check if it includes the word "CODEHUB" (it should after step 2).
- Replace "CODEHUB" with "YOU".
- Print the final string and its length.
Summary
- Strings are immutable sequences of UTF-16 characters; methods return new strings, never mutate.
- Access characters by index (
str[0]) and measure length with str.length. - Key methods:
toUpperCase, toLowerCase, trim, slice, includes, replace, split. - Template literals (backticks) allow string interpolation with
${expression} and multi-line strings. - Auto-boxing wraps primitives in temporary String objects when methods are accessed - avoid
new String().
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Numbers & Math
JavaScript has one number type for both integers and decimals, plus a built-in Math object packed with useful functions.
In simple terms
Numbers & the Math Toolbox
JavaScript uses one type for all numbers - whether they're whole or have decimal points:
let apples = 10; let price = 2.99; let temperature = -5;
Basic maths operations:
console.log(10 + 3); // 13 console.log(10 - 3); // 7 console.log(10 * 3); // 30 console.log(10 / 3); // 3.3333... console.log(10 % 3); // 1 (remainder) console.log(2 ** 8); // 256 (power)
The % operator gives the remainder after division. It's great for checking if a number is even or odd:
console.log(8 % 2); // 0 - even! console.log(7 % 2); // 1 - odd!
JavaScript has a built-in Math toolbox:
console.log(Math.round(4.7)); // 5 console.log(Math.floor(4.9)); // 4 (always rounds down) console.log(Math.ceil(4.1)); // 5 (always rounds up) console.log(Math.abs(-42)); // 42 (removes the minus) console.log(Math.max(3,7,2)); // 7 console.log(Math.min(3,7,2)); // 2 console.log(Math.random()); // random number between 0 and 1
Random integer between 1 and 10:
let roll = Math.floor(Math.random() * 10) + 1; console.log(roll);
Deep dive
Numbers: IEEE 754 and the Math Object
IEEE 754 Double Precision
JavaScript's Number type is a 64-bit IEEE 754 floating-point. This gives about 15–17 significant decimal digits of precision. Consequence: floating-point arithmetic can be imprecise:
console.log(0.1 + 0.2); // 0.30000000000000004
For financial/exact arithmetic use integer arithmetic (e.g., cents instead of dollars), or a library like decimal.js. Reference: MDN Number.
Special Number Values
Infinity / -Infinity - result of dividing by zero or overflow. NaN (Not a Number) - result of invalid arithmetic like "abc" * 2. NaN !== NaN is true; use Number.isNaN() to test for it. Number.MAX_SAFE_INTEGER = 253-1. Beyond this, integer arithmetic becomes unreliable. Use BigInt for larger values.
Number Conversion
Number("42") // 42 Number("") // 0 Number("abc") // NaN parseInt("42px") // 42 parseFloat("3.14") // 3.14 parseInt("0xFF", 16) // 255 (hex)
Math Object (selected methods)
Math.round(x) - nearest integer; .5 rounds up. Math.floor(x) / Math.ceil(x) - round down / up. Math.trunc(x) - removes fractional part (no rounding). Math.abs(x) - absolute value. Math.sqrt(x) / Math.cbrt(x) - square/cube root. Math.pow(base, exp) - same as **. Math.max(...values) / Math.min(...values) - spread an array with Math.max(...arr). Math.random() - uniform float in [0, 1). Not cryptographically secure; use crypto.getRandomValues() for security. Math.PI, Math.E, Math.LN2 - mathematical constants.
Challenge
Challenge: Dice Simulator
Write a program that simulates rolling two six-sided dice:
- Generate a random integer between 1 and 6 for die 1.
- Generate a random integer between 1 and 6 for die 2.
- Print each die's result.
- Print the total of both dice.
- Print whether the total is greater than 7 (use a boolean).
Summary
- JavaScript uses IEEE 754 64-bit floating-point for all numbers - both integers and decimals share one type.
- Floating-point arithmetic is sometimes imprecise; use integer arithmetic or decimal libraries for money.
- Special values:
NaN, Infinity, -Infinity; use Number.isNaN() not == NaN. - The
Math object provides round, floor, ceil, abs, sqrt, max, min, random, and many more. Math.random() returns [0,1); multiply and floor to get random integers in a range.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Booleans, null & undefined
Booleans represent yes/no values. null and undefined represent the absence of a value.
In simple terms
Booleans, null & undefined
A boolean is like a light switch - it is either on (true) or off (false). Just two options!
let isRaining = false; let hasHomework = true;
Booleans appear when asking questions:
console.log(5 > 3); // true console.log(5 < 3); // false console.log(5 === 5); // true
undefined means a variable exists but has no value assigned yet:
let x; console.log(x); // undefined
null means intentionally empty - you deliberately put nothing there:
let selectedUser = null;
Every value in JavaScript is either truthy or falsy. The falsy values are: false, 0, "", null, undefined, and NaN. Everything else is truthy!
Deep dive
Booleans, null, undefined: Technical Detail
Boolean
The Boolean type has exactly two values: true and false. Use Boolean(value) or !!value to coerce any value to boolean. Comparison and logical operators produce booleans.
undefined
A declared but uninitialised variable holds undefined. Functions without an explicit return yield undefined. Accessing a missing object property returns undefined. typeof undefined === "undefined".
null
null is a deliberate absence of value and must be explicitly assigned. The well-known quirk: typeof null === "object" is a historical bug that cannot be fixed. Use strict equality: value === null.
Falsy Values (exactly 8)
false, 0, -0, 0n, "", null, undefined, NaN
Truthy examples: [], {}, "0", -1.
Nullish Coalescing (??)
const port = userPort ?? 3000; const count = 0 ?? 42; // 0 - because 0 is not null/undefined
Optional Chaining (?.)
const city = user?.address?.city; // undefined if intermediate is null/undefined
Reference: MDN Nullish coalescing, MDN Optional chaining.
Challenge
Challenge: Truthiness Table
For each value below, predict truthy or falsy then verify with Boolean(value):
01"""false" null[]NaN-1
Print each value and its boolean result on one line.
Summary
- Booleans have exactly two values: true and false; comparison operators produce them.
undefined means declared but never assigned a value. null is an intentional no-value marker that must be explicitly set. - The 8 falsy values: false, 0, -0, 0n, empty string, null, undefined, NaN.
- Use
?? for null-safe fallbacks and ?. for safe nested property access.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Operators
Operators perform actions on values: arithmetic, comparison, logical, assignment, and more.
In simple terms
Operators: The Action Heroes
Operators are symbols that do things to values. You already know +, -, *, /. Here are the rest!
Comparison operators return true or false:
console.log(5 === 5); // true console.log(5 !== 3); // true console.log(5 > 3); // true console.log(5 < 3); // false console.log(5 >= 5); // true
Always use === not ==. Triple equals checks value AND type:
console.log(5 == "5"); // true (dangerous!) console.log(5 === "5"); // false (correct!)
Logical operators:
console.log(true && false); // false (AND - both must be true) console.log(true || false); // true (OR - one must be true) console.log(!true); // false (NOT - flips it)
Assignment shortcuts:
let n = 10; n += 5; // 15 n -= 3; // 12 n *= 2; // 24 n++; // 25
Deep dive
Operators: Technical Reference
Arithmetic
+ - * / % (modulo) ** (exponentiation). Unary + converts to number; unary - negates.
Strict vs Loose Equality
Strict equality (===) checks value and type with no type coercion. Loose (==) has complex coercion rules. Always use ===. Reference: MDN Strict equality.
Logical Operators
&& returns the first falsy operand or the last operand if all truthy (short-circuit). || returns the first truthy operand or the last if all falsy. ! coerces to boolean and inverts. ?? returns right only if left is null/undefined.
const name = user.name || "Anonymous"; const port = userPort ?? 3000;
Logical Assignment (ES2021)
a &&= b; // a = a && b a ||= b; // a = a || b a ??= b; // a = a ?? b
Bitwise Operators
& | ^ ~ << >> >>> operate on 32-bit integers. Useful for flags and bitmasks.
Operator Precedence
Use parentheses to make intent clear. Full table: MDN Operator Precedence.
Challenge
Challenge: Grade Calculator
Three test scores: 72, 85, 91.
- Calculate the average.
- Check if average >= 80.
- Check if ALL scores are above 70 (use &&).
- Check if ANY score is above 90 (use ||).
- Print all four results with labels.
Summary
- Always use === for equality - it tests value and type without coercion surprises.
- && and || return operand values enabling short-circuit evaluation.
- ?? provides null-safe fallback; || falls back on any falsy value including 0 and empty string.
- Compound assignment operators (+=, -=, etc.) are shorthand for reassignment.
- Use parentheses to make operator precedence explicit and code readable.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Type Coercion & Conversion
JavaScript automatically converts between types in certain situations. Understanding this prevents bugs.
In simple terms
Type Coercion: JavaScript Magic Tricks
Sometimes JavaScript converts types automatically. This is called type coercion. Sometimes handy - sometimes very confusing!
console.log("5" + 3); // "53" (not 8 - string concat!) console.log("5" - 3); // 2 (subtraction coerces to number)
+ with a string joins them. All other math operators coerce strings to numbers.
Explicit conversion is always safer:
let age = Number("25"); // 25 let price = parseFloat("3.99"); // 3.99 let text = String(42); // "42" let bool1 = Boolean(0); // false let bool2 = Boolean("hello"); // true let bool3 = !!null; // false
Golden rule: when in doubt, convert explicitly. Never rely on automatic conversion!
Deep dive
Type Coercion: The Full Picture
Implicit Coercion
Governed by ECMAScript abstract operations: ToPrimitive, ToNumber, ToString, ToBoolean. These rules are extensive and sometimes counterintuitive.
The + Operator Dual Role
If either operand is a string, + performs concatenation. Otherwise numeric addition. This is why "" + 1 === "1" but 1 - "" === 1.
Abstract Equality Coercion Quirks
null == undefined // true null == 0 // false [] == false // true "" == false // true [] == ![] // true
Avoid == entirely. Always use ===.
Explicit Conversion
Number(x): empty string -> 0, null -> 0, undefined -> NaN. parseInt(str, 10): always specify radix 10 for decimal. parseFloat(str): parses decimal numbers. String(x): calls toString. Boolean(x): explicit ToBoolean.
Object-to-Primitive
Uses [Symbol.toPrimitive], then valueOf(), then toString().
Reference: MDN Type Coercion.
Challenge
Challenge: Safe Converter
Write a function safeAdd(a, b) that converts both args to numbers, returns "Invalid input" if either is NaN, otherwise returns the sum. Test with: safeAdd("5","3"), safeAdd("hello",2), safeAdd(10,20).
Summary
- Type coercion is automatic conversion triggered by operators like == and +.
- The + operator concatenates if either operand is a string; other arithmetic coerces to number.
- Abstract equality (==) has complex coercion rules - always use ===.
- Explicit conversion with Number(), String(), Boolean(), parseInt() is always safer.
- NaN results from invalid numeric conversion; test with Number.isNaN(), never == NaN.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Arrays
Arrays store ordered lists of values. One of the most-used data structures in JavaScript.
In simple terms
Arrays: Lists of Things
An array keeps multiple values in one neat list:
let fruits = ["apples", "bread", "milk"]; console.log(fruits[0]); // "apples" (index starts at 0) console.log(fruits[1]); // "bread" console.log(fruits.length); // 3
Add and remove items:
fruits.push("eggs"); // adds to end fruits.pop(); // removes last fruits.unshift("tea"); // adds to start fruits.shift(); // removes first
Loop through an array:
for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]); }
Deep dive
Arrays: Technical Deep Dive
Arrays as Objects
Arrays are objects with integer-indexed properties and a special length property. typeof [] === "object" - use Array.isArray(). Arrays are sparse: arr[100] = 1 gives length 101 with one real element.
Creation
const a = [1, 2, 3]; const b = Array.from("hello"); // ["h","e","l","l","o"] const c = Array.from({length:5}, (_, i) => i); // [0,1,2,3,4]
Mutation Methods
push/pop - add/remove at end. unshift/shift - add/remove at start. splice(start, deleteCount, ...items) - insert/remove at any position. sort(compareFn) - in-place; always provide compareFn for numbers: (a,b) => a-b. reverse() - reverses in-place. fill(value, start, end) - fills range.
Accessor Methods (return new values)
slice(start, end) - shallow copy of a portion. concat(...arrays) - merges arrays. indexOf/includes - search. join(sep) - to string. flat(depth)/flatMap(fn) - flatten nested arrays. at(i) - negative index support (ES2022).
Reference: MDN Array.
Challenge
Challenge: Top Scores
Start with: [43, 91, 78, 55, 100, 62, 88]
- Print the number of scores.
- Print the first and last score.
- Add 95 to the end.
- Remove the first score.
- Sort descending (highest first).
- Print the final array.
Summary
- Arrays store ordered, indexed collections; index starts at 0.
- Use Array.isArray() to detect arrays, not typeof.
- Mutation methods (push, pop, splice, sort) modify the original in-place.
- Accessor methods (slice, concat, flat) return new arrays.
- Always provide a compare function to sort() for numeric sorting.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Array Methods
JavaScript arrays have powerful built-in methods like map, filter, and reduce that let you transform and query data elegantly.
In simple terms
Array Methods: Superpowers for Lists
Three of the most important array methods are map, filter, and reduce.
map transforms every item and returns a new array:
const numbers = [1, 2, 3, 4]; const doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6, 8]
filter keeps only items that pass a test:
const evens = numbers.filter(n => n % 2 === 0); console.log(evens); // [2, 4]
reduce combines all items into one value:
const sum = numbers.reduce((total, n) => total + n, 0); console.log(sum); // 10
More useful ones:
console.log(numbers.find(n => n > 2)); // 3 (first match) console.log(numbers.some(n => n > 3)); // true console.log(numbers.every(n => n > 0)); // true console.log(numbers.findIndex(n => n > 2)); // 2 const flat = [[1,2],[3,4]].flat(); // [1,2,3,4]
Deep dive
Array Methods: Functional Programming Patterns
map(callback)
Returns a new array of equal length where each element is the return value of callback(element, index, array). Does not mutate the original. Time complexity: O(n).
filter(callback)
Returns a new array containing only elements for which callback returns truthy. Length may be shorter than original. Does not mutate.
reduce(callback, initialValue)
Executes callback(accumulator, currentValue, index, array) for each element, passing the return value as the next accumulator. Returns the final accumulator value. Always provide an explicit initialValue to avoid errors on empty arrays.
find / findIndex
find(callback) returns the first element for which callback is truthy, or undefined. findIndex returns the index or -1. ES2022: findLast and findLastIndex search from the end.
some / every
some returns true if at least one element passes the test. every returns true if all elements pass. Both short-circuit.
forEach
Executes a callback for each element with no return value (undefined). Not chainable. Use map when you need the results; use forEach for side effects only.
flatMap
Equivalent to map(...).flat(1) but more efficient. Useful for one-to-many transformations.
Chaining
const result = [1,2,3,4,5] .filter(n => n % 2 !== 0) .map(n => n ** 2) .reduce((acc, n) => acc + n, 0); // 1 + 9 + 25 = 35
Reference: MDN Array instance methods.
Challenge
Challenge: Student Grades
Given scores: [55, 82, 91, 47, 73, 68, 95, 39]
- Filter out scores below 60 (failing).
- Map the passing scores to letter grades: >=90 = "A", >=80 = "B", >=70 = "C", else "D".
- Count how many students passed (use
.length on the filtered array). - Calculate the average of passing scores using
reduce. - Print all results.
Summary
- map transforms every element returning a new equal-length array; filter selects elements returning a shorter array.
- reduce accumulates all elements into one value; always provide an explicit initial value.
- find returns the first matching element; some/every check existence/universality of a condition.
- forEach is for side effects only and is not chainable; prefer map when you need results.
- Methods can be chained: filter then map then reduce is a common functional pattern.
Objects
Objects store collections of related data as key-value pairs. They are the foundation of JavaScript data modelling.
In simple terms
Objects: Real-World Things in Code
An object groups related information together. Think of a person: they have a name, age, and city. An object holds all of that:
const person = { name: "Alice", age: 25, city: "London" };
Access properties with dot notation or bracket notation:
console.log(person.name); // "Alice" console.log(person["age"]); // 25
Add or change properties:
person.email = "[email protected]"; person.age = 26;
Objects can have methods (functions inside objects):
const dog = { name: "Rex", bark: function() { console.log("Woof! I am " + this.name); } }; dog.bark(); // "Woof! I am Rex"
Loop over all properties:
for (let key in person) { console.log(key + ": " + person[key]); }
Deep dive
Objects: Technical Reference
Object Literals and Property Access
Object literals use { key: value } syntax. Property keys are strings (or Symbols). Dot notation (obj.key) works for valid identifiers. Bracket notation (obj["key"]) works for any string, including computed or dynamic keys.
Property Shorthand (ES6)
const name = "Alice"; const age = 25; const user = { name, age }; // same as { name: name, age: age }
Computed Property Names
const key = "score"; const obj = { [key]: 100 }; // { score: 100 }
Methods and this
this inside a method refers to the object the method is called on. Arrow functions do NOT have their own this - they inherit from the enclosing scope. Therefore use regular functions for object methods when this is needed.
Object Utility Methods
Object.keys(obj) - array of own enumerable property names. Object.values(obj) - array of own enumerable values. Object.entries(obj) - array of [key, value] pairs. Object.assign(target, ...sources) - shallow copy/merge. Object.freeze(obj) - prevents modification (shallow). Object.fromEntries(entries) - creates object from [key,value] pairs.
Spread Operator for Objects
const updated = { ...original, age: 26 }; // shallow clone with override
Optional Chaining with Objects
const zip = user?.address?.zipCode; // undefined if address missing
Reference: MDN Object.
Challenge
Challenge: Library Book
Create an object representing a library book with properties: title, author, year, pages, isAvailable. Then:
- Print the title and author.
- Mark the book as unavailable.
- Add a property
genre. - Print all keys using
Object.keys(). - Print all entries using
Object.entries().
Summary
- Objects store key-value pairs; keys are strings or Symbols, values can be anything.
- Use dot notation for known keys, bracket notation for dynamic or special-character keys.
- Methods are functions stored as object properties; use regular functions (not arrows) when you need this.
- Object.keys, Object.values, Object.entries provide iterable views of an object's own properties.
- Spread syntax creates shallow copies and enables immutable update patterns.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Map & Set
Map and Set are built-in data structures that solve problems arrays and plain objects handle poorly.
In simple terms
Map and Set: Better Tools for Specific Jobs
You already know arrays (ordered lists) and objects (key-value pairs). Map and Set are two more built-in containers, each solving a specific problem those structures handle awkwardly.
Set is a list that refuses duplicates. Every value in a Set is unique:
const tags = new Set();
tags.add("javascript");
tags.add("web");
tags.add("javascript"); // ignored - already in the Set
console.log(tags.size); // 2
console.log(tags.has("web")); // true
The most common use: remove duplicates from an array in one line:
const nums = [1, 2, 2, 3, 3, 3];
const unique = [...new Set(nums)]; // [1, 2, 3]
Map is like an object, but keys can be anything - not just strings:
const scores = new Map();
scores.set("Alice", 95);
scores.set("Bob", 87);
console.log(scores.get("Alice")); // 95
console.log(scores.size); // 2
Use Map when you need to associate data with non-string keys, or when insertion order matters.
Deep dive
Map and Set: Technical Details
Set
A Set stores unique values of any type. Uniqueness is determined by the SameValueZero algorithm - the same rules as === except that NaN === NaN is true inside a Set.
const s = new Set([1, 2, 3, 2, 1]);
console.log([...s]); // [1, 2, 3]
// Iterating
for (const val of s) console.log(val);
// Methods
s.add(4);
s.delete(1);
s.has(2); // true
s.clear();
s.size; // 0
Sets are iterable and maintain insertion order. Common pattern: deduplication via spread or Array.from.
Map
A Map is a collection of key-value pairs where keys can be any value (objects, functions, primitives). Unlike plain objects, Maps:
- Allow any type as a key, including objects and functions.
- Maintain insertion order when iterated.
- Have a reliable
.size property.
- Do not inherit prototype keys - no risk of collisions with
toString, constructor, etc.
const map = new Map();
const keyObj = { id: 1 };
map.set(keyObj, "user data");
map.set(42, "a number key");
map.set(true, "a boolean key");
console.log(map.get(keyObj)); // "user data"
console.log(map.size); // 3
// Iterating
for (const [key, value] of map) {
console.log(key, value);
}
// Convert to/from object
const obj = Object.fromEntries(map); // only string-safe keys
const map2 = new Map(Object.entries(obj));
When to use Map vs Object
Use a plain object when keys are strings/symbols known at write time and you want JSON serialisation. Use Map when keys are dynamic, non-string, or you need guaranteed insertion order and a clean .size.
WeakMap and WeakSet
WeakMap and WeakSet hold weak references - they do not prevent garbage collection of their keys/values. Keys must be objects. They have no .size and are not iterable. Use them to attach metadata to objects without memory leaks:
const cache = new WeakMap();
function process(obj) {
if (cache.has(obj)) return cache.get(obj);
const result = heavyComputation(obj);
cache.set(obj, result);
return result;
}
Reference: MDN Map, MDN Set.
Challenge
Challenge: Map and Set in Practice
- Given the array
["apple","banana","apple","cherry","banana","apple"], use a Set to produce a deduplicated array and print it.
- Use a Map to count how many times each fruit appears in that original array. Print the Map entries.
- Use
map.get() to print how many times "apple" appears.
Summary
- Set stores unique values of any type and rejects duplicates automatically.
- The fastest way to deduplicate an array is
[...new Set(array)].
- Map stores key-value pairs where keys can be any type, not just strings.
- Map maintains insertion order and has a reliable
.size property - advantages over plain objects.
- WeakMap and WeakSet hold weak references and are used to attach metadata to objects without preventing garbage collection.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
if / else Conditionals
Conditionals let your code make decisions and execute different paths based on whether a condition is true or false.
In simple terms
if / else: Making Decisions
Code needs to make decisions. The if statement runs a block only when a condition is true:
let temperature = 30; if (temperature > 25) { console.log("It is hot outside!"); }
Add an else for when the condition is false:
if (temperature > 25) { console.log("Hot!"); } else { console.log("Not hot."); }
Chain multiple conditions with else if:
let score = 75; if (score >= 90) { console.log("Grade A"); } else if (score >= 80) { console.log("Grade B"); } else if (score >= 70) { console.log("Grade C"); } else { console.log("Grade D"); }
You can nest if statements inside each other, but keep nesting shallow for readability.
Deep dive
Conditionals: Technical Details
Syntax
The condition can be any expression; it is coerced to boolean. Single-statement blocks can omit braces but always including them is best practice - omitting them is a common source of bugs.
Truthy / Falsy Conditions
Any value can be used as a condition. The 8 falsy values evaluate to false; everything else is true. This enables idioms like:
if (user) { /* user is not null/undefined/falsy */ } if (arr.length) { /* array is non-empty */ }
Guard Clauses (Early Return Pattern)
Instead of deeply nested if-else, use early returns to handle error/edge cases first, leaving the happy path unindented:
function processOrder(order) { if (!order) return "No order provided"; if (!order.items.length) return "Cart is empty"; return processPayment(order); }
Short-Circuit as Conditional
isLoggedIn && showDashboard(); user || redirectToLogin();
Nullish Patterns
const display = value ?? "default"; const name = user?.name ?? "Guest";
Reference: MDN if...else.
Challenge
Challenge: Ticket Price Calculator
Write a function getTicketPrice(age) that returns a ticket price:
- Under 5: free
- 5-12: $5
- 13-17: $8
- 18-64: $12
- 65 and over: $7
Test with ages: 3, 10, 15, 30, 70.
Summary
- if/else executes different code blocks based on whether conditions are truthy or falsy.
- else if chains allow testing multiple conditions in sequence.
- Always include braces even for single-statement blocks to prevent bugs.
- The guard clause pattern (early return) reduces nesting and improves readability.
- Short-circuit operators (&& and ||) can replace simple if statements in expressions.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Switch Statement
The switch statement is a clean way to compare one value against many possible cases.
In simple terms
Switch: The Multi-Choice Decision
When you need to compare one variable against many possible values, switch is cleaner than a long chain of if/else if:
let day = "Monday"; switch (day) { case "Monday": console.log("Start of the work week!"); break; case "Friday": console.log("TGIF!"); break; case "Saturday": case "Sunday": console.log("Weekend!"); break; default: console.log("Midweek."); }
Important rules:
- Each
case is checked with strict equality (===). - Always add
break at the end of each case, or execution falls through to the next case. default runs if no case matches (like the final else). - Multiple cases can share the same block (Saturday and Sunday above).
Deep dive
Switch Statement: Technical Reference
How Switch Works
The switch expression is evaluated once, then compared against each case value using strict equality (===). When a match is found, execution starts there and continues until a break, return, or the end of the switch block.
Fall-Through
Without break, execution falls through to the next case regardless of whether it matches. This is occasionally useful for shared handling but is a common bug source. Always add break unless fall-through is intentional, and document it with a comment.
Return in Switch
Inside a function, you can use return instead of break:
function getDayType(day) { switch (day) { case "Saturday": case "Sunday": return "Weekend"; default: return "Weekday"; } }
Switch vs if-else
Switch is generally better when comparing a single value against many constants. If-else is better for range checks or complex conditions. Modern JavaScript sometimes favours object lookup tables over switch:
const messages = { Monday: "Start of the work week!", Friday: "TGIF!", }; const msg = messages[day] ?? "Midweek.";
Reference: MDN switch.
Challenge
Challenge: HTTP Status Codes
Write a function describeStatus(code) using switch that returns a description for HTTP status codes: 200 = "OK", 201 = "Created", 400 = "Bad Request", 401 = "Unauthorized", 403 = "Forbidden", 404 = "Not Found", 500 = "Internal Server Error". Default: "Unknown status". Test with: 200, 404, 500, 999.
Summary
- Switch compares one expression against many cases using strict equality (===).
- Always add break at the end of each case to prevent fall-through bugs.
- Multiple cases can share a block by stacking them without break between.
- The default case is optional but recommended as a catch-all.
- Object lookup tables are a modern alternative to switch for mapping values to results.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Ternary Operator
The ternary operator is a compact one-line way to write an if/else expression.
In simple terms
Ternary Operator: If/Else in One Line
The ternary operator is a shortcut for simple if/else. It has three parts separated by ? and ::
condition ? valueIfTrue : valueIfFalse
Example:
let age = 20; let status = age >= 18 ? "adult" : "minor"; console.log(status); // "adult"
The same thing written as if/else:
let status; if (age >= 18) { status = "adult"; } else { status = "minor"; }
The ternary is great for inline assignments and JSX in React:
const greeting = isLoggedIn ? "Welcome back!" : "Please log in.";
You can nest ternaries but more than one level deep gets confusing. Use if/else for complex logic!
let score = 75; let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "D";
Deep dive
Ternary Operator: Technical Details
Syntax
condition ? exprIfTrue : exprIfFalse. The condition is coerced to boolean. Unlike if/else which is a statement, the ternary is an expression - it produces a value and can appear anywhere an expression is valid.
When to Use It
- Assigning one of two values based on a condition.
- Returning one of two values from a function.
- Inline in template literals:
`Status: ${isOn ? "on" : "off"}`. - JSX/HTML conditional rendering in React.
When NOT to Use It
- When the branches contain side effects (console.log, mutations) - use if/else for clarity.
- When nesting more than two levels deep - readability collapses.
- When the condition or expressions are complex - use a named if/else block.
Nullish / Logical Alternatives
For simple fallbacks, prefer:
const name = user.name ?? "Guest"; // null/undefined fallback const display = value || "placeholder"; // falsy fallback
Reference: MDN Conditional (ternary) operator.
Challenge
Challenge: Access Control
Using ternary operators (not if/else), write expressions for:
- A variable
accessLevel: "admin" if isAdmin is true, otherwise "user". - A variable
greeting: "Good morning!" if the hour is less than 12, "Good afternoon!" if less than 18, otherwise "Good evening!". - A variable
label: "In Stock" if quantity > 0, "Out of Stock" otherwise.
Summary
- The ternary operator is an expression (produces a value), unlike if/else which is a statement.
- Syntax: condition ? valueIfTrue : valueIfFalse.
- Best for simple inline conditional value assignment or return.
- Avoid for side effects, deeply nested conditions, or complex logic - use if/else instead.
- For simple fallbacks prefer ?? (nullish) or || (falsy) over a ternary.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
for Loop
The for loop repeats a block of code a set number of times. It is the most fundamental loop in JavaScript.
In simple terms
for Loop: Doing Things Repeatedly
A loop lets your code repeat without copy-pasting. The for loop has three parts:
for (start; condition; step) { // code to repeat }
Example - count from 1 to 5:
for (let i = 1; i <= 5; i++) { console.log(i); } // 1, 2, 3, 4, 5
let i = 1 - starting value i <= 5 - keep going while this is true i++ - increase i by 1 each time
Loop through an array:
const colors = ["red", "green", "blue"]; for (let i = 0; i < colors.length; i++) { console.log(colors[i]); }
Loop backwards:
for (let i = 5; i >= 1; i--) { console.log(i); }
Deep dive
for Loop: Technical Reference
Loop Anatomy
The for statement: for (initializer; condition; afterthought) statement. The initializer runs once. The condition is checked before each iteration; if falsy the loop exits. The afterthought runs after each iteration body.
Scope of Loop Variable
Use let (not var) for the loop counter. var is function-scoped and causes the classic closure bug where all callbacks capture the same variable. let creates a new binding per iteration.
// Classic bug with var for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); // prints 3 three times } // Fixed with let for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); // prints 0, 1, 2 }
Nested Loops
Loops can be nested for two-dimensional iteration (e.g., matrices). Time complexity multiplies: O(n) outer * O(m) inner = O(n*m).
for (let row = 0; row < 3; row++) { for (let col = 0; col < 3; col++) { process(matrix[row][col]); } }
Performance Notes
Cache arr.length before the loop when iterating large arrays (though modern engines optimise this). For arrays, for...of and array methods are usually more readable.
Reference: MDN for.
Challenge
Challenge: Multiplication Table
Use a nested for loop to print a multiplication table for numbers 1-5. Each row should print: "1 x 1 = 1", "1 x 2 = 2", etc. Outer loop is the first number (1-5), inner loop is the second number (1-5).
Summary
- The for loop has three parts: initialiser, condition, afterthought; condition is checked before each iteration.
- Use let (not var) for loop counters to get per-iteration scope and avoid closure bugs.
- Loop body executes as long as the condition is truthy; make sure the condition eventually becomes false.
- Nested loops enable two-dimensional iteration but multiply time complexity.
- For iterating arrays, for...of and array methods (map, filter) are often more expressive than a classic for loop.
while & do...while
while loops repeat as long as a condition is true. do...while loops always run at least once.
In simple terms
while & do...while: Keep Going Until Done
The while loop keeps running as long as its condition is true. Use it when you don't know in advance how many times to repeat:
let count = 0; while (count < 5) { console.log(count); count++; } // prints 0, 1, 2, 3, 4
A real-world example - keep asking until valid input:
let password = ""; while (password.length < 8) { password = getInput(); // imaginary function }
The do...while loop is similar but runs the body FIRST, then checks the condition. Guarantees at least one run:
let num; do { num = Math.floor(Math.random() * 10); } while (num < 5); console.log("Got a number >= 5:", num);
Warning: make sure the condition eventually becomes false, or you create an infinite loop!
Deep dive
while and do...while: Technical Details
while
Checks the condition before each iteration. If the condition is false initially, the body never runs. Suitable when the number of iterations is unknown (reading until EOF, polling, game loops, retry logic).
do...while
Executes the body first, then checks the condition. Guarantees at least one execution. Useful for menu prompts, input validation, and retry loops where you need to act before you can check the result.
Infinite Loop Prevention
A while loop without a terminating condition will freeze the browser tab or crash a Node.js process. Always ensure:
- The condition will eventually become false.
- The loop variable or state changes inside the body.
- Consider a maximum iteration guard:
let i = 0; while (condition && i++ < 10000).
While for Iterator Protocols
const iter = someIterable[Symbol.iterator](); let result = iter.next(); while (!result.done) { process(result.value); result = iter.next(); }
Reference: MDN while, MDN do...while.
Challenge
Challenge: Guess the Number
Simulate a number guessing game using a while loop:
- Generate a random integer between 1 and 10.
- Start with a guess of 0 and an attempt counter of 0.
- In the loop, generate a new random guess each iteration, increment attempts.
- Exit when the guess equals the target.
- Print how many attempts it took.
Summary
- while checks condition before each iteration - body may never run if condition starts false.
- do...while checks condition after - body always runs at least once.
- Use while when iteration count is unknown; use for when it is known.
- Always ensure the loop condition will eventually become false to prevent infinite loops.
- Consider adding a max-iterations guard for loops that depend on external state or randomness.
for...of & for...in
These modern loop forms make iterating over arrays and objects much cleaner than a classic for loop.
In simple terms
for...of and for...in: Modern Loops
for...of loops over the values of an iterable (arrays, strings, Sets, Maps):
const fruits = ["apple", "banana", "cherry"]; for (const fruit of fruits) { console.log(fruit); } // apple, banana, cherry
Works on strings too!
for (const letter of "hello") { console.log(letter); } // h, e, l, l, o
for...in loops over the keys (property names) of an object:
const car = { brand: "Toyota", model: "Corolla", year: 2020 }; for (const key in car) { console.log(key + ": " + car[key]); } // brand: Toyota, model: Corolla, year: 2020
Rule of thumb: use for...of for arrays and iterables. Use for...in for object keys.
Deep dive
for...of and for...in: Technical Reference
for...of and the Iterator Protocol
for...of works with any object that implements the iterable protocol (has a [Symbol.iterator] method). Built-in iterables: Array, String, Set, Map, NodeList, arguments, generators. Does NOT work on plain objects (they are not iterable by default).
// Works with Map const map = new Map([["a", 1], ["b", 2]]); for (const [key, value] of map) { console.log(key, value); } // Works with Set const set = new Set([1, 2, 3]); for (const item of set) console.log(item);
for...in and the Prototype Chain
for...in iterates over all enumerable string-keyed properties, including inherited ones from the prototype chain. Use Object.hasOwn(obj, key) (ES2022) or obj.hasOwnProperty(key) to filter to own properties only:
for (const key in obj) { if (Object.hasOwn(obj, key)) { console.log(key); } }
Note: for...in is not guaranteed to iterate in insertion order for all keys (integer-like keys are sorted numerically). Prefer Object.keys(obj).forEach() for reliable iteration of object properties.
entries() for Index + Value
for (const [index, value] of arr.entries()) { console.log(index, value); }
Reference: MDN for...of, MDN for...in.
Challenge
Challenge: Inventory Report
Given an object inventory = { apples: 50, bananas: 0, cherries: 23, dates: 0, elderberries: 12 }:
- Use
for...in to loop over the inventory. - Print only items that have a quantity greater than 0.
- Count how many items are out of stock.
- Use
for...of with Object.entries() to print each item as "Item: quantity units".
Summary
- for...of iterates over values of any iterable: arrays, strings, Sets, Maps, generators.
- for...in iterates over enumerable string keys of an object including inherited properties.
- Use Object.hasOwn() to filter for...in to own properties only.
- for...of does not work on plain objects - use Object.keys/values/entries with for...of instead.
- Use array.entries() with for...of to get both index and value in one loop.
break & continue
break exits a loop early. continue skips the rest of the current iteration and moves to the next one.
In simple terms
break & continue: Loop Control
break stops the loop immediately and jumps out:
for (let i = 0; i < 10; i++) { if (i === 5) break; console.log(i); } // prints 0, 1, 2, 3, 4 then stops
Useful when searching - stop as soon as you find what you want:
const names = ["Alice", "Bob", "Charlie", "Dave"]; for (const name of names) { if (name === "Charlie") { console.log("Found Charlie!"); break; } }
continue skips the rest of this iteration and goes to the next one:
for (let i = 0; i < 10; i++) { if (i % 2 === 0) continue; // skip even numbers console.log(i); } // prints 1, 3, 5, 7, 9
Think of break as pressing the emergency stop button, and continue as pressing "skip this one".
Deep dive
break and continue: Technical Details
break
Terminates the nearest enclosing loop or switch statement. Execution continues with the statement after the loop. In a switch statement, break prevents fall-through to the next case.
continue
Skips the remainder of the current loop body and jumps to the afterthought (for loop) or condition check (while loop). Reduces nesting in loop bodies - a guard clause at the top of a loop body using continue is equivalent to wrapping the rest of the body in an if block.
Labelled break and continue
Labels allow breaking or continuing an outer loop from an inner loop:
outer: for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) break outer; console.log(i, j); } }
Labelled breaks are rarely needed and can make code harder to follow. Consider restructuring into a function with an early return instead.
break in switch
Without break inside a switch case, execution falls through to subsequent cases. This is the primary use of break in switch statements.
Reference: MDN break, MDN continue.
Challenge
Challenge: Number Filter
Given an array of numbers from 1 to 20:
- Use
continue to skip multiples of 3. - Use
break to stop the loop once the sum exceeds 50. - Print each number as it is added and print the final sum.
Summary
- break immediately exits the nearest enclosing loop or switch statement.
- continue skips the rest of the current iteration body and moves to the next iteration.
- Both work in for, while, do...while, and for...of/for...in loops.
- Labelled break/continue can exit or skip an outer loop from an inner one but are rarely needed.
- Using continue as a guard clause at the loop top reduces nesting and improves readability.
Functions
Functions are reusable blocks of code. They take input, perform an action, and optionally return output.
In simple terms
Functions: Your Own Commands
A function is a reusable recipe. You write it once, then call it whenever you need it:
function greet(name) { console.log("Hello, " + name + "!"); } greet("Alice"); // Hello, Alice! greet("Bob"); // Hello, Bob!
Functions can take parameters (inputs) and return a value (output):
function add(a, b) { return a + b; } let result = add(3, 4); console.log(result); // 7
Default parameter values:
function greet(name = "friend") { console.log("Hello, " + name + "!"); } greet(); // Hello, friend! greet("Alice"); // Hello, Alice!
Functions are values too - you can store them in variables:
const square = function(n) { return n * n; }; console.log(square(5)); // 25
Deep dive
Functions: Technical Reference
Function Declaration vs Expression
Function declarations are hoisted: the entire function is available throughout its scope, even before the declaration line. Function expressions are not hoisted (the variable is hoisted but uninitialised if using let/const).
// Declaration - hoisted hello(); // works even before definition function hello() { console.log("hi"); } // Expression - not hoisted const hi = function() { console.log("hi"); }; hi(); // must call after this line
Parameters and Arguments
Parameters are the names in the function definition. Arguments are the values passed when calling. Extra arguments beyond declared parameters are accessible via the arguments object (not available in arrow functions) or rest parameters (...args).
Default Parameters (ES6)
function createUser(name, role = "viewer") { ... }
Defaults are evaluated at call time, not definition time. This means default expressions can reference earlier parameters.
Return Values
A function without an explicit return returns undefined. return with no value also returns undefined. Functions can return any value including other functions.
Pure Functions
A pure function always returns the same output for the same input and has no side effects. Prefer pure functions - they are easier to test, reason about, and compose.
First-Class Functions
Functions are first-class values: they can be assigned to variables, stored in arrays, passed as arguments, and returned from other functions. This enables callbacks, higher-order functions, and functional patterns.
Reference: MDN Functions guide.
Challenge
Challenge: Temperature Converter
Write two functions:
celsiusToFahrenheit(c) - converts Celsius to Fahrenheit (formula: c * 9/5 + 32). fahrenheitToCelsius(f) - converts Fahrenheit to Celsius (formula: (f - 32) * 5/9).
Round results to one decimal place. Test with: 0C, 100C, 32F, 212F. Print formatted output like "0°C = 32°F".
Summary
- Functions are reusable code blocks that take parameters and optionally return a value.
- Function declarations are hoisted; function expressions are not.
- Default parameters provide fallback values when arguments are missing.
- Functions without an explicit return statement return undefined.
- Functions are first-class values: they can be stored in variables, passed as arguments, and returned from functions.
Arrow Functions
Arrow functions are a concise syntax for writing functions introduced in ES6. They also handle "this" differently from regular functions.
In simple terms
Arrow Functions: Shorter, Slicker Functions
Arrow functions let you write functions with less typing. Compare:
// Regular function function double(n) { return n * 2; } // Arrow function const double = n => n * 2;
If there is only one parameter, no parentheses needed. If the body is one expression, no braces and no return keyword needed!
const square = n => n * n; const add = (a, b) => a + b; const greet = name => "Hello, " + name + "!";
Multi-line arrow functions still need braces and return:
const multiply = (a, b) => { const result = a * b; return result; };
Arrow functions work great with array methods:
const nums = [1, 2, 3, 4, 5]; const doubled = nums.map(n => n * 2); const evens = nums.filter(n => n % 2 === 0); const sum = nums.reduce((acc, n) => acc + n, 0);
Deep dive
Arrow Functions: Technical Reference
Syntax Variants
() => expression // no parameters x => expression // one parameter, no parens (x, y) => expression // multiple parameters (x, y) => { statements; return val; } // block body () => ({ key: value }) // return object literal (wrap in parens)
Lexical this
The most important distinction: arrow functions do not have their own this. They capture this from the surrounding lexical scope at definition time. This makes them ideal for callbacks inside methods:
function Timer() { this.seconds = 0; setInterval(() => { this.seconds++; // correctly refers to Timer instance }, 1000); }
With a regular function, this inside setInterval would be undefined (strict mode) or the global object.
No arguments Object
Arrow functions do not have their own arguments object. Use rest parameters instead: (...args) => ....
Cannot be Constructors
Arrow functions cannot be used with new. They have no prototype property.
No duplicate named parameters
Arrow functions (and strict mode functions) do not allow duplicate parameter names.
Reference: MDN Arrow functions.
Challenge
Challenge: Array Pipeline
Given const products = [{name:"Laptop",price:999},{name:"Mouse",price:29},{name:"Monitor",price:349},{name:"Keyboard",price:79},{name:"Webcam",price:149}]:
- Use an arrow function with filter to get products under $200.
- Use an arrow function with map to extract just the names.
- Use an arrow function with reduce to calculate the total price of ALL products.
- Print all three results.
Summary
- Arrow functions provide a concise syntax: single params need no parens, single-expression bodies need no braces or return.
- Arrow functions capture this lexically from the enclosing scope - they have no own this.
- Arrow functions have no arguments object - use rest parameters instead.
- Arrow functions cannot be used as constructors with new.
- They are ideal for callbacks and array method handlers (map, filter, reduce).
Scope & Closures
Scope determines where variables are accessible. Closures let functions remember the variables from their birth environment.
In simple terms
Scope & Closures: Variable Visibility
Scope is the area of code where a variable can be seen and used.
Global scope - variable declared outside any function, visible everywhere:
let globalName = "World"; // accessible anywhere
Local / function scope - variable inside a function, only visible there:
function sayHi() { let localMsg = "Hi!"; console.log(localMsg); // works } console.log(localMsg); // ReferenceError!
Block scope - let and const are block-scoped:
if (true) { let blockVar = "inside"; } console.log(blockVar); // ReferenceError!
A closure is when a function remembers variables from its outer scope even after that outer function has finished:
function makeCounter() { let count = 0; return function() { count++; return count; }; } const counter = makeCounter(); console.log(counter()); // 1 console.log(counter()); // 2 console.log(counter()); // 3
The inner function "closes over" the count variable - it keeps a private memory!
Deep dive
Scope and Closures: Technical Detail
Scope Chain
When JavaScript looks up a variable, it searches the current scope, then the outer scope, then the next outer scope, all the way up to the global scope. This chain of scopes is the scope chain. If the variable is not found anywhere, a ReferenceError is thrown.
Lexical Scoping
JavaScript uses lexical (static) scoping: a function's scope is determined by where it is defined in the source code, not where it is called. The scope chain is fixed at parse time.
Variable Environments and Closures
Every function call creates a new execution context with its own variable environment. When a function is created, it captures a reference to its outer variable environment - this is the closure. As long as the inner function exists, the captured environment is not garbage collected.
Practical Uses of Closures
- Private state (module pattern, counters).
- Factory functions that produce customised functions.
- Memoisation and caching.
- Partial application and currying.
- Event handlers that remember context.
function multiplier(factor) { return n => n * factor; // closes over factor } const triple = multiplier(3); console.log(triple(7)); // 21
IIFE (Immediately Invoked Function Expression)
Used to create a new scope to avoid polluting global scope:
(() => { const privateVar = "safe"; })();
Reference: MDN Closures.
Challenge
Challenge: Private Counter
Use a closure to create a counter factory function makeCounter(start, step) that:
- Starts at
start (default 0). - Each call increments by
step (default 1). - Returns an object with methods:
increment(), decrement(), reset(), value().
Create two independent counters and show they don't share state.
Summary
- Scope determines where variables are accessible: global, function, or block scope.
- JavaScript uses lexical scoping - a function's scope chain is fixed at definition time.
- A closure is a function that retains access to its outer scope's variables after that scope has returned.
- Closures enable private state, factory functions, memoisation, and partial application.
- The scope chain is traversed upward during variable lookup; a ReferenceError is thrown if not found.
The this Keyword
Understanding what this refers to is one of the most important - and most misunderstood - parts of JavaScript.
In simple terms
The this Keyword
this refers to the object that is currently running the code. Its value depends entirely on how a function is called, not where it is defined.
In a method (a function inside an object), this is the object:
const user = {
name: "Alice",
greet() {
console.log("Hello, " + this.name);
}
};
user.greet(); // "Hello, Alice"
If you take that method out and call it as a plain function, this is no longer the object:
const greet = user.greet;
greet(); // "Hello, undefined" - this is now undefined (strict mode)
Arrow functions do not have their own this. They inherit it from the surrounding code:
const timer = {
seconds: 0,
start() {
setInterval(() => {
this.seconds++; // this is still the timer object
console.log(this.seconds);
}, 1000);
}
};
timer.start();
If start() used a regular function instead of an arrow, this.seconds would fail because this inside setInterval's callback would not be the timer object.
Deep dive
this: Binding Rules and Precedence
JavaScript determines the value of this at call time using four rules, in order of precedence:
1. Default binding
A plain function call. In strict mode this is undefined. In sloppy mode it is the global object (window in browsers, global in Node).
"use strict";
function show() { console.log(this); }
show(); // undefined
2. Implicit binding
When a function is called as a method of an object, this is that object.
const obj = { val: 42, get() { return this.val; } };
obj.get(); // 42
3. Explicit binding
call, apply, and bind let you set this explicitly.
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const person = { name: "Bob" };
greet.call(person, "Hello"); // "Hello, Bob"
greet.apply(person, ["Hi"]); // "Hi, Bob"
const boundGreet = greet.bind(person);
boundGreet("Hey"); // "Hey, Bob"
4. new binding
When a function is called with new, a new object is created and this refers to it.
function Person(name) {
this.name = name;
}
const alice = new Person("Alice");
console.log(alice.name); // "Alice"
Arrow functions: lexical this
Arrow functions do not have their own this binding. They capture this from the enclosing lexical scope at definition time. You cannot change an arrow function's this with call, apply, or bind.
const obj = {
value: 10,
regular: function() { return this.value; }, // this = obj
arrow: () => this.value, // this = outer scope (not obj)
};
console.log(obj.regular()); // 10
console.log(obj.arrow()); // undefined
Class methods and this
In a class, method calls follow implicit binding. A common pitfall is passing a method as a callback - it loses its this. Fix: bind in the constructor, or use a class field arrow function.
class Counter {
count = 0;
// Class field arrow - this is always the instance
increment = () => { this.count++; };
}
const c = new Counter();
const inc = c.increment;
inc(); // works correctly - this.count is still the Counter instance
Reference: MDN this.
Challenge
Challenge: this in Practice
- Create an object
bank with a balance of 100 and a method deposit(amount) that adds to the balance and prints the new total using this.
- Extract the
deposit method into a standalone variable and call it - observe what happens to this.
- Use
.bind() to fix the extracted method so it still works correctly.
Summary
this is determined at call time by four rules: default, implicit (method call), explicit (call/apply/bind), and new.
- In strict mode, default binding sets
this to undefined instead of the global object.
- Arrow functions do not have their own
this - they inherit it lexically from the enclosing scope.
- Use
.bind() to create a new function with a fixed this, or class field arrows to avoid losing context in callbacks.
- The most common bug: extracting a method from an object and calling it as a plain function, losing the object as
this.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Higher-Order Functions
Higher-order functions either accept functions as arguments or return functions. They are central to functional programming in JavaScript.
In simple terms
Higher-Order Functions: Functions Using Functions
A higher-order function is one that either takes a function as an argument OR returns a function. This sounds fancy but you already use them! map, filter, and reduce are all higher-order functions.
Passing a function as an argument (a callback):
function runTwice(fn) { fn(); fn(); } runTwice(() => console.log("Hello!")); // prints Hello! twice
Returning a function:
function makeMultiplier(factor) { return n => n * factor; } const double = makeMultiplier(2); const triple = makeMultiplier(3); console.log(double(5)); // 10 console.log(triple(5)); // 15
Build your own forEach:
function myForEach(array, callback) { for (let i = 0; i < array.length; i++) { callback(array[i], i); } } myForEach(["a","b","c"], (item, i) => console.log(i, item));
Deep dive
Higher-Order Functions: Technical Depth
First-Class Functions
Higher-order functions are possible because JavaScript treats functions as first-class values. They can be stored in variables, passed as arguments, returned from functions, and stored in data structures.
Callbacks
A callback is a function passed to another function to be called at a specific time. Callbacks are used for: event handling, asynchronous operations, array iteration methods, and customising behavior. Callback-based async code can lead to "callback hell" - deeply nested callbacks - which Promises and async/await solve.
Function Composition
Combining two or more functions so the output of one feeds the input of the next:
const compose = (f, g) => x => f(g(x)); const addOne = x => x + 1; const double = x => x * 2; const addOneThenDouble = compose(double, addOne); console.log(addOneThenDouble(3)); // (3+1)*2 = 8
Partial Application and Currying
Partial application pre-fills some arguments of a function:
const add = (a, b) => a + b; const add5 = add.bind(null, 5); // partial application console.log(add5(3)); // 8
Currying transforms a multi-argument function into a chain of single-argument functions:
const curry = a => b => a + b; const add5 = curry(5); console.log(add5(3)); // 8
Reference: MDN Callback function.
Challenge
Challenge: Function Pipeline
Create a pipe(...fns) function that takes any number of functions and returns a new function that passes its argument through all of them left-to-right. Test with a pipeline that: trims a string, converts to lowercase, replaces spaces with hyphens (to make a URL slug).
Summary
- Higher-order functions accept functions as arguments or return functions (or both).
- Callbacks are functions passed to be called later - they power event handling and async code.
- Function composition chains the output of one function into the input of the next.
- Currying transforms a multi-argument function into nested single-argument functions.
- Partial application pre-fills some arguments using bind or closures.
Template Literals
Template literals use backticks and allow embedded expressions, multi-line strings, and tagged templates.
In simple terms
Template Literals: Strings with Superpowers
Before template literals, building strings with variables was messy:
const name = "Alice"; const age = 25; const old = "My name is " + name + " and I am " + age + " years old.";
Template literals use backticks and ${} to embed expressions cleanly:
const better = `My name is ${name} and I am ${age} years old.`;
You can put ANY expression inside ${}:
const a = 5, b = 3; console.log(`${a} plus ${b} equals ${a + b}`); console.log(`${a > b ? "a is bigger" : "b is bigger or equal"}`);
Multi-line strings are natural - just press Enter:
const poem = `Roses are red, Violets are blue, JavaScript is awesome, And so are you!`;
Calling functions inside:
const shout = name => name.toUpperCase(); console.log(`Hello, ${shout("world")}!`); // Hello, WORLD!
Deep dive
Template Literals: Technical Reference
Syntax
Template literals are enclosed in backticks ( ` ). Embedded expressions use ${expression} syntax. The expression can be any valid JavaScript expression: variable, arithmetic, function call, ternary, method chain, etc.
Multi-line
Newlines inside template literals are preserved literally, unlike regular strings where you need . This makes them ideal for HTML snippets, SQL queries, and multi-line messages.
Expression Interpolation
The embedded expression is coerced to a string via toString(). Objects will give [object Object] unless they have a custom toString or you use JSON.stringify.
Tagged Templates
A tag function can process a template literal before it becomes a string:
function highlight(strings, ...values) { return strings.reduce((result, str, i) => result + str + (values[i] ? `<strong>${values[i]}</strong>` : ""), ""); } const user = "Alice"; const msg = highlight`Welcome, ${user}! You have ${3} messages.`; // "Welcome, <strong>Alice</strong>! You have <strong>3</strong> messages."
Tagged templates are used by libraries like styled-components, graphql-tag, and sql template engines for DSL (domain-specific language) support.
String.raw
String.raw`... ...` returns the raw string with escape sequences not processed. Useful for Windows file paths and regex patterns.
Reference: MDN Template literals.
Challenge
Challenge: Receipt Generator
Given an array of items with name and price, use template literals to generate a formatted receipt string. Include: a header, each item on its own line with price right-aligned, a separator line, and a total. Use multi-line template literals and expression interpolation throughout.
Summary
- Template literals use backticks and embed expressions with ${expression}.
- Any valid JavaScript expression can be embedded: arithmetic, function calls, ternaries.
- Multi-line strings are native to template literals - newlines are preserved.
- Embedded expressions are converted to strings via toString(); use JSON.stringify for objects.
- Tagged templates allow a function to pre-process a template literal, enabling DSLs and sanitisation.
Destructuring
Destructuring lets you unpack values from arrays and properties from objects into distinct variables in a single statement.
In simple terms
Destructuring: Unpacking Made Easy
Without destructuring, extracting values is repetitive:
const point = [10, 20, 30]; const x = point[0]; const y = point[1]; const z = point[2];
Array destructuring unpacks in one line:
const [x, y, z] = [10, 20, 30]; console.log(x, y, z); // 10 20 30
Skip elements with commas:
const [first, , third] = [1, 2, 3]; console.log(first, third); // 1 3
Object destructuring extracts by property name:
const user = { name: "Alice", age: 25, city: "London" }; const { name, age } = user; console.log(name, age); // Alice 25
Rename while destructuring:
const { name: userName, age: userAge } = user; console.log(userName); // Alice
Default values:
const { name, role = "viewer" } = user; console.log(role); // "viewer" (not in user object)
Deep dive
Destructuring: Technical Reference
Array Destructuring
Works with any iterable. Uses the iterator protocol under the hood. Supports rest elements:
const [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2,3,4]
Object Destructuring
Matches by property name. Supports renaming ({ old: newName }), defaults ({ key = defaultVal }), and rest ({ a, ...rest }).
Nested Destructuring
const { address: { city, zip } } = user; const [[a, b], [c, d]] = [[1,2],[3,4]];
Function Parameter Destructuring
One of the most common uses - destructure directly in function parameters:
function greet({ name, role = "user" }) { return `Hello ${name}, you are a ${role}`; } greet({ name: "Alice", role: "admin" });
Swapping Variables
let a = 1, b = 2; [a, b] = [b, a]; // a = 2, b = 1
Destructuring Return Values
function getCoords() { return [10, 20]; } const [x, y] = getCoords();
Reference: MDN Destructuring assignment.
Challenge
Challenge: API Response Parser
Given:
const response = { status: 200, data: { user: { id: 42, name: "Bob", email: "[email protected]" }, posts: ["Post 1", "Post 2", "Post 3"] }, error: null };
Use destructuring to extract: status, user id and name (renamed to userId and userName), the first post, and the remaining posts. Print all extracted values.
Summary
- Array destructuring unpacks values by position; object destructuring by property name.
- Rename during object destructuring: { originalKey: newVariableName }.
- Set defaults in destructuring patterns for missing values.
- Rest elements (...rest) capture remaining items into an array or object.
- Destructuring works in function parameters, for...of loops, and assignment expressions.
Spread & Rest Operators
Both use the ... syntax. Spread expands an iterable into individual elements. Rest collects multiple elements into one array.
In simple terms
Spread & Rest: The Three Dots
Three dots ... do two opposite things depending on where you put them.
Spread expands (opens up) an array or object:
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const combined = [...arr1, ...arr2]; console.log(combined); // [1,2,3,4,5,6] const original = { a: 1, b: 2 }; const copy = { ...original, c: 3 }; console.log(copy); // { a:1, b:2, c:3 }
Spread a string into characters:
const letters = [..."hello"]; console.log(letters); // ["h","e","l","l","o"]
Pass array elements as function arguments:
const nums = [3, 1, 4, 1, 5, 9]; console.log(Math.max(...nums)); // 9
Rest collects remaining arguments into an array:
function sum(...numbers) { return numbers.reduce((acc, n) => acc + n, 0); } console.log(sum(1, 2, 3, 4, 5)); // 15
Deep dive
Spread and Rest: Technical Reference
Spread in Array Literals
Expands any iterable (array, string, Set, Map, generator) into the surrounding array:
const a = [1,2]; const b = [3,4]; const c = [0, ...a, ...b, 5]; // [0,1,2,3,4,5]
Spread in Object Literals
Copies own enumerable properties shallowly. Later properties override earlier ones (useful for override patterns):
const defaults = { color: "red", size: "M", qty: 1 }; const custom = { ...defaults, size: "L", qty: 3 }; // { color:"red", size:"L", qty:3 }
Spread in Function Calls
Math.max(...arr); someFunc(...args);
Rest Parameters
The rest parameter must be the last parameter. It collects all remaining arguments into a real array (unlike the legacy arguments object which is array-like, not an array):
function log(level, ...messages) { messages.forEach(m => console.log(`[${level}] ${m}`)); }
Shallow Copy Warning
Spread creates only a shallow copy. Nested objects and arrays are still shared by reference:
const obj = { a: { b: 1 } }; const copy = { ...obj }; copy.a.b = 99; console.log(obj.a.b); // 99 - same nested object!
Use structuredClone(obj) (ES2022) for deep copies.
Reference: MDN Spread syntax, MDN Rest parameters.
Challenge
Challenge: Object Merger
- Write a function
mergeConfigs(...configs) that accepts any number of config objects and merges them left to right (later values override earlier ones). Use spread. - Write a function
first(arr, n=1) that returns the first n elements and the remaining elements as a separate array. Use rest and spread/destructuring. - Test both functions with sample data.
Summary
- Spread (...) expands iterables into individual elements in array literals, object literals, and function calls.
- Rest (...) collects remaining function arguments into a real array; must be the last parameter.
- Spread creates shallow copies - nested objects are still shared by reference.
- Object spread follows left-to-right precedence: later keys override earlier ones.
- Use structuredClone() for deep copies when nested mutation protection is needed.
Classes & OOP
Classes provide a clean syntax for creating objects with shared structure and behaviour. JavaScript classes are syntactic sugar over prototypal inheritance.
In simple terms
Classes: Blueprints for Objects
A class is like a blueprint. You define it once, then create as many objects (instances) from it as you like:
class Animal { constructor(name, sound) { this.name = name; this.sound = sound; } speak() { console.log(`${this.name} says ${this.sound}!`); } } const dog = new Animal("Rex", "Woof"); const cat = new Animal("Whiskers", "Meow"); dog.speak(); // Rex says Woof! cat.speak(); // Whiskers says Meow!
Inheritance lets one class extend another:
class Dog extends Animal { constructor(name) { super(name, "Woof"); // call parent constructor } fetch() { console.log(`${this.name} fetches the ball!`); } } const buddy = new Dog("Buddy"); buddy.speak(); // Buddy says Woof! buddy.fetch(); // Buddy fetches the ball!
Deep dive
Classes: Technical Reference
Class Syntax
Classes are syntactic sugar over JavaScript's prototype-based inheritance. Under the hood, class methods are added to the prototype, not the instance. Class declarations are NOT hoisted (unlike function declarations).
Constructor
The constructor method runs when new ClassName() is called. It sets up instance properties using this. Only one constructor per class.
Instance Methods and Properties
Methods defined in the class body are placed on the prototype (shared across all instances). Instance properties set in the constructor or via class fields are per-instance.
class Circle { #radius; // private field (ES2022) static PI = Math.PI; // static property constructor(radius) { this.#radius = radius; } get area() { return Circle.PI * this.#radius ** 2; } set radius(r) { if (r > 0) this.#radius = r; } }
Inheritance and super
extends sets up the prototype chain. super() calls the parent constructor and must be called before accessing this in a derived class. super.method() calls a parent method.
Static Members
Static methods and properties belong to the class itself, not instances. Called as ClassName.method().
Private Fields (#)
Private class fields (ES2022) are truly private - inaccessible outside the class. Use getters/setters for controlled access.
Reference: MDN Classes.
Challenge
Challenge: Bank Account
Create a BankAccount class with:
- Private field
#balance (initial 0). - Constructor that accepts an owner name and optional starting balance.
- Methods:
deposit(amount), withdraw(amount) (reject if insufficient funds), getBalance(). - A static method
transfer(from, to, amount) that withdraws from one account and deposits to another.
Test it: create two accounts, deposit, transfer between them, print balances.
Summary
- Classes are syntactic sugar over prototypal inheritance; methods are added to the prototype, not each instance.
- The constructor runs on new and sets up instance state with this.
- extends sets up inheritance; super() calls the parent constructor (required before using this in child).
- Static members belong to the class itself, not instances.
- Private fields (#fieldName) are truly encapsulated and not accessible outside the class body.
Prototypes
Prototypes are the mechanism behind JavaScript inheritance. Every object has a prototype from which it can inherit methods and properties.
In simple terms
Prototypes: How JavaScript Objects Share Behaviour
Every JavaScript object has a hidden link to another object called its prototype. When you look for a property and it is not found on the object, JavaScript automatically looks up the prototype chain.
const animal = { breathe() { console.log("Breathing..."); } }; const dog = Object.create(animal); dog.name = "Rex"; dog.breathe(); // "Breathing..." - found on prototype! console.log(dog.name); // "Rex" - found on dog itself
This is how array methods work. Every array inherits from Array.prototype:
const arr = [1, 2, 3]; console.log(arr.__proto__ === Array.prototype); // true
Classes just make the prototype system more readable:
class Dog { bark() { console.log("Woof!"); } } // bark is stored on Dog.prototype, shared by all Dog instances
Deep dive
Prototypes: Technical Deep Dive
The Prototype Chain
Every object has an internal [[Prototype]] slot (accessible as __proto__ or via Object.getPrototypeOf(obj)). Property lookup traverses the chain until the property is found or the chain ends at null (Object.prototype's prototype).
Object.create()
Creates a new object with a specified prototype:
const proto = { greet() { return `Hello, ${this.name}`; } }; const obj = Object.create(proto); obj.name = "Alice"; obj.greet(); // "Hello, Alice"
Constructor Functions (pre-class syntax)
function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const alice = new Person("Alice");
When new is used: a new object is created, its [[Prototype]] is set to Constructor.prototype, this inside the constructor refers to the new object, and the object is returned.
hasOwnProperty vs Inherited
Object.hasOwn(obj, "prop"); // own property only (ES2022) "prop" in obj; // own OR inherited Object.getPrototypeOf(obj); // get prototype Object.setPrototypeOf(obj, proto); // set prototype (avoid - slow)
Prototype Pollution
Modifying Object.prototype affects ALL objects and is a critical security vulnerability. Never do this in production code.
Reference: MDN Object prototypes.
Challenge
Challenge: Prototype Chain Explorer
- Create a base object
vehicle with a method describe() that prints its type and speed. - Use
Object.create(vehicle) to create a car object that adds a honk() method. - Use
Object.create(car) to create a sportsCar with a turboBoost() method. - Call all three methods on sportsCar and prove the chain with
Object.getPrototypeOf().
Summary
- Every JavaScript object has a [[Prototype]] link forming a chain for property lookup.
- Property lookup walks up the chain until found or null is reached, then returns undefined.
- Object.create(proto) creates an object with a specified prototype.
- Classes are syntactic sugar - methods defined in a class body live on the class's prototype, shared by all instances.
- Never modify Object.prototype - it affects all objects and is a security vulnerability.
The DOM
The Document Object Model (DOM) is the browser's representation of an HTML page as a tree of objects that JavaScript can read and manipulate.
In simple terms
The DOM: JavaScript Meets HTML
When a browser loads an HTML page, it creates a family tree of all the elements. This tree is called the DOM (Document Object Model). JavaScript can see and change every part of this tree!
Select elements:
const title = document.getElementById("main-title"); const buttons = document.querySelectorAll(".btn"); const firstBtn = document.querySelector(".btn");
Change content and styles:
title.textContent = "New Title!"; title.style.color = "blue"; title.classList.add("highlight"); title.classList.remove("old-class");
Create and add new elements:
const newPara = document.createElement("p"); newPara.textContent = "This is a new paragraph!"; document.body.appendChild(newPara);
Read and change attributes:
const link = document.querySelector("a"); console.log(link.getAttribute("href")); link.setAttribute("href", "https://example.com");
Deep dive
The DOM: Technical Reference
What is the DOM
The DOM is a language-independent API that represents an HTML (or XML) document as a tree of Node objects. The browser constructs the DOM from parsed HTML. JavaScript interacts with the DOM through the document and window global objects.
Node Types
Key node types: Element (HTML elements, nodeType 1), Text (text content, nodeType 3), Comment (nodeType 8), Document (nodeType 9).
Selection Methods
document.getElementById(id) - by id (fastest, unique). document.querySelector(selector) - first match by CSS selector. document.querySelectorAll(selector) - all matches, returns NodeList. element.closest(selector) - nearest ancestor matching selector. element.matches(selector) - boolean, does element match?
DOM Manipulation
element.textContent - text only, no HTML parsing (safe from XSS). element.innerHTML - HTML string (be careful: XSS risk with user data). element.insertAdjacentHTML(position, html) - safer alternative to innerHTML for appending. document.createElement(tag) + parent.appendChild(child) - create and attach. element.remove() - remove element from DOM. element.cloneNode(deep) - clone element.
Performance
DOM operations are expensive. Minimise reflows by batching changes, using DocumentFragment for bulk inserts, and modifying classes/styles instead of individual properties. Reading layout properties (offsetWidth, getBoundingClientRect) forces a synchronous reflow.
Reference: MDN DOM.
Challenge
Challenge: Dynamic List Builder
In a browser environment, write JavaScript that:
- Creates an empty unordered list and appends it to document.body.
- Adds 5 list items with the text "Item 1" through "Item 5".
- Styles every other item with a light grey background.
- Adds a "Remove" button next to each item that removes that item when clicked.
Summary
- The DOM is a tree of Node objects representing the HTML document; JavaScript interacts via document and window.
- querySelector/querySelectorAll use CSS selectors and are the most flexible selection methods.
- Use textContent (not innerHTML) when setting plain text to avoid XSS vulnerabilities.
- Create elements with createElement, configure them, then insert with appendChild or insertAdjacentHTML.
- Batch DOM changes and avoid forced reflows to maintain performance.
Events & Event Listeners
Events are actions that happen in the browser. JavaScript can listen for and respond to user interactions like clicks, typing, and scrolling.
In simple terms
Events: Responding to the User
Every time a user clicks, types, scrolls, or hovers, the browser fires an event. JavaScript can listen for these events and run code when they happen.
const button = document.querySelector("#myButton"); button.addEventListener("click", function() { console.log("Button was clicked!"); });
The event object is automatically passed to your handler - it contains info about the event:
button.addEventListener("click", function(event) { console.log("Clicked at:", event.clientX, event.clientY); console.log("Target:", event.target); });
Common events:
element.addEventListener("click", handler); element.addEventListener("input", handler); // typing element.addEventListener("submit", handler); // form submit element.addEventListener("keydown", handler); // key pressed element.addEventListener("mouseover", handler); window.addEventListener("load", handler); window.addEventListener("resize", handler);
Remove a listener:
element.removeEventListener("click", handler);
Deep dive
Events: Technical Reference
Event Flow: Capture and Bubble
Events travel in three phases: capture (from window down to target), target, and bubble (from target back up to window). By default, addEventListener listens in the bubble phase. Pass true or { capture: true } as the third argument to listen during capture.
Event Delegation
Instead of attaching listeners to every child, attach one listener to the parent and use event.target to identify which child was interacted with. More efficient, works for dynamically added elements:
ul.addEventListener("click", (e) => { if (e.target.tagName === "LI") { e.target.classList.toggle("done"); } });
Preventing Default Behaviour
form.addEventListener("submit", (e) => { e.preventDefault(); // stops form from reloading the page validateAndSubmit(); });
Stopping Propagation
e.stopPropagation(); // stops bubbling to parent listeners e.stopImmediatePropagation(); // stops other listeners on same element too
addEventListener Options
element.addEventListener("click", handler, { once: true, // auto-remove after first invocation passive: true, // will not call preventDefault (improves scroll performance) capture: false });
Reference: MDN addEventListener, MDN Events guide.
Challenge
Challenge: Interactive Counter
Create HTML with: a display showing "0", an Increment button, a Decrement button, and a Reset button. Wire up event listeners so: Increment adds 1, Decrement subtracts 1 (minimum 0), Reset sets back to 0. Update the display on every change. Use event delegation on a container instead of three separate listeners.
Summary
- addEventListener attaches a handler for a named event; multiple handlers can be added for the same event.
- The event object passed to handlers contains target, type, coordinates, key pressed, and more.
- Events bubble up the DOM by default; use stopPropagation to prevent further bubbling.
- Event delegation attaches one listener to a parent and uses event.target to handle dynamic children.
- Use preventDefault() to stop default browser behaviour like form submission or link navigation.
Iterators & Generators
Iterators define how JavaScript steps through a sequence of values. Generators make it easy to create custom iterators.
In simple terms
Iterators and Generators
Every time you use for...of, JavaScript is using an iterator behind the scenes. An iterator is any object with a next() method that returns { value, done }.
You can make your own iterator, but it is verbose. Generators are a cleaner way to produce sequences of values on demand:
function* countdown(n) {
while (n > 0) {
yield n;
n--;
}
}
for (const num of countdown(3)) {
console.log(num); // 3, 2, 1
}
The function* syntax creates a generator function. yield pauses the function and hands back a value. The function resumes from where it left off on the next call.
Generators are lazy - they only compute the next value when asked. This makes them useful for large or infinite sequences:
function* naturals() {
let n = 1;
while (true) {
yield n++;
}
}
const nums = naturals();
console.log(nums.next().value); // 1
console.log(nums.next().value); // 2
console.log(nums.next().value); // 3
// Never exhausted - produces values forever on demand
Deep dive
Iterators and Generators: Protocol and Patterns
The Iterator Protocol
An object is an iterator if it has a next() method that returns { value: any, done: boolean }. When done is true, the sequence is exhausted.
The Iterable Protocol
An object is iterable if it has a [Symbol.iterator]() method that returns an iterator. Arrays, strings, Maps, Sets, and generator objects are all iterable. This is what for...of, spread (...), and destructuring consume.
// Custom iterable range
const range = {
from: 1,
to: 5,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next() {
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true };
}
};
}
};
console.log([...range]); // [1, 2, 3, 4, 5]
Generator Functions
function* returns a generator object that is both an iterator and an iterable. yield suspends execution; the function resumes on the next .next() call. return inside a generator sets done: true.
function* gen() {
yield 1;
yield 2;
return 3; // done: true, not included in for...of
}
const g = gen();
console.log(g.next()); // { value: 1, done: false }
console.log(g.next()); // { value: 2, done: false }
console.log(g.next()); // { value: 3, done: true }
yield* - delegating to another iterable
function* concat(...iterables) {
for (const it of iterables) yield* it;
}
console.log([...concat([1,2], [3,4])]); // [1,2,3,4]
Async Generators
async function* combines generators with async/await. Used with for await...of to process asynchronous streams:
async function* fetchPages(urls) {
for (const url of urls) {
const res = await fetch(url);
yield await res.json();
}
}
for await (const data of fetchPages(urls)) {
console.log(data);
}
Reference: MDN Iteration Protocols, MDN function*.
Challenge
Challenge: Custom Range Generator
- Write a generator function
range(start, end, step) that yields numbers from start up to (but not including) end, incrementing by step.
- Use it with
for...of to print every even number from 0 to 10.
- Use spread to convert
range(1, 6, 1) into an array and print it.
Summary
- The iterator protocol defines objects with a
next() method returning { value, done }.
- The iterable protocol defines objects with
[Symbol.iterator]() - used by for...of, spread, and destructuring.
- Generator functions (
function*) use yield to produce values lazily, pausing between each.
- Generators are useful for infinite sequences, custom iteration, and processing data pipelines without loading everything into memory.
- Async generators (
async function*) work with for await...of to handle asynchronous data streams.
/* Lesson playground + migrated-lesson callouts [5818]. Standalone: every colour has a fallback, the learn template's variables are used when present. */
.learn-body .editor-container, .editor-container {
display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 14px; margin: 20px 0; align-items: stretch;
}
@media (max-width: 760px) { .editor-container { grid-template-columns: minmax(0, 1fr); } }
.editor-container .editor-panel, .editor-container .preview-panel {
display: flex; flex-direction: column; min-width: 0; overflow: hidden;
border: 1px solid var(--line, rgba(15, 61, 40, .18)); border-radius: 10px; background: #fff;
}
.editor-container .panel-header {
display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 12px;
background: var(--green-900, #0f3d28); color: #fff;
font: 600 12px/1.2 'Sora', system-ui, sans-serif; letter-spacing: .05em; text-transform: uppercase;
}
.editor-container .editor-buttons { display: flex; gap: 6px; }
.editor-container .editor-buttons button {
font: 600 12px/1 'Sora', system-ui, sans-serif; padding: 6px 12px; border-radius: 6px; cursor: pointer;
border: 1px solid rgba(255, 255, 255, .35); background: rgba(255, 255, 255, .12); color: #fff;
}
.editor-container .editor-buttons .btn-run { background: var(--green-500, #34c759); border-color: var(--green-500, #34c759); color: #0b2016; }
.editor-container .editor-buttons button:hover { filter: brightness(1.12); }
.editor-container .editor-buttons button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.editor-container textarea {
flex: 1; width: 100%; min-height: 220px; resize: vertical; border: 0; outline: 0; margin: 0; padding: 12px 14px;
background: #1a1a1a; color: #e6e6e6; tab-size: 2; white-space: pre; overflow: auto;
font: 13.5px/1.55 ui-monospace, 'Cascadia Code', 'Fira Code', monospace;
}
.editor-container textarea:focus-visible { box-shadow: inset 0 0 0 2px var(--green-500, #34c759); }
.editor-container iframe { flex: 1; width: 100%; min-height: 220px; border: 0; background: #fff; }
.editor-container[data-pg-lang="javascript"] iframe, .editor-container[data-pg-lang="python"] iframe { background: #1a1a1a; }
/* CodeHub lesson callouts and sections, unstyled in the plain learn template */
.learn-body .analogy, .learn-body .info-box {
margin: 16px 0; padding: 14px 18px; border-radius: 10px; border-left: 4px solid var(--green-600, #22a65a);
background: var(--green-100, #d9f5e3); color: var(--green-900, #0f3d28); font-size: 15.5px; line-height: 1.65;
}
.learn-body .info-box { border-left-color: #2f7fd3; background: #e8f1fb; color: #123a63; }
.learn-body .lesson-header h1 { font-family: 'Sora', system-ui, sans-serif; font-size: clamp(26px, 3vw, 36px); margin: 0 0 8px; }
.learn-body .try-it, .learn-body .challenge { margin-top: 28px; }
.learn-body .challenge { padding: 6px 18px 12px; border: 1px dashed var(--green-600, #22a65a); border-radius: 12px; }
/* Lesson playground [5818]
*
* Makes the "Try it yourself" blocks of migrated CodeHub lessons work on the learn pages.
* A block is the markup CodeHub lessons already carry:
*
*
*
* No data-lang means html (the HTML and CSS course blocks). The code runs in a sandboxed iframe
* (sandbox="allow-scripts", no allow-same-origin): it cannot read the page, its cookies or storage.
* JavaScript mirrors console.* into the output; Python runs on Skulpt (loaded from jsDelivr, as CodeHub does).
* Plain ES5 on purpose: the file is inlined into WordPress pages without a build step.
*/
(function () {
'use strict';
if (window.__pgPlayground) { window.__pgPlayground.scan(document); return; }
var SKULPT = [
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt.min.js',
'https://cdn.jsdelivr.net/npm/[email protected]/dist/skulpt-stdlib.js'
];
var AUTO_RUN_DELAY = 400;
var LANGS = { html: 1, css: 1, javascript: 1, python: 1 };
// Source text for a script that runs inside the generated document. JSON.stringify output is safe in a
// script block except for a closing script tag, an HTML comment opener and the two line separators, so escape
// every "<" and U+2028/2029.
function js(value) {
return JSON.stringify(value).replace(/</g, '\\u003c').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
var OUTPUT_STYLE =
'body{font:13px/1.45 "Cascadia Code","Fira Code",ui-monospace,monospace;padding:12px;margin:0;background:#1a1a1a;color:#d4d4d4}' +
'.line{padding:1px 0;white-space:pre-wrap;word-break:break-word}.warn{color:#e5c07b}.error{color:#e06c75}.info{color:#61afef}.hint{color:#8a8a8a;font-style:italic}';
function javascriptDoc(code) {
return '' + OUTPUT_STYLE + '' +
'(function(){var out=document.getElementById("out");' +
'function show(args,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");' +
'd.textContent=Array.prototype.map.call(args,function(a){if(a===null)return "null";if(a===undefined)return "undefined";' +
'if(typeof a==="object"){try{return JSON.stringify(a,null,2)}catch(e){return String(a)}}return String(a)}).join(" ");out.appendChild(d)}' +
'console.log=function(){show(arguments,"")};console.info=function(){show(arguments,"info")};' +
'console.warn=function(){show(arguments,"warn")};console.error=function(){show(arguments,"error")};' +
'window.alert=function(m){show(["alert: "+m],"info")};' +
'window.addEventListener("error",function(e){show([e.message],"error")});' +
'window.addEventListener("unhandledrejection",function(e){show(["Unhandled rejection: "+(e.reason&&e.reason.message||e.reason)],"error")});' +
'try{(0,eval)(' + js(code) + ')}catch(e){show([String(e)],"error")}})();' +
'';
}
function pythonDoc(code) {
return '' + OUTPUT_STYLE + '' +
'' +
'(function(){var out=document.getElementById("out");' +
'function line(t,cls){var d=document.createElement("div");d.className="line"+(cls?" "+cls:"");d.textContent=t;out.appendChild(d)}' +
'if(typeof Sk==="undefined"){out.innerHTML="";line("Could not load the Python runtime. Check your connection and press Run again.","error");return}' +
'out.innerHTML="";' +
'function read(x){if(Sk.builtinFiles===undefined||Sk.builtinFiles.files[x]===undefined)throw "File not found: \'"+x+"\'";return Sk.builtinFiles.files[x]}' +
'Sk.configure({output:function(t){var parts=t.split("\\n");parts.forEach(function(p,i){if(i<parts.length-1||p!=="")line(p)})},' +
'read:read,__future__:Sk.python3,inputfun:function(){return ""}});' +
'Sk.misceval.asyncToPromise(function(){return Sk.importMainWithBody("",false,' + js(code) + ',true)})' +
'.catch(function(e){line(String(e),"error")})})();' +
'';
}
function htmlDoc(code) {
if (/<!doctype|]/i.test(code)) { return code; }
return 'body{font-family:Arial,sans-serif;padding:16px}' + code + '';
}
function buildDoc(lang, code) {
if (lang === 'javascript') { return javascriptDoc(code); }
if (lang === 'python') { return pythonDoc(code); }
return htmlDoc(code);
}
function langOf(box) {
var l = (box.getAttribute('data-lang') || 'html').toLowerCase();
return Object.prototype.hasOwnProperty.call(LANGS, l) ? l : 'html';
}
function ensure(parent, selector, make) {
var el = parent.querySelector(selector);
if (!el) { el = make(); parent.appendChild(el); }
return el;
}
function element(tag, className, text) {
var e = document.createElement(tag);
if (className) { e.className = className; }
if (text) { e.textContent = text; }
return e;
}
function setup(box) {
if (box.getAttribute('data-pg-ready')) { return; }
var lang = langOf(box);
var editor = box.querySelector('.editor-panel');
var textarea = box.querySelector('textarea');
if (!editor || !textarea) { return; }
box.setAttribute('data-pg-ready', '1');
box.setAttribute('data-pg-lang', lang);
var preview = ensure(box, '.preview-panel', function () {
var p = element('div', 'preview-panel');
var h = element('div', 'panel-header');
h.appendChild(element('span', '', lang === 'html' || lang === 'css' ? 'Result' : 'Output'));
p.appendChild(h);
return p;
});
var frame = preview.querySelector('iframe');
if (!frame) {
frame = document.createElement('iframe');
preview.appendChild(frame);
}
frame.setAttribute('sandbox', 'allow-scripts');
frame.setAttribute('title', lang === 'html' || lang === 'css' ? 'Result' : 'Output');
frame.setAttribute('loading', 'lazy');
frame.setAttribute('referrerpolicy', 'no-referrer');
textarea.setAttribute('spellcheck', 'false');
textarea.setAttribute('aria-label', 'Code editor');
var buttons = ensure(editor.querySelector('.panel-header') || editor, '.editor-buttons', function () { return element('div', 'editor-buttons'); });
var run = buttons.querySelector('.btn-run') || buttons.appendChild(element('button', 'btn-run', 'Run'));
var reset = buttons.querySelector('.btn-reset') || buttons.appendChild(element('button', 'btn-reset', 'Reset'));
run.type = 'button';
reset.type = 'button';
var initial = textarea.value;
var live = lang === 'html' || lang === 'css';
var timer = null;
function render() {
if (timer) { clearTimeout(timer); timer = null; }
frame.srcdoc = buildDoc(lang, textarea.value);
}
run.addEventListener('click', render);
reset.addEventListener('click', function () {
textarea.value = initial;
if (live) { render(); } else { frame.srcdoc = emptyDoc(); }
});
textarea.addEventListener('keydown', function (e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); render(); }
});
if (live) {
textarea.addEventListener('input', function () {
if (timer) { clearTimeout(timer); }
timer = setTimeout(render, AUTO_RUN_DELAY);
});
render();
} else {
frame.srcdoc = emptyDoc();
}
}
function emptyDoc() {
return '' + OUTPUT_STYLE + 'Press Run (or Ctrl+Enter) to see the output.
';
}
function scan(root) {
var boxes = (root || document).querySelectorAll('.editor-container');
for (var i = 0; i < boxes.length; i++) { setup(boxes[i]); }
}
window.__pgPlayground = { scan: scan, buildDoc: buildDoc };
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { scan(document); }); }
else { scan(document); }
})();
Promises
A Promise represents the eventual result of an asynchronous operation. It can be pending, fulfilled, or rejected.
In simple terms
Promises: Dealing with "Not Yet"
Imagine ordering food at a restaurant. You don't get the food immediately - you get a promise that it will come. While waiting you can do other things. When the food arrives, you eat it. If the kitchen burns it, you complain!
A Promise in JavaScript works the same way. It represents a value that will be available in the future:
const myPromise = new Promise((resolve, reject) => { // simulate an async operation setTimeout(() => { resolve("Food is ready!"); // success // reject("Kitchen on fire!"); // failure }, 1000); });
Handle the result with .then() and .catch():
myPromise .then(result => console.log(result)) // "Food is ready!" .catch(error => console.log(error)); // handles failure
Chain multiple steps:
fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Failed:", error));
Deep dive
Promises: Technical Reference
Promise States
A Promise is always in one of three states: pending (initial, neither fulfilled nor rejected), fulfilled (operation succeeded, has a value), or rejected (operation failed, has a reason). Once settled (fulfilled or rejected), state cannot change.
Creating Promises
const p = new Promise((resolve, reject) => { if (success) resolve(value); else reject(new Error("reason")); }); // Shorthand: Promise.resolve(value); Promise.reject(new Error("reason"));
Consuming Promises
.then(onFulfilled, onRejected) - returns a new Promise; onFulfilled receives the value. .catch(onRejected) - shorthand for .then(undefined, onRejected). .finally(callback) - runs regardless of outcome, receives no value.
Promise Combinators
Promise.all([p1,p2,p3]) - resolves when ALL resolve; rejects if ANY rejects. Ideal for parallel independent operations. Promise.allSettled([...]) - resolves when ALL settle; gives status of each. Never rejects. Promise.race([...]) - settles with the first to settle (fulfilled or rejected). Promise.any([...]) - resolves with the first to fulfil; rejects if ALL reject (AggregateError).
Microtask Queue
Promise callbacks (.then, .catch) are placed in the microtask queue, which is processed after the current task completes but before any macrotasks (setTimeout, setInterval). This gives Promises priority over setTimeout callbacks.
Reference: MDN Promise.
Challenge
Challenge: Promise Chain
Simulate a multi-step user registration process using Promises:
- Step 1:
validateEmail(email) - returns a Promise that resolves if email contains "@", rejects otherwise. - Step 2:
createUser(email) - returns a Promise that resolves with a user object {id: 1, email} after 500ms. - Step 3:
sendWelcomeEmail(user) - returns a Promise that resolves with "Email sent to user.email".
Chain them and handle both success and failure cases. Then use Promise.all to run two registrations in parallel.
Summary
- A Promise represents a future value and is in one of three states: pending, fulfilled, or rejected.
- Use .then() for success handling, .catch() for errors, .finally() for cleanup regardless of outcome.
- Promise chains return new Promises allowing sequential async operations to be expressed linearly.
- Promise.all runs Promises in parallel and waits for all to resolve; Promise.allSettled never rejects.
- Promise callbacks run in the microtask queue - after the current task but before setTimeout callbacks.
async / await
async/await is syntactic sugar over Promises that lets you write asynchronous code that looks and reads like synchronous code.
In simple terms
async / await: Async Code That Reads Like Normal Code
Promises with .then() chains can get complex. async/await makes async code look like regular step-by-step code:
With Promises:
fetchUser(1) .then(user => fetchPosts(user.id)) .then(posts => console.log(posts)) .catch(err => console.error(err));
With async/await:
async function loadUserPosts() { try { const user = await fetchUser(1); const posts = await fetchPosts(user.id); console.log(posts); } catch (err) { console.error(err); } }
Key rules:
async before a function makes it return a Promise. await pauses execution until the Promise resolves. await can only be used inside async functions (or at the module top level). - Use
try/catch for error handling.
Deep dive
async / await: Technical Reference
async Functions
An async function always returns a Promise. If the function returns a value, the Promise fulfils with that value. If the function throws, the Promise rejects with the thrown error.
await
await unwraps a Promise: it pauses the async function's execution until the Promise settles, then returns the fulfilled value. If the Promise rejects and the rejection is not caught, the async function's returned Promise rejects. await only pauses the current async function - other code on the event loop continues.
Error Handling
async function safe() { try { const data = await riskyOperation(); return data; } catch (err) { console.error(err); return null; // fallback } finally { cleanup(); } }
Alternative: use .catch() on the awaited promise directly: const data = await riskyOp().catch(() => null).
Parallel Execution
Awaiting sequentially means each operation waits for the previous. For parallel, use Promise.all:
// Sequential (slow) const a = await fetchA(); const b = await fetchB(); // Parallel (fast) const [a, b] = await Promise.all([fetchA(), fetchB()]);
Top-Level await
In ES modules (type="module"), await can be used at the top level without an async function wrapper.
Reference: MDN async function.
Challenge
Challenge: Sequential vs Parallel
Given a delay(ms) function that returns a Promise resolving after ms milliseconds:
- Write an async function that awaits three 1-second delays sequentially and logs the total time.
- Write an async function that runs all three delays in parallel with Promise.all and logs the total time.
- Add try/catch to handle a function that randomly rejects.
Summary
- async functions always return a Promise; await unwraps a Promise inside an async function.
- await pauses only the current async function - the event loop continues processing other tasks.
- Use try/catch/finally inside async functions for error handling, just like synchronous code.
- Awaiting in sequence is slow when operations are independent; use Promise.all for parallel execution.
- Top-level await is available in ES modules without an async wrapper.
Fetch API
The Fetch API is the modern way to make HTTP requests from JavaScript. It returns Promises and supports all HTTP methods.
In simple terms
Fetch API: Getting Data from the Internet
The fetch() function lets your JavaScript get data from the internet or send data to a server. It is like a built-in search assistant!
async function getJoke() { const response = await fetch("https://official-joke-api.appspot.com/random_joke"); const joke = await response.json(); console.log(joke.setup); console.log(joke.punchline); } getJoke();
Two steps: first await fetch(url) to get the response, then await response.json() to parse the body.
Send data with POST:
async function createPost(data) { const response = await fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); const result = await response.json(); console.log(result); } createPost({ title: "Hello", body: "World", userId: 1 });
Deep dive
Fetch API: Technical Reference
Basic Fetch
const response = await fetch(url, options);
Returns a Promise that resolves to a Response object. Important: fetch only rejects on network failure. A 404 or 500 response is considered a resolved Promise! Always check response.ok (true for 2xx status codes):
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
Response Methods
response.json() - parses body as JSON. response.text() - body as plain text. response.blob() - body as Blob (binary). response.formData() - body as FormData. response.arrayBuffer() - body as ArrayBuffer. response.headers.get("Content-Type") - read response headers. response.status, response.statusText, response.ok - status info.
Request Options
fetch(url, { method: "POST", // GET, POST, PUT, PATCH, DELETE headers: { "Content-Type": "application/json", "Authorization": "Bearer token" }, body: JSON.stringify(payload), // request body credentials: "include", // send cookies cross-origin signal: abortController.signal, // AbortController for cancellation cache: "no-cache" });
Aborting Requests
const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); // 5s timeout const response = await fetch(url, { signal: controller.signal });
Reference: MDN Fetch API.
Challenge
Challenge: Public API Explorer
Using fetch and async/await:
- Fetch a list of posts from
https://jsonplaceholder.typicode.com/posts?_limit=5. - Log the title of each post.
- Then fetch the user for the first post's userId from
https://jsonplaceholder.typicode.com/users/{id}. - Log the user's name and email.
- Handle both network errors and non-ok responses.
Summary
- fetch(url) returns a Promise for a Response object; it only rejects on network failure, not HTTP errors.
- Always check response.ok before parsing; throw for non-2xx status codes.
- Call response.json(), response.text(), or response.blob() to read the body (each also returns a Promise).
- Pass an options object as the second argument to set method, headers, body, credentials, and signal.
- Use AbortController to cancel pending requests (timeouts, component unmounts).
Error Handling
Errors are inevitable. JavaScript provides try/catch/finally and a hierarchy of Error types to handle them gracefully.
In simple terms
Error Handling: When Things Go Wrong
Errors happen. A user types the wrong thing, a server is down, a file doesn't exist. Good code handles these gracefully instead of crashing.
The try/catch block catches errors:
try { const result = JSON.parse("not valid json"); console.log(result); } catch (error) { console.log("Something went wrong:", error.message); } console.log("Program continues!");
finally always runs - great for cleanup:
try { doRiskyOperation(); } catch (err) { console.error("Error:", err.message); } finally { closeConnection(); // always runs }
Throw your own errors:
function divide(a, b) { if (b === 0) throw new Error("Cannot divide by zero!"); return a / b; } try { console.log(divide(10, 0)); } catch (err) { console.log(err.message); // Cannot divide by zero! }
Deep dive
Error Handling: Technical Reference
try/catch/finally
The try block runs until an error is thrown. The catch block runs with the error object. Finally runs unconditionally. All three blocks share the same outer scope but each has its own block scope.
Error Types
Error - base class. SyntaxError - invalid syntax (usually parse-time). ReferenceError - accessing an undeclared variable. TypeError - wrong type operation (calling non-function, accessing property of null). RangeError - value out of range (Array(-1), recursion depth exceeded). URIError - malformed URI passed to encodeURI. EvalError - deprecated, rarely seen.
Custom Error Classes
class ValidationError extends Error { constructor(message, field) { super(message); this.name = "ValidationError"; this.field = field; } } try { throw new ValidationError("Required", "email"); } catch (err) { if (err instanceof ValidationError) { console.log(`${err.field}: ${err.message}`); } else { throw err; // re-throw unknown errors } }
Error Properties
error.message - human-readable description. error.name - type name (e.g., "TypeError"). error.stack - stack trace string (non-standard but universal). error.cause - original error passed as { cause: originalError } (ES2022).
Unhandled Rejections
window.addEventListener("unhandledrejection", (event) => { console.error("Unhandled:", event.reason); event.preventDefault(); // optional: suppress browser console error });
Reference: MDN try...catch.
Challenge
Challenge: Robust JSON Parser
Write a function safeJsonParse(str, fallback) that:
- Attempts to parse the string as JSON.
- Returns the parsed value on success.
- Returns
fallback if parsing fails (default: null). - Logs the error message to console.warn (don't silently swallow errors).
Also write a function fetchWithTimeout(url, ms) that rejects with a TimeoutError if the fetch takes longer than ms milliseconds. Use a custom Error class for the timeout.
Summary
- try/catch/finally lets you handle errors gracefully; finally always runs regardless of outcome.
- JavaScript has built-in error types: Error, TypeError, ReferenceError, SyntaxError, RangeError.
- Extend Error to create custom error classes with instanceof-checkable types.
- Always include error.message and the stack trace in logs; use error.cause (ES2022) for error chaining.
- Re-throw errors you cannot handle so they propagate to a handler that can.
localStorage & JSON
localStorage lets you store data in the browser that persists across page reloads. JSON serialises JavaScript objects to strings and back.
In simple terms
localStorage & JSON: Remembering Things
localStorage is like a little notebook built into every browser. Your JavaScript can write things in it and read them back - even after the page is refreshed!
// Save localStorage.setItem("username", "Alice"); // Read const name = localStorage.getItem("username"); console.log(name); // "Alice" // Delete one item localStorage.removeItem("username"); // Delete everything localStorage.clear();
localStorage only stores strings. To save objects and arrays, use JSON.stringify() to convert them, and JSON.parse() to get them back:
const settings = { theme: "dark", fontSize: 16 }; // Save object localStorage.setItem("settings", JSON.stringify(settings)); // Load object const loaded = JSON.parse(localStorage.getItem("settings")); console.log(loaded.theme); // "dark"
JSON.stringify and JSON.parse also work for copying objects:
const copy = JSON.parse(JSON.stringify(settings)); // deep copy!
Deep dive
localStorage and JSON: Technical Reference
Web Storage API
localStorage persists until explicitly cleared. sessionStorage persists only for the browser tab session. Both implement the same Storage interface. Keys and values are always strings. Storage limit is typically 5-10 MB per origin.
localStorage Methods
setItem(key, value) - store (value coerced to string). getItem(key) - retrieve (null if key not found). removeItem(key) - delete one key. clear() - delete all keys for the origin. key(index) - get key name by index. length - number of stored items.
JSON.stringify
Serialises JavaScript to a JSON string. Supports a replacer (filter/transform keys) and space (pretty-print) arguments:
JSON.stringify(obj, null, 2); // pretty-printed with 2-space indent
Values that are undefined, functions, or Symbols are omitted. Circular references throw a TypeError.
JSON.parse
Parses a JSON string back to a JavaScript value. Supports a reviver function to transform values during parsing (e.g., converting date strings to Date objects):
const data = JSON.parse(str, (key, value) => key === "date" ? new Date(value) : value );
Security Considerations
localStorage is accessible by any JavaScript on the same origin - do NOT store sensitive data (passwords, tokens) there. Use HttpOnly cookies for authentication tokens. The storage event fires in other tabs of the same origin when localStorage changes.
Reference: MDN localStorage, MDN JSON.
Challenge
Challenge: Persistent Todo List
Build a todo list that persists in localStorage:
- Write
loadTodos() - reads todos array from localStorage or returns []. - Write
saveTodos(todos) - saves todos array to localStorage. - Write
addTodo(text) - adds a todo with id, text, and completed:false, then saves. - Write
toggleTodo(id) - flips the completed status of a todo by id, then saves. - Test by adding 3 todos and toggling one.
Summary
- localStorage stores string key-value pairs persistently across browser sessions; sessionStorage clears on tab close.
- Always use JSON.stringify before storing objects and JSON.parse when reading them back.
- getItem returns null (not undefined) when a key does not exist - always check before parsing.
- localStorage is origin-scoped and accessible to all JS on that origin; never store sensitive data there.
- JSON.stringify omits undefined, functions, and Symbol values; circular references throw TypeError.
Regular Expressions
Regular expressions (regex) are patterns used to match, search, and replace text. They are powerful but have a steep learning curve.
In simple terms
Regular Expressions: Pattern Matching
A regular expression is a pattern that describes a set of strings. Think of it as a search term with superpowers!
// Create a regex with /pattern/ or new RegExp("pattern") const pattern = /hello/; console.log(pattern.test("hello world")); // true console.log(pattern.test("goodbye")); // false
Common regex characters:
// . matches any character (except newline) /h.t/.test("hat"); // true /h.t/.test("hit"); // true // ^ starts with, $ ends with /^Hello/.test("Hello World"); // true /World$/.test("Hello World"); // true // + one or more, * zero or more, ? optional /go+/.test("gooo"); // true (one or more o) /colou?r/.test("color"); // true (u is optional) // \d digit, \w word char, \s whitespace /\d+/.test("abc123"); // true (one or more digits)
Find matches:
const str = "My phone is 555-1234"; const match = str.match(/\d{3}-\d{4}/); console.log(match[0]); // "555-1234"
Replace with regex:
const clean = "Hello World".replace(/\s+/g, " "); console.log(clean); // "Hello World"
Deep dive
Regular Expressions: Technical Reference
Regex Syntax
- Literals: match themselves.
. - any char except newline (use [\s\S] for all chars). ^ / $ - start / end of string (or line with m flag). \d / \D - digit / non-digit. \w / \W - word char [a-zA-Z0-9_] / non-word. \s / \S - whitespace / non-whitespace. \b - word boundary. [abc] - character class; [^abc] - negated class. a|b - alternation (a or b). (abc) - capturing group; (?:abc) - non-capturing. {n} / {n,m} / {n,} - exact / range / min quantifiers. + / * / ? - one-or-more / zero-or-more / zero-or-one. - Append
? to make quantifiers lazy: +? matches as few as possible.
Flags
g - global (find all matches). i - case insensitive. m - multiline (^ and $ match line boundaries). s - dotAll (. matches newline). u - unicode mode (full Unicode support). d - generate indices for substrings (ES2022).
Methods
regex.test(str) // boolean match str.match(regex) // array of matches (null if none) str.matchAll(regex) // iterator of all matches (needs g flag) str.replace(regex, rep) // replace (rep can be function) str.replaceAll(regex, rep) // replace all (regex must have g flag) str.search(regex) // index of first match (-1 if none) str.split(regex) // split by pattern
Named Capture Groups (ES2018)
const re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/; const { groups: { year, month, day } } = "2024-01-15".match(re);
Reference: MDN Regular Expressions.
Challenge
Challenge: Form Validator
Write validation functions using regex:
isValidEmail(str) - basic email format (contains @, a dot in domain). isValidPhone(str) - 10 digits, optionally formatted as (123) 456-7890 or 123-456-7890. isStrongPassword(str) - at least 8 chars, one uppercase, one lowercase, one digit. extractHashtags(str) - returns array of all hashtags in a string.
Test each with valid and invalid inputs.
Summary
- Regular expressions describe text patterns; create with /pattern/flags or new RegExp().
- Key meta-characters: . ^ $ * + ? [] () {} | and escape sequences \d \w \s \b.
- Flags modify behaviour: g (global), i (case-insensitive), m (multiline), s (dotAll).
- Use test() for existence, match() for extracting, replace() for substitution, split() for splitting.
- Named capture groups (?<name>) make complex patterns more readable and maintainable.
Dates & Times
JavaScript's Date object represents a moment in time. It provides methods to get, set, and format dates and times.
In simple terms
Dates & Times: Working with Clocks and Calendars
JavaScript has a built-in Date object for working with dates and times.
const now = new Date(); console.log(now); // current date and time const birthday = new Date("1990-05-15"); const specific = new Date(2024, 0, 15); // Jan 15 2024 (month is 0-indexed!)
Get individual parts:
const d = new Date(); console.log(d.getFullYear()); // e.g., 2024 console.log(d.getMonth()); // 0-11 (January = 0!) console.log(d.getDate()); // 1-31 (day of month) console.log(d.getDay()); // 0-6 (Sunday = 0) console.log(d.getHours()); // 0-23 console.log(d.getMinutes()); // 0-59
Format dates nicely:
const d = new Date("2024-01-15"); console.log(d.toLocaleDateString("en-GB")); // "15/01/2024" console.log(d.toLocaleDateString("en-US")); // "1/15/2024" const formatted = d.toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }); console.log(formatted); // "January 15, 2024"
Calculate time differences:
const start = new Date("2024-01-01"); const end = new Date("2024-12-31"); const diffMs = end - start; const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24)); console.log(diffDays + " days");
Deep dive
Dates and Times: Technical Reference
The Date Object Internally
A Date object stores a single number: milliseconds elapsed since the Unix Epoch (January 1, 1970 00:00:00 UTC). Retrieve it with date.getTime() or +date or Date.now() (no Date object needed). This epoch value is useful for arithmetic and sorting.
Creating Dates
new Date() // current moment new Date(milliseconds) // from epoch ms new Date("ISO-8601-string") // parse ISO string (safest string format) new Date(year, monthIndex, day, hours, minutes, seconds, ms) Date.now() // current epoch ms (no object)
Month index is 0-based (0 = January, 11 = December) - a common source of bugs.
Getter Methods
getFullYear, getMonth, getDate, getDay, getHours, getMinutes, getSeconds, getMilliseconds, getTime, getTimezoneOffset. UTC variants: getUTCFullYear, etc.
Setter Methods
setFullYear, setMonth, setDate, setHours, etc. Mutate the Date object.
Formatting with Intl.DateTimeFormat
For production use, prefer the Intl.DateTimeFormat API over toLocaleDateString:
const formatter = new Intl.DateTimeFormat("en-GB", { weekday: "long", year: "numeric", month: "short", day: "numeric" }); console.log(formatter.format(new Date())); // "Monday, 15 Jan 2024"
Temporal API (future)
The Temporal API is a Stage 3 TC39 proposal that will replace Date with a better, immutable, timezone-aware date library. Check MDN for current support.
Libraries
For complex date manipulation, consider date-fns (tree-shakeable) or Day.js (lightweight Moment.js alternative). Reference: MDN Date.
Challenge
Challenge: Age and Countdown Calculator
- Write a function
calculateAge(birthDateString) that returns a person's age in years (accounting for whether their birthday has passed this year). - Write a function
daysUntil(dateString) that returns the number of days until a given date (or negative if in the past). - Write a function
formatDate(date, locale) that returns a nicely formatted date string like "Monday, January 15, 2024". - Test all three functions with sample dates.
Summary
- The Date object stores a single number: milliseconds since the Unix Epoch (Jan 1, 1970 UTC).
- Month indices are 0-based: January is 0, December is 11 - a common off-by-one bug source.
- Date arithmetic works by comparing or subtracting epoch millisecond values.
- Use toLocaleDateString() or Intl.DateTimeFormat for locale-aware formatting.
- For complex date logic in production, use date-fns or Day.js instead of raw Date methods.
ES Modules
ES Modules are the official JavaScript module system. They let you split code into reusable files using import and export statements.
In simple terms
ES Modules: Organising Your Code
As projects grow, keeping all code in one file becomes unmanageable. Modules let you split code into separate files and share only what is needed.
Export from a file (math.js):
// math.js export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; } export const PI = 3.14159;
Import in another file (main.js):
// main.js import { add, subtract, PI } from "./math.js"; console.log(add(2, 3)); // 5 console.log(PI); // 3.14159
Rename on import:
import { add as sum, subtract as minus } from "./math.js"; console.log(sum(1, 2)); // 3
Import everything as a namespace:
import * as Math from "./math.js"; console.log(Math.add(2, 3)); console.log(Math.PI);
Default export (one per file):
// user.js export default function createUser(name) { return { name, createdAt: new Date() }; } // main.js import createUser from "./user.js"; // any name works for default const user = createUser("Alice");
Deep dive
ES Modules: Technical Reference
Module Scope
Each ES module has its own scope. Variables declared at the top level are NOT added to the global scope. Modules run in strict mode automatically.
Named vs Default Exports
Named exports: export const x = 1 or export { x, y }. Imported with their exact name (or renamed with as). Multiple per file. Default exports: export default value. One per file. Imported without curly braces, with any name. Mixing is allowed but can be confusing.
Re-exporting
Create barrel files (index.js) that re-export from multiple modules:
// index.js export { add, subtract } from "./math.js"; export { default as createUser } from "./user.js"; export * from "./utils.js";
Dynamic Import
Load modules on demand (code splitting, lazy loading):
async function loadModule() { const module = await import("./heavy-module.js"); module.doSomething(); }
Returns a Promise. Supported by all modern bundlers (Webpack, Vite, Rollup) for automatic code splitting.
Module Loading in the Browser
<script type="module" src="main.js"></script>
Module scripts are deferred by default, have CORS requirements for cross-origin loads, and cannot be embedded inline without a correct MIME type (text/javascript).
CommonJS vs ES Modules
Node.js historically used CommonJS (require/module.exports). ES modules are the standard; Node.js fully supports them with .mjs extension or "type":"module" in package.json. Key difference: ES module imports are static and analysable at build time; CommonJS requires are dynamic.
Reference: MDN JavaScript modules.
Challenge
Challenge: Utility Library
Design a small module system (conceptually - write the code as if it were in separate files):
- Create a
stringUtils module with named exports: capitalize, slugify, truncate(str, maxLen). - Create a
arrayUtils module with named exports: unique (removes duplicates), groupBy(arr, key). - Create an
index module that re-exports everything from both. - Write the consumer code that imports from index and tests all functions.
Write all the code as self-contained functions in the editor to simulate the module structure.
Summary
- ES Modules use import/export statements and give each file its own scope in strict mode.
- Named exports require curly braces on import and use the exact exported name (or rename with as).
- Default exports have one per file and can be imported with any name without curly braces.
- Dynamic import() loads modules on demand and returns a Promise - enabling code splitting.
- ES modules are static (analysable at build time) unlike CommonJS require which is dynamic.