Skip to content

Commit d57d035

Browse files
Hachondeorosumn2u
authored andcommitted
Add new articles on this keyword, rest operator, and more
Added comprehensive documentation for `this` keyword, rest operator, hoisting, and getters and setters in JavaScript. Updated the table of contents to include these new topics for better navigation and understanding.
1 parent 9911647 commit d57d035

File tree

6 files changed

+377
-1
lines changed

6 files changed

+377
-1
lines changed

en/SUMMARY.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@
5353
- [Closures](functions/closures.md)
5454
- [Set Interval](functions/set-interval.md)
5555
- [Set Timeout](functions/set-timeout.md)
56+
- [Rest Operator](functions/rest-operator.md)
57+
- [This Keyword](functions/this-keyword.md)
58+
- [Hoisting](functions/hoisting.md)
59+
- [Getters and Setters](functions/getters-setters.md)
5660
- [Objects](objects/README.md)
5761
- [Properties](objects/properties.md)
5862
- [Mutable](objects/mutable.md)

en/functions/README.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,8 @@ In this chapter, we will explore following topics:
5151
* [High Order Functions](./higher-order.md)
5252
* [Recursive Functions](./recursive-functions.md)
5353
* [Set Interval](./set-interval.md)
54-
* [Set Timeout](./set-timeout.md)
54+
* [Set Timeout](./set-timeout.md)
55+
* [This Keyword](./this-keyword.md)
56+
* [Rest Operator](./rest-operator.md)
57+
* [Hoisting](./hoisting.md)
58+
* [Getters and Setters](./getters-setters.md)

en/functions/getters-setters.md

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
---
2+
chapter: 8
3+
description: Understanding Getters and Setters in JavaScript.
4+
---
5+
6+
## Understanding Getters and Setters in JavaScript
7+
8+
Getters and setters in JavaScript are special methods that provide a way to access and update the properties of an object. They allow you to control how a property is accessed and modified, adding a layer of abstraction and encapsulation.
9+
10+
### What are Getters and Setters?
11+
12+
- **Getters**: Methods that get the value of a specific property.
13+
- **Setters**: Methods that set the value of a specific property.
14+
15+
### Defining Getters and Setters
16+
17+
You can define getters and setters using the `get` and `set` keywords within an object literal or a class.
18+
19+
### Example with Object Literals
20+
21+
Here's an example of defining getters and setters in an object literal:
22+
23+
```javascript
24+
let person = {
25+
firstName: "John",
26+
lastName: "Doe",
27+
get fullName() {
28+
return `${this.firstName} ${this.lastName}`;
29+
},
30+
set fullName(name) {
31+
[this.firstName, this.lastName] = name.split(" ");
32+
}
33+
};
34+
35+
console.log(person.fullName); // Output: John Doe
36+
person.fullName = "Jane Smith";
37+
console.log(person.firstName); // Output: Jane
38+
console.log(person.lastName); // Output: Smith
39+
```
40+
41+
### Example with Classes
42+
43+
Here's an example of defining getters and setters in a class:
44+
45+
```javascript
46+
class Person {
47+
constructor(firstName, lastName) {
48+
this.firstName = firstName;
49+
this.lastName = lastName;
50+
}
51+
52+
get fullName() {
53+
return `${this.firstName} ${this.lastName}`;
54+
}
55+
56+
set fullName(name) {
57+
[this.firstName, this.lastName] = name.split(" ");
58+
}
59+
}
60+
61+
let person = new Person("John", "Doe");
62+
console.log(person.fullName); // Output: John Doe
63+
person.fullName = "Jane Smith";
64+
console.log(person.firstName); // Output: Jane
65+
console.log(person.lastName); // Output: Smith
66+
```
67+
68+
### Benefits of Using Getters and Setters
69+
70+
1. **Encapsulation**: Control how properties are accessed and modified.
71+
2. **Validation**: Add validation logic when setting a property.
72+
3. **Computed Properties**: Create properties that are computed based on other properties.
73+
74+
### Example of Validation
75+
76+
Here's an example of adding validation logic in a setter:
77+
78+
```javascript
79+
class User {
80+
constructor(username) {
81+
this._username = username;
82+
}
83+
84+
get username() {
85+
return this._username;
86+
}
87+
88+
set username(name) {
89+
if (name.length < 3) {
90+
console.error("Username must be at least 3 characters long.");
91+
} else {
92+
this._username = name;
93+
}
94+
}
95+
}
96+
97+
let user = new User("jsmith");
98+
console.log(user.username); // Output: jsmith
99+
user.username = "jo"; // Output: Username must be at least 3 characters long.
100+
console.log(user.username); // Output: jsmith
101+
```
102+
103+
### Conclusion
104+
105+
Getters and setters provide a powerful way to manage object properties in JavaScript. By using them, you can add validation, encapsulation, and computed properties, making your code more robust and maintainable.

