### Standard GET Request with XMLHttpRequest
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/08-xmlhttprequest/article.md
A boilerplate example of performing a GET request, including error handling and progress tracking for the response download.
```javascript
let xhr = new XMLHttpRequest();
xhr.open('GET', '/my/url');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200) {
alert( 'Error: ' + xhr.status);
return;
}
};
xhr.onprogress = function(event) {
alert(`Loaded ${event.loaded} of ${event.total}`);
};
xhr.onerror = function() {
};
```
--------------------------------
### HTTP Request Headers Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/05-fetch-crossorigin/1-do-we-need-origin/task.md
Illustrates a typical HTTP request, highlighting the presence of both 'Origin' and 'Referer' headers. This example demonstrates how a request originating from 'http://javascript.info' to 'http://google.com' includes these headers.
```http
Accept: */*
Accept-Charset: utf-8
Accept-Encoding: gzip,deflate,sdch
Connection: keep-alive
Host: google.com
Origin: http://javascript.info
Referer: http://javascript.info/some/url
```
--------------------------------
### Full Fetch Download Progress Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/03-fetch-progress/article.md
This comprehensive example shows a complete workflow for tracking download progress with the Fetch API. It initiates a fetch request, obtains a stream reader, reads the total content length from headers, processes incoming data chunks, concatenates them into a single Uint8Array, and finally decodes the data into a JSON string. It also includes a note on how to create a Blob directly from chunks if binary data is needed.
```javascript
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits?per_page=100');
const reader = response.body.getReader();
const contentLength = +response.headers.get('Content-Length');
let receivedLength = 0;
let chunks = [];
while(true) {
const {done, value} = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} of ${contentLength}`)
}
let chunksAll = new Uint8Array(receivedLength);
let position = 0;
for(let chunk of chunks) {
chunksAll.set(chunk, position);
position += chunk.length;
}
let result = new TextDecoder("utf-8").decode(chunksAll);
let commits = JSON.parse(result);
alert(commits[0].author.login);
```
--------------------------------
### Demonstrating Capturing and Bubbling Phases
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/2-events/02-bubbling-and-capturing/article.md
A complete example attaching both capturing and bubbling listeners to all elements to observe the event propagation order.
```html
```
--------------------------------
### JavaScript Parameter Alignment Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/03-code-quality/02-coding-style/article.md
An example illustrating how to align function parameters with the opening bracket using spaces for indentation. This technique improves the readability of function calls with many parameters.
```javascript
show(parameters,
aligned, // 5 spaces padding at the left
one,
after,
another
) {
// ...
```
--------------------------------
### Basic Fetch GET Request with Async/Await
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/01-fetch/article.md
Demonstrates a basic GET request using the fetch() method with async/await syntax. It shows how to check if the HTTP response is successful (status 200-299) and then parse the response body as JSON.
```javascript
let url = 'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits';
let response = await fetch(url);
if (response.ok) {
let json = await response.json();
console.log(json);
} else {
alert("HTTP-Error: " + response.status);
}
```
--------------------------------
### Observe full document event flow
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/5-loading/01-onload-ondomcontentloaded/article.md
An example demonstrating the sequence of events during page load, including readyState changes, DOMContentLoaded, and window/element onload events.
```html
```
--------------------------------
### Implementing Test Lifecycle Hooks
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/03-code-quality/05-testing-mocha/article.md
Shows the usage of before, after, beforeEach, and afterEach hooks to manage setup and teardown logic for test suites and individual tests.
```javascript
describe("test", function() {
before(() => alert("Testing started – before all tests"));
after(() => alert("Testing finished – after all tests"));
beforeEach(() => alert("Before a test – enter a test"));
afterEach(() => alert("After a test – exit a test"));
it('test 1', () => alert(1));
it('test 2', () => alert(2));
});
```
--------------------------------
### Opening and Focusing a Popup Window
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/3-frames-and-windows/01-popup-windows/article.md
This example shows how to open a new popup window and then attempt to bring it into focus. While not always guaranteed to work due to browser restrictions, it's a common practice when launching popups.
```javascript
let newWindow = window.open('about:blank', 'myPopup', 'width=400,height=300');
if (newWindow) {
newWindow.focus();
}
```
--------------------------------
### Invalid JavaScript Variable Naming
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/02-first-steps/04-variables/article.md
Shows examples of invalid variable names that cause syntax errors, such as starting with a digit or using hyphens.
```javascript
let 1a; // Syntax error: cannot start with a digit
let my-name; // Syntax error: hyphens not allowed
```
--------------------------------
### Open and Initialize IndexedDB
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/6-data-storage/03-indexeddb/article.md
Demonstrates how to open an IndexedDB database and handle the initialization process using the onupgradeneeded event. This is essential for setting up the database schema for the first time.
```javascript
let openRequest = indexedDB.open("store", 1);
openRequest.onupgradeneeded = function() {
// triggers if the client had no database
// ...perform initialization...
};
openRequest.onerror = function() {
console.error("Error", openRequest.error);
};
openRequest.onsuccess = function() {
let db = openRequest.result;
// continue working with database using db object
};
```
--------------------------------
### Accessing Window Properties in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/1-document/01-browser-environment/article.md
Shows how to access properties of the `window` object, such as `innerHeight`, to get information about the browser window. This example displays the inner height of the browser window.
```javascript
alert(window.innerHeight); // inner window height
```
--------------------------------
### Tracking Text Selection with onselect
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/99-ui-misc/02-selection-range/article.md
This example demonstrates how to use the `onselect` event handler on a textarea to track the start and end positions of the selected text and display them in input fields.
```APIDOC
## Tracking Selection with onselect
### Description
This example uses the `onselect` event to track the start and end indices of the selected text within a textarea. The selected indices are then displayed in two disabled input fields.
### Method
Event Handler
### Endpoint
N/A (Client-side JavaScript)
### Parameters
#### DOM Elements
- **area** (textarea) - The textarea element where selection occurs.
- **from** (input) - Disabled input field to display the start index of the selection.
- **to** (input) - Disabled input field to display the end index of the selection.
#### Event
- **onselect** - Triggered when text is selected within the `area` element.
### Request Example
```html
From – To
```
### Response
#### Success Response (Event Trigger)
- **from.value** (number) - The starting index of the selection.
- **to.value** (number) - The ending index of the selection.
#### Response Example
When text is selected, the `from` and `to` input fields will be updated with the numerical start and end indices of the selection.
```
--------------------------------
### Fetch API - Full Options
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/06-fetch-api/article.md
Demonstrates the complete set of options that can be passed to the fetch function, including their default values and possible alternatives.
```APIDOC
## Fetch API - Advanced Options
### Description
This section details the advanced configuration options for the `fetch` API, providing a comprehensive overview of its capabilities for making network requests.
### Method
GET (default, but options can be applied to any method)
### Endpoint
`fetch(url, options)`
### Parameters
#### Request Options
- **method** (string) - Optional - The HTTP method to use (e.g., "GET", "POST", "PUT", "DELETE"). Defaults to "GET".
- **headers** (object) - Optional - An object containing request headers. The "Content-Type" header is often auto-set based on the body.
- **body** (string | FormData | Blob | BufferSource | URLSearchParams) - Optional - The request body. Can be various data types.
- **referrer** (string) - Optional - Controls the value of the `Referer` header. Can be an empty string, a URL from the current origin, or "about:client".
- **referrerPolicy** (string) - Optional - Specifies the referrer policy for the request (e.g., "strict-origin-when-cross-origin", "no-referrer-when-downgrade").
- **mode** (string) - Optional - Controls whether requests can be made to cross-origin domains. Options: "cors", "same-origin", "no-cors". Defaults to "cors".
- **credentials** (string) - Optional - Controls whether cookies are sent with the request. Options: "omit", "include", "same-origin". Defaults to "same-origin".
- **cache** (string) - Optional - Controls how the request and response are cached. Options: "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached". Defaults to "default".
- **redirect** (string) - Optional - Controls how redirects are handled. Options: "follow", "manual", "error". Defaults to "follow".
- **integrity** (string) - Optional - A Subresource Integrity hash string (e.g., "sha256-abcdef1234567890").
- **keepalive** (boolean) - Optional - If true, allows the request to continue running even after the page is unloaded. Defaults to `false`.
- **signal** (AbortSignal) - Optional - An `AbortSignal` object to abort the request.
- **window** (Window | null) - Optional - Specifies the window context for the request. Defaults to the current `window`.
### Request Example
```javascript
let promise = fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
key: "value"
}),
mode: "cors",
cache: "no-cache",
signal: abortController.signal
});
```
### Response
#### Success Response (200)
- **Response** (object) - A `Response` object representing the server's reply.
#### Response Example
```javascript
// Assuming the fetch request was successful and returned JSON
response.json().then(data => {
console.log(data);
});
```
```
--------------------------------
### Initialize and Configure XMLHttpRequest
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/08-xmlhttprequest/article.md
Demonstrates the basic steps to instantiate an XMLHttpRequest object, configure the request method and URL, and initiate the network transfer.
```javascript
let xhr = new XMLHttpRequest();
xhr.open('GET', '/article/xmlhttprequest/example/load');
xhr.send();
```
--------------------------------
### Getting and Setting Text Selection
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/99-ui-misc/02-selection-range/article.md
Provides JavaScript code examples for retrieving the current text selection using `document.getSelection()` and manipulating it, including cloning selected content and setting new selections.
```APIDOC
## Getting and Setting Text Selection
### Description
Demonstrates how to get the current text selection using `document.getSelection()` and how to manipulate it. Includes examples for cloning selected nodes and programmatically setting a new selection range.
### Method
JavaScript API
### Endpoint
N/A
### Parameters
N/A
### Request Example
```javascript
// Getting the selection
let selection = document.getSelection();
// Cloning selected nodes to another element
let cloned = /* element to clone the selected nodes to */;
for (let i = 0; i < selection.rangeCount; i++) {
cloned.append(selection.getRangeAt(i).cloneContents());
}
// Setting the selection
selection.removeAllRanges();
selection.addRange(range); // where 'range' is a Range object
// Or directly setting base and extent
// selection.setBaseAndExtent(...from...to...);
```
### Response
N/A
```
--------------------------------
### Create Downloadable Blob Link in HTML and JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/4-binary/03-blob/article.md
This example demonstrates creating a Blob with 'Hello, world!' content and then generating a downloadable link using `URL.createObjectURL`. The `download` attribute on the anchor tag ensures the file is downloaded when clicked.
```html
Download
```
--------------------------------
### Get Upload Status from Server (JavaScript)
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/09-resume-upload/article.md
This code shows how to send a request to the server to determine the number of bytes already uploaded for a given file ID. The server's response indicates the starting byte for resuming the upload.
```javascript
let response = await fetch('status', {
headers: {
'X-File-Id': fileId
}
});
// The server has that many bytes
let startByte = +await response.text();
```
--------------------------------
### Creating and Comparing Symbols
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/04-object-basics/08-symbol/article.md
Demonstrates how to instantiate symbols with descriptions and confirms that symbols with the same description are unique and not equal.
```javascript
let id1 = Symbol("id");
let id2 = Symbol("id");
alert(id1 == id2); // false
```
--------------------------------
### Filter Properties with ownKeys Trap in JavaScript Proxy
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/01-proxy/article.md
This example demonstrates using the 'ownKeys' trap in a JavaScript Proxy to filter out object properties that start with an underscore when iterating. It affects methods like 'for..in', 'Object.keys', and 'Object.values'.
```javascript
let user = {
name: "John",
age: 30,
_password: "***"
};
user = new Proxy(user, {
ownKeys(target) {
return Object.keys(target).filter(key => !key.startsWith('_'));
}
});
// 'ownKeys' filters out _password
for(let key in user) alert(key); // name, then: age
// same effect on these methods:
alert( Object.keys(user) ); // name,age
alert( Object.values(user) ); // John,30
```
--------------------------------
### Protecting Object Properties with Proxy Traps in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/01-proxy/article.md
This JavaScript code uses a Proxy to intercept and prevent access, modification, or deletion of object properties that start with an underscore. It defines 'get', 'set', 'deleteProperty', and 'ownKeys' traps to enforce privacy conventions.
```javascript
let user = {
name: "John",
_password: "***"
};
user = new Proxy(user, {
get(target, prop) {
if (prop.startsWith('_')) {
throw new Error("Access denied");
}
let value = target[prop];
return (typeof value === 'function') ? value.bind(target) : value;
},
set(target, prop, val) {
if (prop.startsWith('_')) {
throw new Error("Access denied");
} else {
target[prop] = val;
return true;
}
},
deleteProperty(target, prop) {
if (prop.startsWith('_')) {
throw new Error("Access denied");
} else {
delete target[prop];
return true;
}
},
ownKeys(target) {
return Object.keys(target).filter(key => !key.startsWith('_'));
}
});
try {
alert(user._password);
} catch(e) { alert(e.message); }
try {
user._password = "test";
} catch(e) { alert(e.message); }
try {
delete user._password;
} catch(e) { alert(e.message); }
for(let key in user) alert(key);
```
--------------------------------
### Create and Initialize a Range Object
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/99-ui-misc/02-selection-range/article.md
Demonstrates the basic instantiation of a Range object and how to define its boundaries using setStart and setEnd methods.
```javascript
let range = new Range();
range.setStart(node, offset);
range.setEnd(node, offset);
```
--------------------------------
### Get Window Dimensions
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/1-document/10-size-and-scroll-window/article.md
This section explains how to get the visible width and height of the browser window, excluding scrollbars, using document.documentElement.clientWidth and document.documentElement.clientHeight.
```APIDOC
## Get Window Dimensions
### Description
Retrieves the visible width and height of the browser window, excluding any scrollbars.
### Method
N/A (JavaScript properties)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```html
```
### Response
#### Success Response (N/A)
- **document.documentElement.clientWidth** (number) - The visible width of the window.
- **document.documentElement.clientHeight** (number) - The visible height of the window.
#### Response Example
(Alert box showing a numeric value for height)
````warn header="Note on `window.innerWidth/innerHeight`"
While `window.innerWidth` and `window.innerHeight` also provide dimensions, they include scrollbars. `clientWidth/clientHeight` provide the space available for content, which is often more useful for layout purposes.
```
```
--------------------------------
### JavaScript Nested Comment Error Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/02-first-steps/02-structure/article.md
Shows an example of invalid nested multi-line comments in JavaScript. Nested comments are not supported and will result in an error.
```javascript
/*
/* nested comment ?!? */
*/
alert( 'World' );
```
--------------------------------
### Object Creation with Prototypes
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/08-prototypes/04-prototype-methods/article.md
Demonstrates creating objects with a given prototype using literal syntax and Object.create.
```APIDOC
## Object Creation with Prototypes
### Description
This section explains how to create objects with a specified prototype using either literal syntax or the `Object.create` method.
### Methods
1. **Literal Syntax**: `{ __proto__: ... }`
- Allows specifying multiple properties directly.
2. **`Object.create(proto[, descriptors])`**
- Creates a new object with the specified prototype (`proto`).
- Optionally accepts property descriptors for new properties.
- Useful for shallow-copying objects with all descriptors:
```javascript
let obj = { a: 1 };
let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
```
### Prototype-less Objects
- Created using `Object.create(null)` or `{__proto__: null}`.
- Useful as dictionaries for storing keys without inheriting from `Object.prototype`.
```
--------------------------------
### HTML Structure for MutationObserver Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/99-ui-misc/01-mutation-observer/article.md
Provides the HTML structure for a practical example demonstrating MutationObserver. It includes a contentEditable div that can be modified to trigger mutation events.
```html
Click and edit, please
```
--------------------------------
### Create Objects with Property Descriptors
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/08-prototypes/04-prototype-methods/article.md
Shows how to use Object.create to initialize an object with a prototype and define additional properties using property descriptors.
```javascript
let animal = { eats: true };
let rabbit = Object.create(animal, {
jumps: {
value: true
}
});
alert(rabbit.jumps); // true
```
--------------------------------
### JavaScript Error: Invalid Property Descriptor (get and value)
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/07-object-properties/02-property-accessors/article.md
Demonstrates an error scenario where `Object.defineProperty` is used with both 'get' and 'value' in the same descriptor, which is invalid as a property cannot be both an accessor and a data property simultaneously.
```javascript
// Error: Invalid property descriptor.
Object.defineProperty({}, 'prop', {
get() {
return 1
},
value: 2
});
```
--------------------------------
### Initialize Mocha and Chai for Testing in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/03-code-quality/05-testing-mocha/index.html
This snippet shows how to set up the Mocha testing framework and integrate Chai for assertions. It makes the 'assert' object globally accessible, simplifying test writing. No specific inputs or outputs are defined as this is a setup configuration.
```javascript
mocha.setup('bdd');
let assert = chai.assert;
function pow(x, n) { /* function code is to be written, empty now */ }
mocha.run();
```
--------------------------------
### Initialize WebSocket Connection
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/11-websocket/article.md
Demonstrates how to instantiate a new WebSocket object using the secure wss:// protocol, which is recommended for reliability and encryption.
```javascript
let socket = new WebSocket("wss://javascript.info");
```
--------------------------------
### Example of Negative Array Indexing in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/01-proxy/02-array-negative/task.md
This example illustrates the concept of accessing array elements using negative indexes, which are counted from the end of the array. This syntax is not native to JavaScript but can be simulated.
```javascript
let array = [1, 2, 3];
array[-1]; // 3, the last element
array[-2]; // 2, one step from the end
array[-3]; // 1, two steps from the end
```
--------------------------------
### Control Animation with JavaScript Classes and Delays
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/7-animation/2-css-animations/article.md
Explains how to start animations by adding CSS classes via JavaScript and how to use negative transition-delay to start animations from specific time offsets.
```javascript
stripe.classList.add('animate');
stripe.onclick = function() {
let sec = new Date().getSeconds() % 10;
stripe.style.transitionDelay = '-' + sec + 's';
stripe.classList.add('animate');
};
```
--------------------------------
### Usage and Extension of Calculator
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md
Demonstrates how to instantiate the Calculator, perform basic calculations, and extend it with new operations like multiplication, division, and exponentiation.
```javascript
let powerCalc = new Calculator();
powerCalc.addMethod("*", (a, b) => a * b);
powerCalc.addMethod("/", (a, b) => a / b);
powerCalc.addMethod("**", (a, b) => a ** b);
let result = powerCalc.calculate("2 ** 3");
console.log(result); // 8
```
--------------------------------
### Implementing Async/Await Patterns in JavaScript
Source: https://context7.com/javascript-tutorial/en.javascript.info/llms.txt
Demonstrates basic async function usage, error handling with try/catch blocks, and techniques for sequential versus parallel execution. These patterns simplify asynchronous code by making it appear synchronous.
```javascript
async function fetchUser() {
let response = await fetch('/api/user');
let user = await response.json();
return user;
}
async function fetchData() {
try {
let response = await fetch('http://no-such-url');
let data = await response.json();
return data;
} catch (err) {
console.log("Fetch failed:", err.message);
return null;
}
}
async function loadParallel() {
let [user, posts] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/posts').then(r => r.json())
]);
return { user, posts };
}
```
--------------------------------
### Create and Start Low-Resolution Clock (JavaScript)
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/09-classes/02-class-inheritance/2-clock-class-extended/solution.view/index.html
This snippet initializes a new clock instance with a 'h:m:s' template and a precision of 10000 milliseconds, then starts its execution. It assumes the existence of an 'ExtendedClock' class.
```javascript
let lowResolutionClock = new ExtendedClock({ template: 'h:m:s', precision: 10000 });
lowResolutionClock.start();
```
--------------------------------
### DOM Property Typing: Boolean Example in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/1-document/06-dom-attributes-and-properties/article.md
Explains that DOM properties are not always strings. This example shows the `input.checked` property for checkboxes, which is a boolean, contrasting it with the attribute's string representation.
```html
checkbox
```
--------------------------------
### Basic Web Storage Operations
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/6-data-storage/02-localstorage/article.md
Demonstrates the fundamental methods for setting, retrieving, and removing data in localStorage.
```javascript
localStorage.setItem('test', 1);
alert(localStorage.getItem('test'));
localStorage.removeItem('test');
```
--------------------------------
### Dynamic Module Loading with import()
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/13-modules/03-modules-dynamic-imports/article.md
Demonstrates how to load a module dynamically using the import() expression. It shows both promise-based syntax and async/await usage.
```javascript
let modulePath = prompt("Which module to load?");
import(modulePath)
.then(obj => console.log(obj))
.catch(err => console.error(err));
// Or using async/await
async function loadModule(path) {
let module = await import(path);
return module;
}
```
--------------------------------
### Get Current Timestamp with Date.now() in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/05-data-types/11-date/article.md
Illustrates using the static Date.now() method to get the current timestamp in milliseconds. This method is preferred over new Date().getTime() for performance as it avoids creating a Date object.
```javascript
let start = Date.now();
// do the job
for (let i = 0; i < 100000; i++) {
let doSomething = i * i * i;
}
let end = Date.now();
alert( `The loop took ${end - start} ms` );
```
--------------------------------
### Accessing Response Headers with Fetch API (JavaScript)
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/01-fetch/article.md
Demonstrates how to retrieve and iterate over response headers obtained from a fetch request. It shows how to get a specific header using `get()` and how to loop through all headers using a `for...of` loop.
```javascript
let response = await fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits');
// get one header
alert(response.headers.get('Content-Type')); // application/json; charset=utf-8
// iterate over all headers
for (let [key, value] of response.headers) {
alert(`${key} = ${value}`);
}
```
--------------------------------
### Instantiating Objects using constructor property
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
Demonstrates how to create a new object instance based on the constructor of an existing object. It shows both a standard implementation and a scenario where the constructor property might lead to unexpected results.
```javascript
function User(name) {
this.name = name;
}
let user1 = new User('John');
let user2 = new user1.constructor('Pete');
console.log(user2.name); // Pete
// Example that works wrong:
User.prototype = {};
let user3 = new user1.constructor('Mary');
console.log(user3.name); // undefined (because the new prototype lacks the constructor)
```
--------------------------------
### Create Functions Dynamically with new Function
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/06-advanced-functions/07-new-function/article.md
Demonstrates the basic syntax for creating functions using the new Function constructor, including passing arguments and defining the function body as a string.
```javascript
let sum = new Function('a', 'b', 'return a + b');
alert(sum(1, 2)); // 3
let sayHi = new Function('alert("Hello")');
sayHi(); // Hello
```
--------------------------------
### Fetch GET Request with Promises
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/01-fetch/article.md
An alternative implementation of a GET request using the fetch() method with traditional promise chaining (.then()). It fetches data, parses it as JSON, and logs the author's login from the first commit.
```javascript
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(commits => {
console.log(commits[0].author.login);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
```
--------------------------------
### Creating BigInt values
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/05-bigint/article.md
Demonstrates how to initialize BigInts using the 'n' suffix or the BigInt constructor from strings and numbers.
```javascript
const bigint = 1234567890123456789012345678901234567890n;
const sameBigint = BigInt("1234567890123456789012345678901234567890");
const bigintFromNumber = BigInt(10);
```
--------------------------------
### JavaScript Class Definition and Instantiation
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/09-classes/01-class/article.md
Demonstrates the basic syntax for defining a JavaScript class named 'User' with a constructor and a 'sayHi' method. It shows how to create an instance of the class and call its method.
```javascript
class User {
constructor(name) {
this.name = name;
}
sayHi() {
alert(this.name);
}
}
// Usage:
let user = new User("John");
user.sayHi();
```
--------------------------------
### JavaScript try...catch: Errorless Execution Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/10-error-handling/1-try-catch/article.md
An example illustrating the 'try...catch' block when no errors occur within the 'try' block. Both the code inside 'try' executes, and the 'catch' block is skipped.
```javascript
try {
alert('Start of try runs');
alert('End of try runs');
} catch (err) {
alert('Catch is ignored, because there are no errors');
}
```
--------------------------------
### JavaScript WebSocket Connection with Subprotocols
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/11-websocket/article.md
Demonstrates how to establish a WebSocket connection and specify desired subprotocols using the `WebSocket` constructor. The server will respond with the agreed-upon protocols.
```javascript
let socket = new WebSocket("wss://javascript.info/chat", ["soap", "wamp"]);
```
--------------------------------
### JavaScript String substr() Method
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/05-data-types/03-string/article.md
The substr() method extracts a part of a string starting from a specified index and returning a specified number of characters. The start index can be negative to count from the end. This method is part of Annex B and generally not recommended for new development.
```javascript
let str = "st*!*ring*/!*ify";
alert( str.substr(2, 4) ); // 'ring', from the 2nd position get 4 characters
alert( str.substr(-4, 2) ); // 'gi', from the 4th position get 2 characters
```
--------------------------------
### Example Usage of the JavaScript Delay Decorator
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/06-advanced-functions/09-call-apply-decorators/02-delay/task.md
This example shows how to use the `delay` decorator. It defines a sample function `f` and then creates two delayed versions of it, `f1000` and `f1500`, with different delay times. Calling these delayed functions demonstrates that they execute after their specified delays.
```javascript
function f(x) {
alert(x);
}
// create wrappers
let f1000 = delay(f, 1000);
let f1500 = delay(f, 1500);
f1000("test"); // shows "test" after 1000ms
f1500("test"); // shows "test" after 1500ms
```
--------------------------------
### Create and Parse URL Objects
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/07-url/article.md
Demonstrates how to instantiate a URL object using absolute paths or relative paths with a base URL, and how to access individual URL components like protocol, host, and pathname.
```javascript
let url1 = new URL('https://javascript.info/profile/admin');
let url2 = new URL('/profile/admin', 'https://javascript.info');
// Accessing components
let url = new URL('https://javascript.info/url');
console.log(url.protocol); // https:
console.log(url.host); // javascript.info
console.log(url.pathname); // /url
```
--------------------------------
### GET /window/selection
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/99-ui-misc/02-selection-range/article.md
Retrieves the current user selection object from the document.
```APIDOC
## GET /window/selection
### Description
Retrieves the Selection object representing the current user selection in the document. Note that while the API supports multiple ranges, most browsers (except Firefox) limit this to a single range.
### Method
GET
### Endpoint
window.getSelection() or document.getSelection()
### Response
#### Success Response (200)
- **Selection** (Object) - The object representing the current selection, containing zero or more ranges.
```
--------------------------------
### Opening and Accessing Popups
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/3-frames-and-windows/01-popup-windows/article.md
Demonstrates how to open a new window using `window.open` and access its document to write content or modify it after loading.
```APIDOC
## POST /window/open
### Description
Opens a new browser window or tab and returns a reference to it. This reference can be used to manipulate the new window's properties, content, and location.
### Method
`window.open()`
### Endpoint
N/A (JavaScript method)
### Parameters
#### Arguments
- **url** (string) - Optional - The URL to load in the new window. Use "about:blank" for an empty window.
- **windowName** (string) - Optional - The name of the window. Can be used to reference the window later.
- **windowFeatures** (string) - Optional - A comma-separated list of features for the new window (e.g., "width=200,height=200").
### Request Example
```javascript
let newWin = window.open("about:blank", "hello", "width=200,height=200");
newWin.document.write("Hello, world!");
// Modifying content after loading
let newWindow = open('/', 'example', 'width=300,height=300');
newWindow.focus();
newWindow.onload = function() {
let html = `
Welcome!
`;
newWindow.document.body.insertAdjacentHTML('afterbegin', html);
};
```
### Response
#### Success Response
- **Window Reference** (object) - A reference to the newly opened window object.
#### Response Example
(No direct response, but the returned object allows manipulation of the new window.)
```
--------------------------------
### Open Popup with Specific Window Dimensions and Position
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/3-frames-and-windows/01-popup-windows/article.md
Demonstrates opening a popup window with specific dimensions (`width`, `height`) and screen coordinates (`left`, `top`). This example configures the window to be 600px wide, 300px high, and positioned at 100px from the left and 100px from the top of the screen.
```javascript
let params = "scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,
width=600,height=300,left=100,top=100";
open('/', 'test', params);
```
--------------------------------
### Calculate Max Subarray Sum (Slow O(n^2)) - JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/05-data-types/04-array/10-maximal-subarray/solution.md
This function calculates the maximum sum of a contiguous subarray using a nested loop approach. It iterates through all possible starting points and then calculates the sum of subarrays starting from that point. Its time complexity is O(n^2), making it inefficient for large arrays.
```javascript
function getMaxSubSum(arr) {
let maxSum = 0; // if we take no elements, zero will be returned
for (let i = 0; i < arr.length; i++) {
let sumFixedStart = 0;
for (let j = i; j < arr.length; j++) {
sumFixedStart += arr[j];
maxSum = Math.max(maxSum, sumFixedStart);
}
}
return maxSum;
}
alert( getMaxSubSum([-1, 2, 3, -9]) ); // 5
alert( getMaxSubSum([-1, 2, 3, -9, 11]) ); // 11
alert( getMaxSubSum([-2, -1, 1, 2]) ); // 3
alert( getMaxSubSum([1, 2, 3]) ); // 6
alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100
```
--------------------------------
### Implement Default Values with Proxy 'get' Trap (JavaScript)
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/01-proxy/article.md
This snippet shows how to use the 'get' trap of a JavaScript Proxy to provide default values for non-existent properties. It intercepts property reads and returns a specified default value (e.g., 0 for numbers, or the property name itself for untranslated phrases) instead of 'undefined'.
```javascript
let numbers = [0, 1, 2];
numbers = new Proxy(numbers, {
get(target, prop) {
if (prop in target) {
return target[prop];
} else {
return 0; // default value
}
}
});
alert( numbers[1] ); // 1
alert( numbers[123] ); // 0 (no such item)
```
```javascript
let dictionary = {
'Hello': 'Hola',
'Bye': 'Adiós'
};
dictionary = new Proxy(dictionary, {
get(target, phrase) { // intercept reading a property from dictionary
if (phrase in target) { // if we have it in the dictionary
return target[phrase]; // return the translation
} else {
// otherwise, return the non-translated phrase
return phrase;
}
}
});
// Look up arbitrary phrases in the dictionary!
// At worst, they're not translated.
alert( dictionary['Hello'] ); // Hola
alert( dictionary['Welcome to Proxy']); // Welcome to Proxy (no translation)
```
--------------------------------
### Get Weekday Name using getDay() in JavaScript
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/05-data-types/11-date/2-get-week-day/solution.md
This function takes a Date object and returns a short string representation of the weekday (e.g., 'SU', 'MO'). It utilizes the `getDay()` method to get the numeric day of the week and an array to map this number to the corresponding abbreviation. The input is a Date object, and the output is a string representing the weekday.
```javascript
function getWeekDay(date) {
let days = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'];
return days[date.getDay()];
}
let date = new Date(2014, 0, 3); // 3 Jan 2014
alert( getWeekDay(date) ); // FR
```
--------------------------------
### Basic var declaration
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/06-advanced-functions/04-var/article.md
Demonstrates the basic syntax of declaring a variable using the 'var' keyword.
```javascript
var message = "Hi";
alert(message);
```
--------------------------------
### Getting and Setting Prototypes
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/08-prototypes/04-prototype-methods/article.md
Explains the modern JavaScript methods for retrieving and modifying an object's prototype.
```APIDOC
## Getting and Setting Prototypes
### Description
This section covers the modern, recommended methods for interacting with an object's prototype (`[[Prototype]]`).
### Methods
1. **`Object.getPrototypeOf(obj)`**
- Returns the prototype of the given object (`obj`).
- Equivalent to the `__proto__` getter.
2. **`Object.setPrototypeOf(obj, proto)`**
- Sets the prototype of the given object (`obj`) to `proto`.
- Equivalent to the `__proto__` setter.
### Note on `__proto__`
- Using the `__proto__` getter/setter is generally not recommended as it's part of Annex B of the ECMAScript specification and may not be supported in all environments or future versions.
```
--------------------------------
### JavaScript Proxy: Basic Usage Without Traps
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/99-js-misc/01-proxy/article.md
Demonstrates the basic syntax of creating a JavaScript Proxy with an empty handler. This shows how a proxy can act as a transparent wrapper, forwarding all operations to the target object without any custom interception.
```javascript
let target = {};
let proxy = new Proxy(target, {}); // empty handler
proxy.test = 5; // writing to proxy (1)
alert(target.test); // 5, the property appeared in target!
alert(proxy.test); // 5, we can read it from proxy too (2)
for(let key in proxy) alert(key); // test, iteration works (3)
```
--------------------------------
### Get Window Dimensions
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/1-document/10-size-and-scroll-window/article.md
Retrieves the visible width and height of the browser window excluding scrollbars using documentElement properties.
```javascript
alert(document.documentElement.clientHeight);
```
```javascript
alert(window.innerWidth); // Includes scrollbar
alert(document.documentElement.clientWidth); // Excludes scrollbar
```
--------------------------------
### Opening an IndexedDB Database
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/6-data-storage/03-indexeddb/article.md
Demonstrates how to open an IndexedDB database with a specified name and version, and how to handle success, error, and upgrade needed events.
```APIDOC
## Opening an IndexedDB Database
### Description
This section details the process of opening an IndexedDB database. It covers the `indexedDB.open()` method, its parameters, and the essential event handlers: `onsuccess`, `onerror`, and `onupgradeneeded`.
### Method
`indexedDB.open(name, version)
### Endpoint
N/A (Client-side API)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
N/A
### Request Example
```javascript
let openRequest = indexedDB.open("store", 1);
openRequest.onupgradeneeded = function(event) {
// Handle database initialization or upgrade
let db = openRequest.result;
console.log("Database upgrade needed. Old version: " + event.oldVersion);
// Perform initialization if db doesn't exist (oldVersion is 0)
};
openRequest.onerror = function() {
console.error("Error opening database:", openRequest.error);
};
openRequest.onsuccess = function() {
let db = openRequest.result;
console.log("Database opened successfully. Version: " + db.version);
// Proceed with database operations
};
```
### Response
#### Success Response (200)
- **db** (IDBDatabase) - The database object, available on `openRequest.result` upon successful opening.
#### Response Example
```json
{
"message": "Database opened successfully",
"db_version": 1
}
```
```
--------------------------------
### Getting Property Descriptors
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/07-object-properties/01-property-descriptors/article.md
Use Object.getOwnPropertyDescriptor to retrieve the full descriptor object for a given property, including its value and flags.
```APIDOC
## Object.getOwnPropertyDescriptor
### Description
Retrieves the property descriptor for a specified property on an object.
### Method
`Object.getOwnPropertyDescriptor(obj, propertyName)`
### Parameters
- **obj** (object) - The object to get information from.
- **propertyName** (string) - The name of the property.
### Response
- **descriptor** (object) - An object containing the property's value and flags (writable, enumerable, configurable).
### Request Example
```javascript
let user = {
name: "John"
};
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
alert( JSON.stringify(descriptor, null, 2) );
```
### Response Example
```json
{
"value": "John",
"writable": true,
"enumerable": true,
"configurable": true
}
```
```
--------------------------------
### Toggling Element Visibility
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/2-ui/1-document/05-basic-dom-node-properties/article.md
Demonstrates using the hidden property to control element visibility, including a blinking effect example.
```html
A blinking element
```
--------------------------------
### EventSource Initialization
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/5-network/12-server-sent-events/article.md
Shows the basic syntax for creating a new EventSource object, including the URL and optional credentials.
```APIDOC
The syntax is:
```js
let source = new EventSource(url, [credentials]);
```
The second argument has only one possible option: `{ withCredentials: true }`, it allows sending cross-origin credentials.
Overall cross-origin security is same as for `fetch` and other network methods.
```
--------------------------------
### JavaScript ES6 Classes: Syntax and Inheritance
Source: https://context7.com/javascript-tutorial/en.javascript.info/llms.txt
Illustrates the ES6 class syntax for creating objects, including constructors, methods, getters, setters, and static members. Shows how to implement inheritance using the `extends` keyword and call parent class methods with `super`.
```javascript
// Class declaration
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
sayHi() {
console.log(`Hi, I'm ${this.name}`);
}
// Getter
get info() {
return `${this.name}, ${this.age} years old`;
}
// Setter
set info(value) {
[this.name, this.age] = value.split(', ');
}
// Static method
static createAnonymous() {
return new User('Anonymous', 0);
}
}
let user = new User('John', 30);
user.sayHi(); // "Hi, I'm John"
console.log(user.info); // "John, 30 years old"
User.createAnonymous(); // Creates anonymous user
// Inheritance
class Admin extends User {
constructor(name, age, permissions) {
super(name, age); // call parent constructor
this.permissions = permissions;
}
sayHi() {
super.sayHi(); // call parent method
console.log(`I have ${this.permissions.length} permissions`);
}
}
let admin = new Admin('Jane', 25, ['read', 'write', 'delete']);
admin.sayHi();
// "Hi, I'm Jane"
// "I have 3 permissions"
// Private fields (ES2022)
class BankAccount {
#balance = 0; // private field
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
```
--------------------------------
### Enumerable Property Example
Source: https://github.com/javascript-tutorial/en.javascript.info/blob/master/1-js/07-object-properties/01-property-descriptors/article.md
Demonstrates how the 'enumerable' flag affects property visibility in loops and Object.keys. Non-enumerable properties are excluded.
```APIDOC
## Enumerable Flag
### Description
Controls whether a property is included in `for...in` loops and `Object.keys()`.
### Request Example (Default enumerable property)
```javascript
let user = {
name: "John",
toString() {
return this.name;
}
};
// By default, both properties are listed:
for (let key in user) alert(key); // name, toString
alert(Object.keys(user)); // name, toString
```
### Request Example (Non-enumerable property)
```javascript
let user = {
name: "John",
toString() {
return this.name;
}
};
Object.defineProperty(user, "toString", {
enumerable: false
});
// Now toString is not listed:
for (let key in user) alert(key); // name
alert(Object.keys(user)); // name
```
```