Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

CHP 5

Ch4

\
FLUX ARCTIETURE
The Flux architecture is a design pattern used in React applications to manage the flow of data and
state within the application. It was developed by Facebook to address the problem of data flow in
large and complex applications. In simple terms, Flux promotes a unidirectional flow of data, which
can make it easier to understand and maintain your code.
1. **View**: The user interface (UI) that the user interacts with. In a React application, this would be
your components.

2. **Action**: Events or user interactions that trigger changes in the application's state. These are
plain JavaScript objects that describe what should happen.

3. **Dispatcher**: A central hub that receives actions and dispatches them to the appropriate stores.
It ensures that actions are processed in a predictable order.

4. **Store**: Stores contain the application's state and business logic. They listen to actions, update
their state, and notify the views of changes. Each store is responsible for a specific part of the
application's state.

5. **View (again)**: Once the store updates, it notifies the views, which then re-render with the new
data.

Here's a simple example of how Flux could be implemented in a React application:

Let's say you have a simple "To-Do List" application:

1. **View**: You have a React component that displays the to-do items.

2. **Action**: When a user clicks a "Add New Task" button, an action is dispatched, e.g., `{ type:
'ADD_TASK', text: 'Buy groceries' }`.

3. **Dispatcher**: The Dispatcher receives this action and sends it to the appropriate Store.

4. **Store**: You have a `TaskStore` that listens for the 'ADD_TASK' action. It updates its internal
state to include the new task, e.g., `{ id: 1, text: 'Buy groceries', completed: false }`.
5. View (again): The `TaskStore` notifies the view that the state has changed. The React component
displaying the to-do list re-renders with the updated list, now including the new task.This
unidirectional flow of data ensures that your application's state changes are predictable and
maintainable. Actions are the only way to modify the state, and changes flow in one direction, which
makes it easier to debug and reason about your application's behavior.
CH3
CHP2
JAVASCRIPT PROMISES

JavaScript Promise are easy to manage when dealing with multiple


asynchronous operations where callbacks can create callback hell
leading to unmanageable code. Prior to promises events and callback
functions were used but they had limited functionalities and created
unmanageable code. Multiple callback functions would create callback
hell that leads to unmanageable code. Promises are used to handle
asynchronous operations in JavaScript.

Syntax:
let promise = new Promise(function(resolve, reject){
//do something
});
Parameters

• The promise constructor takes only one argument which is a


callback function
• The callback function takes two arguments, resolve and reject
• Perform operations inside the callback function and if everything
went well then call resolve.
• If desired operations do not go well then call reject.
A Promise has four states:

1. fulfilled: Action related to the promise succeeded


2. rejected: Action related to the promise failed
3. pending: Promise is still pending i.e. not fulfilled or rejected yet
4. settled: Promise has been fulfilled or rejected
Promise Consumers: Promises can be consumed by registering
functions using .then and .catch methods.

1.Promise then() Method: It is invoked when a promise is either


resolved or rejected. It may also be defined as a carrier that takes data
from promise and further executes it successfully.

Parameters: It takes two functions as parameters.

• The first function is executed if the promise is resolved and a


result is received.
• The second function is executed if the promise is rejected and an
error is received. (It is optional and there is a better way to handle
error using .catch() method
Syntax:
.then(function(result){
//handle success
}, function(error){
//handle error
})
Example 2: This example shows how the then method handles when a
promise is resolved
• Javascript
let promise = new Promise(function (resolve, reject) {
resolve('Geeks For Geeks');
})

promise
.then(function (successMessage) {
//success handler function is invoked
console.log(successMessage);
}, function (errorMessage) {
console.log(errorMessage);
});
ES6 Loop
Definite Loops:

1. **`for` Loop**: A definite loop is one where the number of iterations is known in advance. The `for`
loop is typically used when you have a specific number of iterations.

```javascript
for (let i = 0; i < 5; i++) {
// Code to execute repeatedly
}
```

2. for...in` Loop: This loop is used for iterating over the enumerable properties of an object. It's often
used for objects and their properties.

```javascript
for (let key in object) {
if (object.hasOwnProperty(key)) {
// Code to execute for each property
}
}
```

3. for...of` Loop The `for...of` loop is used for iterating over the values of iterable objects like arrays,
strings, maps, sets, etc.
```javascript
for (const value of iterable) {
// Code to execute for each value
}
```

**Indefinite Loops:**

1. `while` Loop: An indefinite loop is one where the number of iterations is not known in advance and
depends on a condition. The `while` loop keeps running as long as a condition is true.

```javascript
while (condition) {
// Code to execute as long as the condition is true
}
```

2. do...while` Loop: This loop is similar to the `while` loop but guarantees that the code block inside
the loop will run at least once, as the condition is checked after the loop body execution.

```javascript
do {
// Code to execute at least once
} while (condition);
```

ES6 arrow function


functions are introduced in the ES6 version. Arrow functions enable us
to write functions with simpler and shorter syntax and make our code
more readable and organized.

Arrow functions are anonymous functions i.e. they are functions


without a name and are not bound by an identifier. Arrow functions do
not return any value and can be declared without the function keyword.
They are also called Lambda Functions.
• Arrow functions do not have the prototype property like this,
arguments, or super.
• Arrow functions cannot be used with the new keyword.
• Arrow functions cannot be used as constructors.
Syntax:

For Single Argument:


let function_name = argument1 => expression
For Multiple Arguments:
let function_name = (argument1, argument2 , ...) =>
expression
Note: In case of multiple arguments you need to enclose the arguments
within brackets.

Uses of arrow function: The arrow function is a single liner we needn’t


use the return keyword.
• JavaScript
// Arrow function for multiplying two numbers
value = (a, b) => a * b;
console.log(value(3, 5));

Output:
15
Example 2: When there are more than two lines to process
From the previous example, we can see that when there’s a single line
of code to be executed we didn’t use the return keyword but if there are
more than two lines to be processed, we need to use a return keyword.
let’s demonstrate that with an example:
• JavaScript
number = (a, b) => {
c = 5;
return (a + b) * c;
};
console.log(number(2, 3));

Output:
25
Word.

ES^ vs Es5

SR.NO. ES5 ES6

ECMA script is a ECMA script is a


trademarked scripting trademarked scripting
language specification language specification
1. defined by Ecma defined by Ecma
international. The fifth international. The sixth
edition of the same is edition of the same is
known as ES5 known as ES6

It was introduced in It was introduced in


2.
2009. 2015.

In ES6, there are some


It supports primitive additions to JavaScript
data types that are data types. It
3. string, number, introduced a new
boolean, null, and primitive data type
undefined. ‘symbol’ for supporting
unique values.
There are only one way There are two new
to define the variables ways to define
4.
by using the var variables that are let
keyword. and const.

It has a lower
It has a higher
5. performance as
performance than ES5.
compared to ES6.

Object manipulation is
Object manipulation is
6. less time-consuming in
time-consuming in ES5.
ES6.

An arrow function is a
In ES5, both function new feature introduced
and return keywords in ES6 by which we
7.
are used to define a don’t require the
function. function keyword to
define the function.

It provides a larger
It provides a less range
range of community
8. of community supports
supports than that of
than that of ES5
ES6
CHP1

You might also like