何岡駿
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    1
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # JS Concept From Solving LeetCode **This note was created through collaboration with ChatGPT.** ## Higher-order function ### Definition A higher-order function is a function that takes one or more functions as arguments (which are called callback functions) and/or returns a function as its result. Essentially, it treats functions as first-class citizens, allowing them to be manipulated and passed around just like any other value. - **Why to use** - **Code Reusability**: Higher-order functions allow for the separation of concerns by delegating certain behaviors to other functions, promoting code reuse and modularity. - **Functional Composition**: Higher-order functions can be used to combine multiple functions together, creating new functions that exhibit more complex behaviors. - **Abstraction**: By accepting callbacks, higher-order functions enable the creation of abstractions that encapsulate generic functionality while allowing customization through callback functions. - **Asynchronous Programming**: Higher-order functions and callbacks are extensively used in asynchronous programming to handle events, timers, and asynchronous operations. They provide a powerful mechanism to handle the order and timing of function execution in asynchronous scenarios. ### Example ```javascript function higherOrderFunction(callback) { // Perform some operations or logic callback(); // Call the callback function } function callbackFunction() { console.log('Callback function called'); } // Passing the callback function to the higher-order function higherOrderFunction(callbackFunction); ``` By leveraging higher-order functions and callbacks, you can achieve modular and customizable code structures that promote code reusability, functional composition, and effective handling of asynchronous operations. ## Variable and Function Hoisting Hoisting is a mechanism in JavaScript where variable and function declarations are moved to the top of their respective scopes during the compilation phase. It is important to note that only the declarations are hoisted, not the assignments or initializations. ### Variable Hoisting When variables declared with the `var` keyword are hoisted, they are initialized with the value `undefined` by default. This can lead to confusion when accessing variables before they are assigned a value. #### Example: ```javascript console.log(a); // undefined var a = 5;` ``` The code is interpreted as follows: ```javascript var a; // Variable declaration is hoisted console.log(a); // undefined a = 5; // Assignment ``` ### Function Hoisting Function declarations are also hoisted in JavaScript. This allows you to call a function before its actual declaration in the code. #### Example ```javascript hoisted(); // Function call before declaration function hoisted() { console.log("Function hoisted!"); } ``` In this case, the function declaration is hoisted to the top, allowing the function to be called before its declaration. - **Notice** - **Hoisting of Function Declarations**: Only function declarations are hoisted, not function expressions or arrow functions. Function declarations are the ones defined with the `function` keyword followed by a name, like `function myFunction() { }`. These declarations are moved to the top of their scope during the compilation phase, making them accessible from anywhere in the code. - **Variables and Assignments Not Hoisted**: It's crucial to note that variables and assignments within the function are not hoisted. Only the function declaration itself is moved to the top of the scope. Any variables declared within the function still follow normal variable scoping rules. - **Usefulness in Mutual Recursion**: Function hoisting can be particularly useful in scenarios where you have multiple functions calling each other, known as mutual recursion. With function hoisting, you can define the functions in any order, as long as they are all function declarations. Please note that hoisting can sometimes lead to confusion and potential bugs if not understood properly. It is generally recommended to declare variables and functions before using them to ensure code clarity and avoid unexpected behavior. ## Variable Declarations in JavaScript In JavaScript, there are different ways to declare variables, including `var`, `let`, and `const`. Each has its own characteristics and behaviors that you should be aware of when using them. ### `var` Declaration The `var` keyword was traditionally used for variable declaration in JavaScript before the introduction of `let` and `const`. However, it has some characteristics that can lead to unexpected behavior: - **Function Scope**: Variables declared with `var` are function-scoped. This means that they are accessible throughout the entire function in which they are declared, regardless of block boundaries. - **Hoisting**: Variable declarations using `var` are hoisted to the top of their containing scope during the compilation phase. However, only the declaration is hoisted, not the assignment. This means you can access and use a variable before it is declared, but its value will be `undefined` until it is assigned. - **No Block Scope**: `var` variables do not have block scope. They are accessible outside of any block they are declared in. #### **Warning** **Reassignable and Redefinable**: Variables declared with `var` can be reassigned and redeclared within the same scope without any restrictions. This can lead to unintended consequences and make it difficult to keep track of variable values. Here's an example code that demonstrates these features: ```javascript var x = 10; console.log(x); // Output: 10 x = 20; // Reassigning the variable console.log(x); // Output: 20 var x = 30; // Redeclaring the variable console.log(x); // Output: 30 ``` In the above code, the variable `x` is initially declared with `var` and assigned a value of `10`. It is then reassigned to `20` and later redeclared with a new value of `30` within the same scope. The ability to reassign and redefine variables with `var` can lead to confusion and unexpected behavior. It's generally recommended to use `let` or `const` declarations, which have more predictable scoping rules and enforce better coding practices. ### `const` and `let` Declarations `const` and `let` were introduced in ECMAScript 6 (ES6) as alternatives to `var`. They have some important differences compared to `var`: 1. **Block Scope**: Variables declared with `const` and `let` are block-scoped. They are limited in scope to the block in which they are declared (e.g., within curly braces `{}`). 2. **Hoisting and Temporal Dead Zone (TDZ)**: While `const` and `let` declarations are hoisted to the top of their block scope, they enter a TDZ. During the TDZ, accessing or assigning a value to the variable results in a reference error. The variable becomes accessible and usable only after the actual declaration is encountered during runtime execution. 3. **`const` Constantness**: Variables declared with `const` are constants and cannot be reassigned once they are assigned a value. However, it's important to note that for complex data types (like objects and arrays), the reference itself is constant, but the properties or elements within them can still be modified. 4. **`let` Reassignability**: Variables declared with `let` can be reassigned within their scope. They are not constant. However, they cannot be redeclared within the same scope. It's important to choose the appropriate variable declaration based on your specific needs. Consider using `const` for values that should not be reassigned, `let` for variables that need reassignability, and avoid using `var` due to its potential pitfalls. ## Object Basics ### Object Declaration In JavaScript, object literals are a convenient way to create objects with key-value pairs. When declaring object properties, there is no difference between using quotes to denote the key as a string type or not using quotes for keys that follow the valid identifier naming rules. **Example 1** ```javascript const object = { "num": 1, "str": "Hello World", "obj": { "x": 5 } }; ``` **Example 2** ```javascript const object = { num: 1, str: "Hello World", obj: { x: 5 } }; ``` Both examples are functionally equivalent, and you can access the properties using either dot notation or bracket notation: `console.log(object.num); // Output: 1` `console.log(object["str"]); // Output: "Hello World"` `console.log(object.obj.x); // Output: 5` Using quotes for keys can be helpful when the key contains special characters, spaces, or starts with a number. However, for keys that follow the valid identifier naming rules, quotes are optional. It's a matter of preference and readability. ### Exceptions While dot notation is commonly used, there are certain scenarios where bracket notation is required. 1. **Accessing properties with dynamic keys:** When accessing properties with dynamic keys, dot notation fails because it looks for a property with the actual key name, rather than evaluating the variable's value. Instead, bracket notation should be used. ```javascript const obj = { key: "value" }; const dynamicKey = "key"; console.log(obj.dynamicKey); // Output: undefined console.log(obj[dynamicKey]); // Output: "value" ``` 2. **Using property names with special characters or reserved words:** If an object has property names that contain special characters or are reserved words, dot notation cannot be used directly. Bracket notation is necessary to access these properties. ```javascript `const obj = { "special-key": "value", for: "in" }; console.log(obj.special-key); // Error: Unexpected token '-' console.log(obj.for); // Error: Unexpected token 'for' console.log(obj["special-key"]); // Output: "value" console.log(obj["for"]); // Output: "in" ``` 3. **Working with computed property names:** Computed property names allow us to define properties using an expression as the property name. In such cases, dot notation will not work, but bracket notation is used to evaluate the expression and access the property. ```javascript const dynamicKey = "key"; const obj = { [dynamicKey]: "value" }; console.log(obj.key); // Output: "value" console.log(obj[dynamicKey]); // Output: "value" ``` ### Summary In summary, while dot notation is commonly used, bracket notation is necessary in certain situations. Bracket notation allows for dynamic evaluation of property names, handles special characters and reserved words, and enables the use of computed property names. Understanding when to use dot notation and when to use bracket notation is crucial for effectively working with objects in JavaScript. ## Prototype chain ### **Definition** In JavaScript, accessing **keys on an object** involves a process known as **property lookup**, which goes beyond simply examining the keys of the object itself. It involves traversing the **prototype chain**, which is a mechanism that allows objects to inherit properties from their prototype objects. When you access a key on an object, JavaScript first looks for that key within the object itself. If the key is found, the corresponding value is returned. However, if the key is not found in the object, JavaScript continues the search by looking at the keys of the object's prototype. The prototype of an object is another object that serves as a blueprint for the current object. It contains properties and methods that can be shared among multiple objects. If the key is found in the prototype object, the corresponding value is returned. If the key is still not found, JavaScript proceeds to look at the prototype's prototype (i.e., the prototype of the prototype) and continues this process until the key is found or until the end of the prototype chain is reached. This mechanism is crucial for implementing **inheritance** in JavaScript. When an object is created using a constructor function or a class, it inherits properties and methods from its prototype. Any properties or methods defined in the prototype are shared among all instances of that object type. This allows for code reuse and the ability to create objects with shared behavior. ```javascript function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log(`Hello, my name is ${this.name}!`); }; const person = new Person("John"); person.sayHello(); // Output: "Hello, my name is John!"` ``` In the above example, we define a `Person` constructor function. When we create a new `Person` object using the `new` keyword, it inherits the `sayHello` method from its **prototype**. The `sayHello` method can be accessed and called on any `Person` object, allowing us to share behavior among different instances. ### Usage By traversing the prototype chain, JavaScript provides a powerful way to organize and structure objects, enabling inheritance and the sharing of properties and methods. It allows objects to access and inherit properties from their prototype objects, providing a flexible and efficient way to work with object-oriented programming concepts in JavaScript. Understanding the prototype chain and how property lookup works is fundamental for effectively working with objects and leveraging the inheritance capabilities of JavaScript. It enables you to create and use objects in a way that promotes code reuse, modularity, and extensibility. Here's another example that demonstrates the prototype chain and property lookup: ```javascript // Parent constructor function function Animal(name) { this.name = name; } // Prototype method Animal.prototype.sayName = function() { console.log(`My name is ${this.name}`); }; // Child constructor function function Dog(name, breed) { Animal.call(this, name); // Call parent constructor this.breed = breed; } // Set up prototype chain Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; // Prototype method specific to Dog Dog.prototype.bark = function() { console.log("Woof!"); }; // Create Dog object const myDog = new Dog("Max", "Labrador"); myDog.sayName(); // Output: "My name is Max" myDog.bark(); // Output: "Woof!" ``` In this example, we have a parent constructor function `Animal` that defines a `sayName` method on its prototype. The child constructor function `Dog` is created using `Object.create` to set up the prototype chain. The `Dog` prototype is linked to the `Animal` prototype, allowing instances of `Dog` to inherit properties and methods from `Animal`. By accessing the `sayName` method on `myDog`, the property lookup process begins by looking for the method in the `myDog` object itself. Since it's not found, JavaScript continues up the prototype chain and finds the method in the `Animal` prototype, which is then invoked. ### Summary The prototype chain and property lookup mechanism provide a powerful way to implement inheritance and share behavior between objects in JavaScript. It allows for a hierarchical structure of objects, where properties and methods can be inherited and overridden as needed. Understanding how the prototype chain works enables you to design and create robust object-oriented JavaScript code, making the most of the language's features and capabilities. ## Proxies ### Definition In JavaScript, a Proxy is an object that wraps another object and intercepts operations performed on it. It allows you to define custom behavior for fundamental operations such as property access, assignment, function invocation, and more. The Proxy syntax provides a way to create and configure Proxy objects. ### Handlers There are several handlers available for defining custom behavior in a Proxy object. Each handler corresponds to a specific operation on the target object. Let's explore some of these handlers with examples: 1. `get` handler: ```javascript const target = { name: "John", age: 30 }; const handler = { get(target, property, receiver) { console.log(`Getting property '${property}'`); return target[property]; } }; const proxy = new Proxy(target, handler); console.log(proxy.name); // Output: Getting property 'name' \n John console.log(proxy.age); // Output: Getting property 'age' \n 30 ``` 2. `set` handler: ```javascript const target = {}; const handler = { set(target, property, value, receiver) { console.log(`Setting property '${property}' to '${value}'`); target[property] = value; return true; } }; const proxy = new Proxy(target, handler); proxy.name = "John"; // Output: Setting property 'name' to 'John' console.log(proxy.name); // Output: John ``` 3. `apply` handler: ```javascript const target = { greet(name) { console.log(`Hello, ${name}!`); } }; const handler = { apply(target, thisArg, argumentsList) { console.log(`Calling function 'greet' with arguments: ${argumentsList}`); target.greet(...argumentsList); } }; const proxy = new Proxy(target, handler); proxy.greet("John"); // Output: Calling function 'greet' with arguments: // John \n Hello, John! ``` 4. `has` handler: ```javascript const target = { name: "John", age: 30 }; const handler = { has(target, property) { console.log(`Checking for property '${property}'`); return property in target; } }; const proxy = new Proxy(target, handler); console.log("name" in proxy); // Output: Checking for property 'name' \n true console.log("city" in proxy); // Output: Checking for property 'city' \n false ``` 5. `deleteProperty` handler: ```javascript const target = { name: "John", age: 30 }; const handler = { deleteProperty(target, property) { console.log(`Deleting property '${property}'`); delete target[property]; return true; } }; const proxy = new Proxy(target, handler); delete proxy.age; // Output: Deleting property 'age' console.log(proxy); // Output: { name: 'John' } ``` 6. `getPrototypeOf` handler: ```javascript const target = {}; const prototype = { greet: "Hello" }; const handler = { getPrototypeOf() { console.log("Retrieving prototype"); return Reflect.getPrototypeOf(target); } }; const proxy = new Proxy(target, handler); Object.setPrototypeOf(proxy, prototype); console.log(Object.getPrototypeOf(proxy)); // Output: Retrieving prototype \n { greet: 'Hello' } ``` #### more demonstration There **should be** more explanation and showcase underneath the hood... ### Usage Proxies offer a wide range of possibilities for customization and control over object behavior. Here are some common use cases where proxies can be valuable: - **Validation**: You can use proxies to enforce validation rules on object properties. By intercepting property assignment operations with the `set` handler, you can validate the incoming values and decide whether to allow the assignment or throw an error. - **Logging**: Proxies are useful for logging object access and modifications. With the `get` and `set` handlers, you can log property access or changes and gather information about how an object is being used. - **Caching**: Proxies can be employed to implement caching mechanisms. By intercepting property access with the `get` handler, you can check if the requested property has been cached and return the cached value, avoiding expensive computations or network requests. - **Security**: Proxies enable you to implement security measures by controlling access to sensitive properties or methods. By using the `get` and `set` handlers, you can enforce access restrictions and prevent unauthorized modifications. - **Virtualization**: With proxies, you can create virtual representations of objects and implement lazy loading or dynamic behavior. By intercepting property access with the `get` handler, you can dynamically generate or fetch the requested data. ### Summary Proxies in JavaScript provide a powerful mechanism to customize object behavior by intercepting and controlling fundamental operations. With the ability to define custom handlers, you can fine-tune the way objects are accessed, modified, and invoked. Proxies offer a wide range of applications, from data validation to logging, caching, security, and virtualization. Please note that the Proxy syntax is a feature introduced in ECMAScript 6 (ES6) and may not be supported in older browsers. Before using the Proxy syntax, make sure to check the compatibility of your target environments. By understanding and utilizing proxies effectively, you can enhance the flexibility, modularity, and security of your JavaScript code. However, keep in mind the compatibility limitations in older environments and verify that proxies are supported in your target platforms. ## Regular Expression

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully