The Modern JavaScript Tutorial

repository·master·Indexed 12 days ago

https://github.com/javascript-tutorial/en.javascript.info

A comprehensive educational resource for learning JavaScript, covering core language fundamentals, JavaScript engines (V8, SpiderMonkey, JavaScriptCore, Chakra), browser capabilities, DOM manipulation, and development environment setup using IDEs like Visual Studio Code and WebStorm.

Tokens
296.6K
Snippets
1K
Records
1.2K
Agent score
96%

What's inside Modern JavaScript Tutorial

  1. Introduction to IndexedDB

    master

    IndexedDB is a powerful, built-in browser database designed for offline applications. Unlike localStorage, it supports:

    • Storing almost any kind of value (including complex objects) via keys.
    • Multiple key types.
    • Transactions for data reliability.
    • Key range queries and indexes.
    • Significantly larger data volumes.

    The native interface is event-based. For modern async/await usage, it is recommended to use a promise-based wrapper like idb (available via https://cdn.jsdelivr.net/npm/idb@3.0.2/build/idb.min.js).

  2. Learn Browser DOM, Events, and Interfaces

    master

    This section of the tutorial covers how to manage the browser page. You will learn how to:

    • Add and manipulate elements: Create new DOM elements and modify their size, position, and content.
    • Handle Events: Implement interactivity by listening to user actions and browser events.
    • Work with Interfaces: Dynamically create and interact with browser interfaces to enhance the visitor experience.
  3. Summary of IndexedDB workflow

    master

    IndexedDB is a powerful key-value database suitable for offline applications. The standard workflow is:

    1. Get a promise wrapper (e.g., idb) to avoid manual event handling.
    2. Open a database: Use idb.openDb(name, version, onupgradeneeded). Use the onupgradeneeded handler to create object stores and indexes.
    3. Perform requests:
      • Create a transaction: db.transaction('storeName', 'readwrite').
      • Get the object store: transaction.objectStore('storeName').
    4. Search/Access data:
      • Search by key: Call methods directly on the object store.
      • Search by field: Create an index on the object store.
    5. Handle large data: Use a cursor if the data does not fit in memory.
  4. Summary of JSON capabilities in JavaScript

    master

    JSON Overview

    • Format: JSON is an independent data format supported by most programming languages.
    • Supported Types: Plain objects, arrays, strings, numbers, booleans, and null.
    • Serialization: Use JSON.stringify(object, replacer, space) to convert JavaScript objects to JSON strings. If an object has a toJSON method, it is called automatically.
    • Deserialization: Use JSON.parse(text, reviver) to convert JSON strings back into JavaScript objects.
    • Transformers: Both stringify (via replacer) and parse (via reviver) support transformer functions for custom logic during reading/writing.
  5. Summary of Decorators and Call/Apply

    master

    Decorators

    A decorator is a wrapper around a function that alters its behavior without changing its source code. They can be viewed as adding 'features' or 'aspects' to a function.

    Key Methods for Decorators

    • func.call(context, arg1, arg2...): Calls func with a specific this context and individual arguments.
    • func.apply(context, args): Calls func with a specific this context and an array-like args object passed as a list of arguments.

    Method Borrowing

    Taking a method from one object and executing it in the context of another (e.g., [].join.call(arguments)). An alternative to borrowing is using rest parameters (...args), which creates a real array.

  6. What is long polling and how does it work?

    master

    Long polling is a technique for maintaining a persistent connection with a server without using specialized protocols like WebSocket or Server-Sent Events. It is an improvement over Regular Polling (where a client sends periodic requests at fixed intervals, e.g., every 10 seconds).

    The Long Polling Flow:

    1. The client sends a request to the server.
    2. The server holds the connection open and does not close it until it has new information/messages to send.
    3. Once a message is available, the server responds to the pending request.
    4. The client receives the message and immediately initiates a new request to start the cycle again.

    If the connection is lost due to network errors, the client should immediately attempt to send a new request to re-establish the cycle.

  7. What is Shadow DOM and how does it work?

    master

    Shadow DOM provides encapsulation for web components. It allows an element to have its own private DOM tree (the shadow tree) that is hidden from the main document. This prevents accidental access from external scripts and ensures that styles applied to the main document do not leak into the component, and vice versa.

    Key concepts:

    • Shadow tree host: The regular DOM element that contains the shadow tree.
    • Light tree: The regular DOM subtree made of standard HTML children.
    • Shadow tree: The hidden DOM subtree. If an element has both, the browser renders the shadow tree instead of the light tree (unless composition via <slot> is used).

    When a shadow tree is present, its elements are invisible to querySelector calls made from the main document and have their own isolated ID and style scope.

    // Example of a custom element with a shadow tree
    customElements.define('show-hello', class extends HTMLElement {
      connectedCallback() {
        const shadow = this.attachShadow({mode: 'open'});
        shadow.innerHTML = `<p>Hello, world!</p>`;
      }  
    });
  8. What is a Promise and how does it work?

    master

    A Promise is a JavaScript object that acts as a link between 'producing code' (which performs a task that takes time, like a network request) and 'consuming code' (which needs the result once it's ready).

    When a Promise is created, it enters a pending state. Once the producing code finishes, the promise moves to a 'settled' state, which is either:

    • fulfilled: The task completed successfully, and the promise holds a result.
    • rejected: An error occurred, and the promise holds an error.

    Note that state and result are internal properties and cannot be accessed directly. You must use consumer methods like .then, .catch, or .finally to interact with them.

    let promise = new Promise(function(resolve, reject) {
      // executor (the producing code)
    });
  9. What is a Closure and how does it work?

    master

    A closure is a function that remembers its outer variables and can access them. In JavaScript, all functions are naturally closures because they possess a hidden property named [[Environment]].

    How it works:

    1. Creation Time: When a function is created, its [[Environment]] property is set to the Lexical Environment in which it was made. This reference is set once and forever.
    2. Execution Time: When the function is called, a new Lexical Environment is created for the call. Its outer reference is taken from the function's [[Environment]] property.
    3. Access: When the function looks for a variable, it searches its own environment, then follows the [[Environment]] link to the outer environment where the variable lives.

    Important Rule: A variable is updated in the Lexical Environment where it lives, not in the environment where the function is called.

    function makeCounter() {
      let count = 0;
    
      return function() {
        return count++;
      };
    }
    
    let counter = makeCounter();
    
    console.log(counter()); // 0
    console.log(counter()); // 1
  10. What is a debounce decorator and how does it work

    master

    A debounce(f, ms) decorator is a wrapper that suspends calls to the original function f until there is a specified period of inactivity (ms milliseconds).

    Key behaviors:

    1. Cooldown Period: It waits for ms milliseconds of silence (no calls) before invoking f.
    2. Single Execution: It invokes f only once after the cooldown period, even if multiple calls were attempted during the wait.
    3. Latest Arguments: When f is finally called, it uses the arguments from the very last call made during the sequence; all previous calls are ignored.

    Common Use Cases:

    • Input Fields: Waiting for a user to finish typing before sending a server request (to avoid a request for every single keystroke).
    • Event Sequences: Handling rapid sequences of events like mouse movements, window resizing, or key presses.
    // Example using Lodash's _.debounce
    let f = _.debounce(alert, 1000);
    
    f("a");
    setTimeout(() => f("b"), 200);
    setTimeout(() => f("c"), 500);
    
    // After 1500ms (500ms + 1000ms cooldown), the function runs once:
    // alert("c")
  11. What is a JavaScript module and how to use it

    master

    A module is a single JavaScript file that can load other modules and interchange functionality using export and import directives.

    • export labels variables or functions to make them accessible outside the module.
    • import allows a module to consume functionality from another module.

    To use modules in a browser, you must specify the script type in your HTML using <script type="module">.

    Important: Modules only work via HTTP(s) protocols. They will not work if you open an HTML file directly via the file:// protocol. Use a local web server (like VS Code's Live Server or static-server) for testing.

    // 📁 sayHi.js
    export function sayHi(user) {
      alert(`Hello, ${user}!`);
    }
    
    // 📁 main.js
    import {sayHi} from './sayHi.js';
    
    sayHi('John'); // Hello, John!