Skip to content

Add new articles on this keyword, rest operator, and more #220

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions en/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@
- [Closures](functions/closures.md)
- [Set Interval](functions/set-interval.md)
- [Set Timeout](functions/set-timeout.md)
- [Rest Operator](functions/rest-operator.md)
- [This Keyword](functions/this-keyword.md)
- [Hoisting](functions/hoisting.md)
- [Getters and Setters](functions/getters-setters.md)
- [Objects](objects/README.md)
- [Properties](objects/properties.md)
- [Mutable](objects/mutable.md)
Expand Down
6 changes: 5 additions & 1 deletion en/functions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,8 @@ In this chapter, we will explore following topics:
* [High Order Functions](./higher-order.md)
* [Recursive Functions](./recursive-functions.md)
* [Set Interval](./set-interval.md)
* [Set Timeout](./set-timeout.md)
* [Set Timeout](./set-timeout.md)
* [This Keyword](./this-keyword.md)
* [Rest Operator](./rest-operator.md)
* [Hoisting](./hoisting.md)
* [Getters and Setters](./getters-setters.md)
105 changes: 105 additions & 0 deletions en/functions/getters-setters.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
---
chapter: 8
description: Understanding Getters and Setters in JavaScript.
---

## Understanding Getters and Setters in JavaScript

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.

### What are Getters and Setters?

- **Getters**: Methods that get the value of a specific property.
- **Setters**: Methods that set the value of a specific property.

### Defining Getters and Setters

You can define getters and setters using the `get` and `set` keywords within an object literal or a class.

### Example with Object Literals

Here's an example of defining getters and setters in an object literal:

```javascript
let person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return `${this.firstName} ${this.lastName}`;
},
set fullName(name) {
[this.firstName, this.lastName] = name.split(" ");
}
};

console.log(person.fullName); // Output: John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith
```

### Example with Classes

Here's an example of defining getters and setters in a class:

```javascript
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

get fullName() {
return `${this.firstName} ${this.lastName}`;
}

set fullName(name) {
[this.firstName, this.lastName] = name.split(" ");
}
}

let person = new Person("John", "Doe");
console.log(person.fullName); // Output: John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: Jane
console.log(person.lastName); // Output: Smith
```

### Benefits of Using Getters and Setters

1. **Encapsulation**: Control how properties are accessed and modified.
2. **Validation**: Add validation logic when setting a property.
3. **Computed Properties**: Create properties that are computed based on other properties.

### Example of Validation

Here's an example of adding validation logic in a setter:

```javascript
class User {
constructor(username) {
this._username = username;
}

get username() {
return this._username;
}

set username(name) {
if (name.length < 3) {
console.error("Username must be at least 3 characters long.");
} else {
this._username = name;
}
}
}

let user = new User("jsmith");
console.log(user.username); // Output: jsmith
user.username = "jo"; // Output: Username must be at least 3 characters long.
console.log(user.username); // Output: jsmith
```

### Conclusion

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.
64 changes: 64 additions & 0 deletions en/functions/hoisting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
chapter: 8
description: Understanding Hoisting for Functions in JavaScript.
---

## Understanding Hoisting for Functions in JavaScript

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.

### Function Hoisting

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.

### Example of Function Hoisting

Here's an example to illustrate function hoisting:

```javascript
console.log(greet()); // Output: Hello, World!

function greet() {
return "Hello, World!";
}
```

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.

### Function Expressions and Hoisting

Unlike function declarations, function expressions are not hoisted. This means that you cannot call a function expression before it is defined.

### Example of Function Expression

Here's an example to illustrate the difference:

```javascript
console.log(greet()); // Output: TypeError: greet is not a function

var greet = function() {
return "Hello, World!";
};
```

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.

### Hoisting with `let` and `const`

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`.

### Example with `let` and `const`

```javascript
console.log(greet); // Output: ReferenceError: Cannot access 'greet' before initialization

