### CSS and HTML for steps(9, start) demo Source: https://javascript.info/css-animations Complete example for the steps(9, start) animation. The click handler adds the 'animate' class to trigger the transition. The first step occurs immediately at 0s. ```css #digit { width: .5em; overflow: hidden; font: 32px monospace; cursor: pointer; } #stripe { display: inline-block } #stripe.animate { transform: translate(-90%); transition-property: transform; transition-duration: 9s; transition-timing-function: steps(9, start); } ``` ```markup Click below to animate:
0123456789
``` -------------------------------- ### HTML: Structure for the WeakRef DOM logger example Source: https://javascript.info/weakref-finalizationregistry This HTML provides the markup for the interactive example, including the start button, the window with header and body, and the script reference. ```markup WeakRef DOM Logger

Messages:

No messages.
``` -------------------------------- ### Create a Map from an array of key/value pairs Source: https://javascript.info/map-set Shows how to initialize a Map with an array of [key, value] pairs. The example uses different key types (string, number, boolean) and demonstrates get(). ```javascript // array of [key, value] pairs let map = new Map([ ['1', 'str1'], [1, 'num1'], [true, 'bool1'] ]); alert( map.get('1') ); // str1 ``` -------------------------------- ### camelize examples Source: https://javascript.info/array-methods Example calls demonstrating the camelize function output. ```javascript camelize("background-color") == 'backgroundColor'; camelize("list-style-image") == 'listStyleImage'; camelize("-webkit-transition") == 'WebkitTransition'; ``` -------------------------------- ### Examples of function names with prefixes Source: https://javascript.info/function-basics Shows typical function names using common prefixes: show, get, calc, create, and check. Each name indicates the action and the return type. ```javascript showMessage(..) // shows a message getAge(..) // returns the age (gets it somehow) calcSum(..) // calculates a sum and returns the result createForm(..) // creates a form (and usually returns it) checkPermission(..) // checks a permission, returns true/false ``` -------------------------------- ### substr with negative start Source: https://javascript.info/string substr allows a negative start to count from the end. Example: str.substr(-4, 2) returns 'gi'. ```javascript let str = "stringify"; alert( str.substr(-4, 2) ); // 'gi', from the 4th position get 2 characters ``` -------------------------------- ### Package file structure Source: https://javascript.info/import-export Example directory structure for a package with an entry point `auth/index.js` and internal modules. ```none auth/ index.js user.js helpers.js tests/ login.js providers/ github.js facebook.js ... ``` -------------------------------- ### substr with length Source: https://javascript.info/string substr returns a substring starting at start with the given length. Example: str.substr(2, 4) returns 'ring'. ```javascript let str = "stringify"; alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters ``` -------------------------------- ### User class example with constructor and method Source: https://javascript.info/class Example of a User class with a constructor that sets the name and a sayHi method that alerts the name. Instantiate with new User("John") and call user.sayHi(). ```javascript class User { constructor(name) { this.name = name; } sayHi() { alert(this.name); } } // Usage: let user = new User("John"); user.sayHi(); ``` -------------------------------- ### slice with start and end Source: https://javascript.info/string Returns the substring from start to end (not including end). The example shows extracting 'strin' and 's' from 'stringify'. ```javascript let str = "stringify"; alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5) alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0 ``` -------------------------------- ### Using document.getElementsByTagName('div') to get all divs Source: https://javascript.info/searching-elements-dom The `getElementsByTagName` method returns a live collection of elements with the given tag. This example shows how to get all divs in the document. ```javascript // get all divs in the document let divs = document.getElementsByTagName('div'); ``` -------------------------------- ### Full working example: fetch with download progress Source: https://javascript.info/fetch-progress This complete example fetches a GitHub API URL, reads the response stream chunk-by-chunk, tracks the received byte count against the Content-Length header, and logs progress. It then concatenates the chunks into a single Uint8Array, decodes it with TextDecoder, and parses the JSON result. Note that using a reader prevents using response.json() on the same response. ```javascript // Step 1: start the fetch and obtain a reader let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100'); const reader = response.body.getReader(); // Step 2: get total length const contentLength = +response.headers.get('Content-Length'); // Step 3: read the data let receivedLength = 0; // received that many bytes at the moment let chunks = []; // array of received binary chunks (comprises the body) while(true) { const {done, value} = await reader.read(); if (done) { break; } chunks.push(value); receivedLength += value.length; console.log(`Received ${receivedLength} of ${contentLength}`) } // Step 4: concatenate chunks into single Uint8Array let chunksAll = new Uint8Array(receivedLength); // (4.1) let position = 0; for(let chunk of chunks) { chunksAll.set(chunk, position); // (4.2) position += chunk.length; } // Step 5: decode into a string let result = new TextDecoder("utf-8").decode(chunksAll); // We're done! let commits = JSON.parse(result); alert(commits[0].author.login); ``` -------------------------------- ### Initialize request with xhr.open Source: https://javascript.info/xmlhttprequest Configures the request method, URL, and optional parameters. Does not open the connection; network activity starts only with send(). ```javascript xhr.open(method, URL, [async, user, password]) ``` -------------------------------- ### Usage example for pseudoRandom generator Source: https://javascript.info/generators Example of how the pseudoRandom(seed) generator is expected to be used. It creates a generator and calls next().value to get successive values. ```javascript let generator = pseudoRandom(1); alert(generator.next().value); // 16807 alert(generator.next().value); // 282475249 alert(generator.next().value); // 1622650073 ``` -------------------------------- ### Count properties example with user object Source: https://javascript.info/keys-values-entries Task example: defines a user object and calls count to get the number of properties. The expected output is 2. ```javascript let user = { name: 'John', age: 30 }; alert( count(user) ); // 2 ``` -------------------------------- ### Full XMLHttpRequest example with progress Source: https://javascript.info/xmlhttprequest Complete example that loads a URL and prints progress. Uses onload to check HTTP status, onprogress to show download progress, and onerror for network failures. ```javascript // 1. Create a new XMLHttpRequest object let xhr = new XMLHttpRequest(); // 2. Configure it: GET-request for the URL /article/.../load xhr.open('GET', '/article/xmlhttprequest/example/load'); // 3. Send the request over the network xhr.send(); // 4. This will be called after the response is received xhr.onload = function() { if (xhr.status != 200) { // analyze HTTP status of the response alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found } else { // show the result alert(`Done, got ${xhr.response.length} bytes`); // response is the server response } }; xhr.onprogress = function(event) { if (event.lengthComputable) { alert(`Received ${event.loaded} of ${event.total} bytes`); } else { alert(`Received ${event.loaded} bytes`); // no Content-Length } }; xhr.onerror = function() { alert("Request failed"); }; ``` -------------------------------- ### Full example: say.js and index.html Source: https://javascript.info/modules-dynamic-imports Complete example showing a module with named and default exports, and an HTML page that dynamically imports it and calls all exports. Note that dynamic imports work in regular scripts without script type="module". ```javascript export function hi() { alert(`Hello`); } export function bye() { alert(`Bye`); } export default function() { alert("Module loaded (export default)!"); } ``` ```markup ``` -------------------------------- ### Basic sequence generator: generateSequence(start, end) Source: https://javascript.info/generators Defines a generator function that yields numbers from start to end inclusive. Used as the building block for composition examples. ```javascript function* generateSequence(start, end) { for (let i = start; i <= end; i++) yield i; } ``` -------------------------------- ### substring swaps start and end Source: https://javascript.info/string substring allows start to be greater than end, swapping them. The example shows that substring(2,6) and substring(6,2) both return 'ring', while slice(6,2) returns an empty string. ```javascript let str = "stringify"; // these are same for substring alert( str.substring(2, 6) ); // "ring" alert( str.substring(6, 2) ); // "ring" // ...but not for slice: alert( str.slice(2, 6) ); // "ring" (the same) alert( str.slice(6, 2) ); // "" (an empty string) ``` -------------------------------- ### Initial Rabbit prototype setup Source: https://javascript.info/function-prototype Creates a Rabbit constructor with a prototype containing eats: true, then alerts rabbit.eats which is true. ```javascript function Rabbit() {} Rabbit.prototype = { eats: true }; let rabbit = new Rabbit(); alert( rabbit.eats ); // true ``` -------------------------------- ### Runnable example with real script Source: https://javascript.info/callbacks A complete example that loads lodash from a CDN and uses a callback to alert when the script is loaded and to access the lodash function. ```javascript function loadScript(src, callback) { let script = document.createElement('script'); script.src = src; script.onload = () => callback(script); document.head.append(script); } loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => { alert(`Cool, the script ${script.src} is loaded`); alert( _ ); // _ is a function declared in the loaded script }); ``` -------------------------------- ### Clock class rewritten in class syntax Source: https://javascript.info/class Solution to the task: rewrites the functional Clock class using class syntax. Includes constructor, render, stop, and start methods, and an example usage that starts the clock. ```javascript class Clock { constructor({ template }) { this.template = template; } render() { let date = new Date(); let hours = date.getHours(); if (hours < 10) hours = '0' + hours; let mins = date.getMinutes(); if (mins < 10) mins = '0' + mins; let secs = date.getSeconds(); if (secs < 10) secs = '0' + secs; let output = this.template .replace('h', hours) .replace('m', mins) .replace('s', secs); console.log(output); } stop() { clearInterval(this.timer); } start() { this.render(); this.timer = setInterval(() => this.render(), 1000); } } let clock = new Clock({template: 'h:m:s'}); clock.start(); ``` -------------------------------- ### Partial application for login - solution with bind Source: https://javascript.info/bind Solution using bind to create partial functions with the correct context and first argument. ```javascript askPassword(user.login.bind(user, true), user.login.bind(user, false)); ``` -------------------------------- ### Sum salaries with Object.values and for..of Source: https://javascript.info/keys-values-entries Task example: defines a salaries object and calls sumSalaries to get the sum. The expected output is 650. ```javascript let salaries = { "John": 100, "Pete": 300, "Mary": 250 }; alert( sumSalaries(salaries) ); // 650 ``` -------------------------------- ### Map to objects: example input Source: https://javascript.info/array-methods Defines user objects with name, surname, and id, then shows a placeholder for mapping to objects with fullName and id. Expected output is shown in a comment. ```javascript let john = { name: "John", surname: "Smith", id: 1 }; let pete = { name: "Pete", surname: "Hunt", id: 2 }; let mary = { name: "Mary", surname: "Key", id: 3 }; let users = [ john, pete, mary ]; let usersMapped = /* ... your code ... */ /* usersMapped = [ { fullName: "John Smith", id: 1 }, { fullName: "Pete Hunt", id: 2 }, { fullName: "Mary Key", id: 3 } ] */ alert( usersMapped[0].id ) // 1 alert( usersMapped[0].fullName ) // John Smith ``` -------------------------------- ### Start CSS transition from current second using negative transition-delay Source: https://javascript.info/css-animations Complete example that starts the digit stripe animation from the current second by setting a negative transition-delay. The JavaScript calculates the current second and sets the transitionDelay style property before adding the 'animate' class. ```javascript stripe.onclick = function() { let sec = new Date().getSeconds() % 10; stripe.style.transitionDelay = '-' + sec + 's'; stripe.classList.add('animate'); }; ``` ```css #digit { width: .5em; overflow: hidden; font: 32px monospace; cursor: pointer; } #stripe { display: inline-block } #stripe.animate { transform: translate(-90%); transition-property: transform; transition-duration: 9s; transition-timing-function: linear; } ``` ```markup Click below to animate:
0123456789
``` -------------------------------- ### Complete easeOut bounce example (CSS, HTML, JavaScript) Source: https://javascript.info/js-animation Full working example showing a brick bouncing with easeOut. Includes CSS for styling, HTML structure, and JavaScript that uses makeEaseOut and the animate function. ```css #brick { width: 40px; height: 20px; background: #EE6B47; position: relative; cursor: pointer; } #path { outline: 1px solid #E8C48E; width: 540px; height: 20px; } ``` ```markup
``` -------------------------------- ### Open database and add books with idb wrapper Source: https://javascript.info/indexeddb Uses idb.openDB to initialize a database and create an object store, then adds books in a transaction with try/catch. The transaction.complete promise resolves when the transaction finishes. ```javascript let db = await idb.openDB('store', 1, db => { if (db.oldVersion == 0) { // perform the initialization db.createObjectStore('books', {keyPath: 'id'}); } }); let transaction = db.transaction('books', 'readwrite'); let books = transaction.objectStore('books'); try { await books.add(...); await books.add(...); await transaction.complete; console.log('jsbook saved'); } catch(err) { console.log('error', err.message); } ``` -------------------------------- ### Range object for 'has' trap Source: https://javascript.info/proxy Defines a simple range object with start and end properties. Used as the target for the 'has' trap in the following example. ```javascript let range = { start: 1, end: 10 }; ``` -------------------------------- ### Demonstrating capturing and bubbling phases Source: https://javascript.info/bubbling-and-capturing This example sets click handlers on every element in the document to show the capturing and bubbling phases. Clicking on

triggers capturing from HTML to P, then bubbling from P to HTML. ```markup

FORM
DIV

P

``` -------------------------------- ### slice without end argument Source: https://javascript.info/string When the second argument is omitted, slice returns the substring from start to the end of the string. Example: str.slice(2) returns 'ringify'. ```javascript let str = "stringify"; alert( str.slice(2) ); // 'ringify', from the 2nd position till the end ``` -------------------------------- ### setInterval Source: https://javascript.info/settimeout-setinterval Runs a function repeatedly, starting after the interval of time, then repeating continuously at that interval. (Note: The source mentions setInterval but does not provide detailed syntax or examples.) ```APIDOC ## setInterval ### Description Runs a function repeatedly, starting after the interval of time, then repeating continuously at that interval. ### Notes - The source only mentions that setInterval allows repeated execution but does not provide detailed syntax or parameters. ``` -------------------------------- ### CSS transition-property and transition-duration for transform Source: https://javascript.info/css-animations CSS rule that animates the transform property with a 9s duration. This is the core transition setup used in the digit stripe example. ```css #stripe.animate { transform: translate(-90%); transition-property: transform; transition-duration: 9s; } ``` -------------------------------- ### Fetch JSON with promise syntax Source: https://javascript.info/fetch Same as the previous example but using promise chaining instead of await. Fetches the same GitHub API and alerts the first commit author's login. ```javascript fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits') .then(response => response.json()) .then(commits => alert(commits[0].author.login)); ``` -------------------------------- ### Using || [] to always get an array from str.match Source: https://javascript.info/regexp-introduction To avoid the null error, combine str.match with || [] so that the result is always an array. The example shows how to safely check for matches. ```javascript let matches = "JavaScript".match(/HTML/) || []; if (!matches.length) { alert("No matches"); // now it works } ``` -------------------------------- ### Promise.all example with fetch Source: https://javascript.info/promise-api Shows how Promise.all rejects as a whole if any promise rejects, suitable for 'all or nothing' cases where all results are needed to proceed. ```javascript Promise.all([ fetch('/template.html'), fetch('/style.css'), fetch('/data.json') ]).then(render); // render method needs results of all fetches ``` -------------------------------- ### Get selected values from multi-select Source: https://javascript.info/form-elements Shows how to retrieve all selected values from a multi-select element by filtering the options collection and mapping to their values. The example uses a select with the multiple attribute. ```markup ``` -------------------------------- ### runOnKeys usage example Source: https://javascript.info/keyboard-events Shows how to call runOnKeys to display an alert when 'Q' and 'W' are pressed together. The keys are specified by their KeyboardEvent.code values (KeyQ, KeyW). ```javascript runOnKeys( () => alert("Hello!"), "KeyQ", "KeyW" ); ``` -------------------------------- ### Access form elements via form.elements Source: https://javascript.info/form-elements Demonstrates getting a form and its input elements using form.elements. The example includes HTML markup and a script that alerts the value of the input. ```markup
``` -------------------------------- ### Map to names: example input Source: https://javascript.info/array-methods Defines user objects and an array, then shows a placeholder for mapping to names. The expected output is an array of names. ```javascript let john = { name: "John", age: 25 }; let pete = { name: "Pete", age: 30 }; let mary = { name: "Mary", age: 28 }; let users = [ john, pete, mary ]; let names = /* ... your code */ alert( names ); // John, Pete, Mary ``` -------------------------------- ### alert example Source: https://javascript.info/alert-prompt-confirm Shows a modal window with the message 'Hello' and waits for the user to press OK. ```javascript alert("Hello"); ``` -------------------------------- ### Are counters independent - makeCounter example Source: https://javascript.info/closure Shows that each call to makeCounter creates a new independent lexical environment with its own 'count'. The second counter starts at 0, so the alerts show 0 and 1. ```javascript function makeCounter() { let count = 0; return function() { return count++; }; } let counter = makeCounter(); let counter2 = makeCounter(); alert( counter() ); // 0 alert( counter() ); // 1 alert( counter2() ); // ? alert( counter2() ); // ? ``` -------------------------------- ### Finding all input tags inside a table with getElementsByTagName Source: https://javascript.info/searching-elements-dom This example demonstrates using `table.getElementsByTagName('input')` to get all input elements inside a table, then iterating over them to display their values and checked state. ```markup
Your age:
``` -------------------------------- ### Proxy constructor syntax Source: https://javascript.info/proxy Shows the basic syntax for creating a Proxy with a target and handler. ```javascript let proxy = new Proxy(target, handler) ``` -------------------------------- ### Create object store syntax Source: https://javascript.info/indexeddb Shows the synchronous syntax for creating an object store. The operation does not require await. keyOptions can include keyPath or autoIncrement. ```javascript db.createObjectStore(name[, keyOptions]); ``` -------------------------------- ### Create an image element and set its source Source: https://javascript.info/onload-onerror Shows how to create an image element in advance so the browser starts loading it and caches it, allowing immediate display when added to the document. ```javascript let img = document.createElement('img'); img.src = 'my.jpg'; ``` -------------------------------- ### HTML example with train image and onclick handler Source: https://javascript.info/css-animations HTML markup for a page with a train image that, when clicked, sets its left style to 400px, triggering a CSS animation with a Bezier curve. The example is used to illustrate how a Bezier curve with y values outside 0..1 moves the element beyond the start and end positions. ```markup ``` -------------------------------- ### Full example: receiving iframe and sender page Source: https://javascript.info/cross-window-communication Complete example with an iframe that listens for messages and a parent page with a form that sends messages to the iframe. The iframe displays the received data and origin, and the parent uses form.onsubmit to post the message. ```markup Receiving iframe. ``` ```markup
``` -------------------------------- ### EventSource message format example Source: https://javascript.info/server-sent-events Shows the format of messages sent by the server: each line starts with 'data:', messages are separated by double newlines, and multiline messages use multiple 'data:' lines. ```none data: Message 1 data: Message 2 data: Message 3 data: of two lines ``` -------------------------------- ### Workaround: bind methods to target for private fields Source: https://javascript.info/proxy Fixes the private field issue by using a get trap that binds methods to the target object. The example shows user.getName() returning 'Guest'. ```javascript class User { #name = "Guest"; getName() { return this.#name; } } let user = new User(); user = new Proxy(user, { get(target, prop, receiver) { let value = Reflect.get(...arguments); return typeof value == 'function' ? value.bind(target) : value; } }); alert(user.getName()); // Guest ``` -------------------------------- ### Using before, after, prepend, and append on a list Source: https://javascript.info/modifying-document Demonstrates inserting strings before and after an
    element, and inserting list items at the beginning and end using prepend and append. ```markup
    1. 0
    2. 1
    3. 2
    ``` -------------------------------- ### ESLint .eslintrc configuration example Source: https://javascript.info/coding-style Example .eslintrc file for ESLint. It extends the 'eslint:recommended' settings and enables browser, node, and ES6 environments. The rules disable 'no-console' and set indent to 2 spaces. ```javascript { "extends": "eslint:recommended", "env": { "browser": true, "node": true, "es6": true }, "rules": { "no-console": 0, "indent": 2 } } ``` -------------------------------- ### another.js - Using the configured module Source: https://javascript.info/modules-intro Imports sayHi from the configured admin module and calls it, showing the configured user. ```javascript // 📁 another.js import {sayHi} from './admin.js'; sayHi(); // Ready to serve, Pete! ```