en/functions/hoisting.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
chapter: 8
3+
description: Understanding Hoisting for Functions in JavaScript.
4+
---
5+
6+
## Understanding Hoisting for Functions in JavaScript
7+
8+
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This means that you can use functions and variables before they are declared in the code.
9+
10+
### Function Hoisting
11+
12+
In JavaScript, function declarations are hoisted to the top of their containing scope. This allows you to call a function before it is defined in the code.
13+
14+
### Example of Function Hoisting
15+
16+
Here's an example to illustrate function hoisting:
17+
18+
```javascript
19+
console.log(greet()); // Output: Hello, World!
20+
21+
function greet() {
22+
return "Hello, World!";
23+
}
24+
```
25+
26+
In this example, the `greet` function is called before it is defined, but it works because the function declaration is hoisted to the top of the scope.
27+
28+
### Function Expressions and Hoisting
29+
30+
Unlike function declarations, function expressions are not hoisted. This means that you cannot call a function expression before it is defined.
31+
32+
### Example of Function Expression
33+
34+
Here's an example to illustrate the difference:
35+
36+
```javascript
37+
console.log(greet()); // Output: TypeError: greet is not a function
38+
39+
var greet = function() {
40+
return "Hello, World!";
41+
};
42+
```
43+
44+
In this example, the `greet` function is defined as a function expression, and calling it before the definition results in an error because the variable `greet` is hoisted, but its assignment is not.
45+
46+
### Hoisting with `let` and `const`
47+
48+
Variables declared with `let` and `const` are also hoisted, but they are not initialized. This means that accessing them before their declaration results in a `ReferenceError`.
49+
50+
### Example with `let` and `const`
51+
52+
```javascript
53+
console.log(greet); // Output: ReferenceError: Cannot access 'greet' before initialization
54+
55+
let greet = function() {
56+
return "Hello, World!";
57+
};
58+
```
59+
60+
In this example, the `greet` variable is hoisted, but it is not initialized, resulting in a `ReferenceError` when accessed before its declaration.
61+
62+
### Conclusion
63+
64+
Understanding hoisting is crucial for writing predictable and bug-free JavaScript code. Function declarations are hoisted, allowing them to be called before they are defined, while function expressions are not hoisted, leading to potential errors if called before their definition. Variables declared with `let` and `const` are hoisted but not initialized, resulting in `ReferenceError` if accessed before their declaration.

en/functions/rest-operator.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
---
2+
chapter: 8
3+
description: Understanding the Rest Operator for Functions in JavaScript.
4+
---
5+
6+
## Understanding the Rest Operator for Functions in JavaScript
7+
8+
The rest operator (`...`) in JavaScript allows you to represent an indefinite number of arguments as an array. It is particularly useful in function definitions to handle multiple parameters without explicitly specifying them.
9+
10+
### Syntax
11+
12+
The rest operator is used by prefixing three dots (`...`) before the parameter name in a function definition.
13+
14+
### Example of Using the Rest Operator
15+
16+
Here's a basic example of using the rest operator in a function:
17+
18+
```javascript
19+
function sum(...numbers) {
20+
return numbers.reduce((acc, curr) => acc + curr, 0);
21+
}
22+
23+
console.log(sum(1, 2, 3)); // Output: 6
24+
console.log(sum(4, 5, 6, 7)); // Output: 22
25+
```
26+
27+
In this example, the `sum` function can accept any number of arguments, which are then combined into an array called `numbers`.
28+
29+
### Combining Rest Operator with Other Parameters
30+
31+
You can use the rest operator in combination with other parameters, but it must be the last parameter in the function definition.
32+
33+
```javascript
34+
function greet(greeting, ...names) {
35+
return `${greeting}, ${names.join(" and ")}!`;
36+
}
37+
38+
console.log(greet("Hello", "Alice", "Bob")); // Output: Hello, Alice and Bob!
39+
console.log(greet("Hi", "Charlie", "Dave", "Eve")); // Output: Hi, Charlie and Dave and Eve!
40+
```
41+
42+
In this example, the `greet` function takes a fixed `greeting` parameter and a variable number of `names`.
43+
44+
### Rest Operator in Arrow Functions
45+
46+
The rest operator can also be used in arrow functions:
47+
48+
```javascript
49+
const multiply = (...numbers) => numbers.reduce((acc, curr) => acc * curr, 1);
50+
51+
console.log(multiply(2, 3)); // Output: 6
52+
console.log(multiply(4, 5, 6)); // Output: 120
53+
```
54+
55+
### Practical Use Cases
56+
57+
1. **Handling Variable Arguments**: Functions that need to handle a variable number of arguments, such as mathematical operations or string manipulations.
58+
2. **Combining Arrays**: Functions that need to combine multiple arrays into one.
59+
3. **Event Handlers**: Functions that handle events with varying numbers of arguments.
60+
61+
### Example of Combining Arrays
62+
63+
Here's an example of using the rest operator to combine arrays:
64+
65+
```javascript
66+
function combineArrays(...arrays) {
67+
return arrays.flat();
68+
}
69+
70+
console.log(combineArrays([1, 2], [3, 4], [5, 6])); // Output: [1, 2, 3, 4, 5, 6]
71+
```
72+
73+
### Conclusion
74+
75+
The rest operator is a powerful feature in JavaScript that allows functions to handle an indefinite number of arguments efficiently. By using the rest operator, you can write more flexible and concise functions that can adapt to various input scenarios.

