owned this note
owned this note
Published
Linked with GitHub
# 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