let greet = function() {
return "Hello, World!";
};
```

In this example, the `greet` variable is hoisted, but it is not initialized, resulting in a `ReferenceError` when accessed before its declaration.

### Conclusion

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.
75 changes: 75 additions & 0 deletions en/functions/rest-operator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
---
chapter: 8
description: Understanding the Rest Operator for Functions in JavaScript.
---

## Understanding the Rest Operator for Functions in JavaScript

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.

### Syntax

The rest operator is used by prefixing three dots (`...`) before the parameter name in a function definition.

### Example of Using the Rest Operator

Here's a basic example of using the rest operator in a function:

```javascript
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(4, 5, 6, 7)); // Output: 22
```

In this example, the `sum` function can accept any number of arguments, which are then combined into an array called `numbers`.

### Combining Rest Operator with Other Parameters

You can use the rest operator in combination with other parameters, but it must be the last parameter in the function definition.

```javascript
function greet(greeting, ...names) {
return `${greeting}, ${names.join(" and ")}!`;
}

console.log(greet("Hello", "Alice", "Bob")); // Output: Hello, Alice and Bob!
console.log(greet("Hi", "Charlie", "Dave", "Eve")); // Output: Hi, Charlie and Dave and Eve!
```

In this example, the `greet` function takes a fixed `greeting` parameter and a variable number of `names`.

### Rest Operator in Arrow Functions

The rest operator can also be used in arrow functions:

```javascript
const multiply = (...numbers) => numbers.reduce((acc, curr) => acc * curr, 1);

console.log(multiply(2, 3)); // Output: 6
console.log(multiply(4, 5, 6)); // Output: 120
```

### Practical Use Cases

1. **Handling Variable Arguments**: Functions that need to handle a variable number of arguments, such as mathematical operations or string manipulations.
2. **Combining Arrays**: Functions that need to combine multiple arrays into one.
3. **Event Handlers**: Functions that handle events with varying numbers of arguments.

### Example of Combining Arrays

Here's an example of using the rest operator to combine arrays:

```javascript
function combineArrays(...arrays) {
return arrays.flat();
}

console.log(combineArrays([1, 2], [3, 4], [5, 6])); // Output: [1, 2, 3, 4, 5, 6]
```

### Conclusion

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.
124 changes: 124 additions & 0 deletions en/functions/this-keyword.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
---
chapter: 8
description: Understanding the `this` Keyword in JavaScript.
---

## Understanding the `this` Keyword in JavaScript

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.

### `this` in Global Context

In the global execution context (outside of any function), `this` refers to the global object, which is `window` in browsers.

```javascript
console.log(this); // Output: Window {...}
```

### `this` in Object Methods

When used in an object method, `this` refers to the object the method belongs to.

```javascript
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return `${this.firstName} ${this.lastName}`;
}
};

console.log(person.fullName()); // Output: John Doe
```

### `this` in Constructor Functions

In a constructor function, `this` refers to the newly created instance.

```javascript
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

const person1 = new Person("Jane", "Smith");
console.log(person1.firstName); // Output: Jane
```

### `this` in Arrow Functions

Arrow functions do not have their own `this`. Instead, `this` is lexically inherited from the outer function where the arrow function is defined.

```javascript
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
const getFullName = () => `${this.firstName} ${this.lastName}`;
return getFullName();
}
};

console.log(person.fullName()); // Output: John Doe
```

### `this` in Event Handlers

In event handlers, `this` refers to the element that received the event.

```html
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function() {
console.log(this); // Output: <button id="myButton">Click me</button>
});
</script>
```

### Changing `this` with `call`, `apply`, and `bind`

You can explicitly set the value of `this` using `call`, `apply`, and `bind`.

#### `call` Method

The `call` method calls a function with a given `this` value and arguments provided individually.

```javascript
function greet() {
console.log(`Hello, ${this.name}`);
}

const person = { name: "Alice" };
greet.call(person); // Output: Hello, Alice
```

#### `apply` Method

The `apply` method calls a function with a given `this` value and arguments provided as an array.

```javascript
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}

const person = { name: "Bob" };
greet.apply(person, ["Hi"]); // Output: Hi, Bob
```

#### `bind` Method

The `bind` method creates a new function that, when called, has its `this` keyword set to the provided value.

```javascript
function greet() {
console.log(`Hello, ${this.name}`);
}

const person = { name: "Charlie" };
const greetPerson = greet.bind(person);
greetPerson(); // Output: Hello, Charlie
```

### Conclusion

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`.
Loading