en/functions/this-keyword.md

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
---
2+
chapter: 8
3+
description: Understanding the `this` Keyword in JavaScript.
4+
---
5+
6+
## Understanding the `this` Keyword in JavaScript
7+
8+
The `this` keyword in JavaScript refers to the object it belongs to. It has different values depending on where it is used: in a method, alone, in a function, in an event, etc.
9+
10+
### `this` in Global Context
11+
12+
In the global execution context (outside of any function), `this` refers to the global object, which is `window` in browsers.
13+
14+
```javascript
15+
console.log(this); // Output: Window {...}
16+
```
17+
18+
### `this` in Object Methods
19+
20+
When used in an object method, `this` refers to the object the method belongs to.
21+
22+
```javascript
23+
const person = {
24+
firstName: "John",
25+
lastName: "Doe",
26+
fullName: function() {
27+
return `${this.firstName} ${this.lastName}`;
28+
}
29+
};
30+
31+
console.log(person.fullName()); // Output: John Doe
32+
```
33+
34+
### `this` in Constructor Functions
35+
36+
In a constructor function, `this` refers to the newly created instance.
37+
38+
```javascript
39+
function Person(firstName, lastName) {
40+
this.firstName = firstName;
41+
this.lastName = lastName;
42+
}
43+
44+
const person1 = new Person("Jane", "Smith");
45+
console.log(person1.firstName); // Output: Jane
46+
```
47+
48+
### `this` in Arrow Functions
49+
50+
Arrow functions do not have their own `this`. Instead, `this` is lexically inherited from the outer function where the arrow function is defined.
51+
52+
```javascript
53+
const person = {
54+
firstName: "John",
55+
lastName: "Doe",
56+
fullName: function() {
57+
const getFullName = () => `${this.firstName} ${this.lastName}`;
58+
return getFullName();
59+
}
60+
};
61+
62+
console.log(person.fullName()); // Output: John Doe
63+
```
64+
65+
### `this` in Event Handlers
66+
67+
In event handlers, `this` refers to the element that received the event.
68+
69+
```html
70+
<button id="myButton">Click me</button>
71+
<script>
72+
document.getElementById("myButton").addEventListener("click", function() {
73+
console.log(this); // Output: <button id="myButton">Click me</button>
74+
});
75+
</script>
76+
```
77+
78+
### Changing `this` with `call`, `apply`, and `bind`
79+
80+
You can explicitly set the value of `this` using `call`, `apply`, and `bind`.
81+
82+
#### `call` Method
83+
84+
The `call` method calls a function with a given `this` value and arguments provided individually.
85+
86+
```javascript
87+
function greet() {
88+
console.log(`Hello, ${this.name}`);
89+
}
90+
91+
const person = { name: "Alice" };
92+
greet.call(person); // Output: Hello, Alice
93+
```
94+
95+
#### `apply` Method
96+
97+
The `apply` method calls a function with a given `this` value and arguments provided as an array.
98+
99+
```javascript
100+
function greet(greeting) {
101+
console.log(`${greeting}, ${this.name}`);
102+
}
103+
104+
const person = { name: "Bob" };
105+
greet.apply(person, ["Hi"]); // Output: Hi, Bob
106+
```
107+
108+
#### `bind` Method
109+
110+
The `bind` method creates a new function that, when called, has its `this` keyword set to the provided value.
111+
112+
```javascript
113+
function greet() {
114+
console.log(`Hello, ${this.name}`);
115+
}
116+
117+
const person = { name: "Charlie" };
118+
const greetPerson = greet.bind(person);
119+
greetPerson(); // Output: Hello, Charlie
120+
```
121+
122+
### Conclusion
123+
124+
Understanding the `this` keyword is crucial for writing effective JavaScript code. Its value depends on the context in which it is used, and it can be explicitly set using `call`, `apply`, and `bind`.

0 commit comments

Comments
 (0)