Document Details

CheeryComprehension5871

Uploaded by CheeryComprehension5871

Université Ferhat Abbas de Sétif

Dr. AISSAOUA HABIB

Tags

javascript arrays programming web development

Summary

This document covers various JavaScript array operations including push, unshift, pop, shift, methods for iteration like forEach, map and reduce, and explanations of Promises. The document is part of learning materials likely for a computer science course. It includes code examples.

Full Transcript

Callback Function  A callback function is a function that is passed as an argument to another function and is executed after the completion of some operations. Dr. AISSAOUA HABIB University Setif -1- Callback Func...

Callback Function  A callback function is a function that is passed as an argument to another function and is executed after the completion of some operations. Dr. AISSAOUA HABIB University Setif -1- Callback Function  A callback's primary purpose is to execute code in response to an event. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." Dr. AISSAOUA HABIB University Setif -1- JavaScript arrays  A JavaScript array has the following characteristics: 1. First, an array can hold values of mixed types 2. Second, the size of an array is dynamic. JavaScript provides you with two ways to create an array. The first one is to use the Array constructor as follows: let scores = new Array(9,10,8,7,6); scores is an array that has five elements. JavaScript allows you to omit the new operator Dr. AISSAOUA HABIB University Setif -1- JavaScript arrays  The more preferred way to create an array is to use the array literal notation: let arrayName = [element1, element2, element3,...]; To access an element in an array, you specify an index in the square brackets [ ]: The length property of an array returns the number of elements. let mountains = ['Everest', 'Fuji', 'Nanga Parbat']; console.log(mountains.length); // 3 Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  To add an element to the end of an array, you use the push() method: let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea']; seas.push('Red Sea'); console.log(seas); output: [ 'Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea', 'Red Sea' ] To add an element to the beginning of an array, you use the unshift() method: let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea']; seas.unshift('Red Sea'); console.log(seas); Output:[ 'Red Sea', 'Black Sea', 'Caribbean Dr. AISSAOUA HABIB Sea',Setif University 'North -1- Sea', 'Baltic Sea' ] Some basic operations on arrays  To remove an element from the end of an array, you use the pop() method: let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea']; const lastElement = seas.pop(); console.log(lastElement); // Baltic Sea To remove an element from the beginning of an array, you use the shift() method: let seas = ['Black Sea', 'Caribbean Sea', 'North Sea', 'Baltic Sea']; const firstElement = seas.shift(); console.log(firstElement); // Black Sea Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  The forEach() method executes a provided function once for each array element. Example: let students = ['John', 'Sara', 'Jack']; students.forEach(myFunction); function myFunction(item) { console.log(item); } Output: John Sara Jack Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  The syntax of the forEach() method is: array.forEach(function(currentValue, index, arr)) Here, 1.function(currentValue, index, arr) - a function to be run for each element of an array 2. CurrentValue - the value of the current element 3. index (optional) - the index of the current element 4. arr (optional) - the array of the current elements Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays Example: let students = ['John', 'Sara', 'Jack']; students.forEach(myFunction); function myFunction(item, index, arr) { arr[index] = 'Hello ' + item; } console.log(students); The output: ["Hello John", "Hello Sara", "Hello Jack"] Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  The map method runs every item in the array through a function and returns a new array with the values returned by the function. Example: function double(number) { return number * 2; } let numbers = [1, 2, 3]; let numbersDoubled = numbers.map(double); The map() method runs the function we provided (double) on each item in the array and uses the return values to create a new array. In the example numbersDoubled is a new array containing [2, 4, 6] Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  Filter() runs every item in the array through a condition that we set, and returns a new array with the values that match the condition. Example: let testScores = [90, 50, 100, 66, 25, 80, 81]; function isHighScore(score) { return score > 80; } let highTestScores = testScores.filter(isHighScore); console.log(highTestScores); // logs [90, 100, 81] Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays  reduce() method executes a reducer function on each element of the array and returns a single output value. It takes two parameters: an accumulator and the current element of an array.  The accumulator is initialized to the first element of an array. The callback function performs some operation on the accumulator and the current element, and returns the result, which becomes the new value of the accumulator for the next iteration.  The syntax is: let value = arr.reduce(function(accumulator,currentValue) { //... }, [initial]); Dr. AISSAOUA HABIB University Setif -1- Some basic operations on arrays Example: let arr = [10, 20, 30, 40, 50, 60]; // Callback function for reduce method function sumofArray(sum, i) { return sum + i; } // Display output console.log(arr.reduce(sumofArray)); const getMax = (a, b) => Math.max(a, b); let x=[1, 150,100].reduce(getMax, 500); console.log(x); Dr. AISSAOUA HABIB University Setif -1- Asynchronous JavaScript Asynchronous (or async) execution refers to execution that doesn’t run in the sequence it appears in the code. In async programming the program doesn’t wait for the task to complete and can move on to the next task. Dr. AISSAOUA HABIB University Setif -1- Asynchronous JavaScript In a nutshell, the asynchronous implementation in JavaScript is done through a call stack, Callback Queue and WebAPI and EventLoop. Each engine contains a memory heap and a call stack where the heap is used to allocate memory and stack to do the function calling. Apart from these, a browser consists of WebApi's, EventLoop, and a Callback Queue. Dr. AISSAOUA HABIB University Setif -1- Asynchronous Behavior Dr. AISSAOUA HABIB University Setif -1- Asynchronous / callback function There are several ways to handle asynchronous code. The method that you choose should depend on the type of application you want to develop. These methods include callback functions, promises, and async/await. A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. Dr. AISSAOUA HABIB University Setif -1- Asynchronous / callback function Dr. AISSAOUA HABIB University Setif -1- Asynchronous / callback function The problem with callbacks is that if you have multiple asynchronous functions that depend on other asynchronous function execution; creating a chain of nested callbacks, it leads to callback hell. Callback hell affects the readability and maintainability of the code Dr. AISSAOUA HABIB University Setif -1- Promise To create a promise object, we use the Promise() constructor. let promise = new Promise(function(resolve, reject){ //do something }); The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and reject(). If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is called. Dr. AISSAOUA HABIB University Setif -1- Promise Let's suppose that the program below is an asynchronous program. Then the program can be handled by using a promise. Dr. AISSAOUA HABIB University Setif -1- Promises A promise may have one of three states: Pending, Fulfilled, Rejected A promise starts in a pending state. That means the process is not complete. If the operation is successful, the process ends in a fulfilled state. And, if an error occurs, the process ends in a rejected state. For example, when you request data from the server by using a promise, it will be in a pending state. When the data arrives successfully, it will be in a fulfilled state. If an error occurs, then it will be in a rejected state. Dr. AISSAOUA HABIB University Setif -1- Promise The then() function is invoked when a promise is either resolved or rejected, and the catch() function is invoked when a promise is either rejected or some error has occurred in execution. then() method takes two functions as parameters: 1. First function is executed if promise is resolved and a result is received. 2. Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to handle error using.catch() method) Dr. AISSAOUA HABIB University Setif -1- Promise Syntax: If you are interested only in successful outcomes, you can just pass one argument to it, like this: Dr. AISSAOUA HABIB University Setif -1- Promise The catch() method is used with the callback when the promise is rejected or if an error occurs: Dr. AISSAOUA HABIB University Setif -1- Promise The promise.then() call always returns a promise We can chain.then together to transform values or run additional async actions one after another. When the first.then method returns a value, the next.then method can receive that. The second one can now pass to the third.then() and so on. Dr. AISSAOUA HABIB University Setif -1- Promise Dr. AISSAOUA HABIB University Setif -1- Promise JavaScript provides a helper function Promise.all to handle multiple promises at once. In general, Promise.all takes an array of promises as an input and returns a Promise. Example: var allPromise = Promise.all([promise1, promise2,...]); Dr. AISSAOUA HABIB University Setif -1- Promise The returned promise will resolve once all the promises passed as input are resolved. If the returned promise is resolved, the resolved values of all promises are returned as an array. Dr. AISSAOUA HABIB University Setif -1- Promise But if at least one promise rejects, then Promise.all() rejects right away (without waiting for other promises to resolve) In this example, the returned promise is rejected because the second promise is rejected. The catch() method is executed to display the reason for the rejected promise. Dr. AISSAOUA HABIB University Setif -1- Promise Promise.allSettled() works similarly to Promise.all() but instead of rejecting immediately if any promise rejects, it waits for all promises to settle and then returns an array of objects with the status and value/reason for each promise. Dr. AISSAOUA HABIB University Setif -1- Async/await If you don’t want to create a promise chain when dealing with asynchronous operations, then you can try async/await. We use the async keyword before the name of a function to represent that the function is an asynchronous function. When such a function or method is called, it returns a promise. Dr. AISSAOUA HABIB University Setif -1- Async/await The async keyword can be placed before a function, like this: async function f() { return 1; } ////// or async function f() { return Promise.resolve(1); } This function returns a resolved promise with the result of 1. Now, we can handle the function as follow: f().then((res)=>console.log(res)) Dr. AISSAOUA HABIB University Setif -1- Async/await The await keyword is used inside the async function to wait for the asynchronous operation. The syntax to use await is: let result = await promise; await makes JavaScript wait until that promise settles and returns its result. Dr. AISSAOUA HABIB University Setif -1- Async/await As result, we get a console log displaying done!. That means our code is executed within 5 second. The execution of the function gets paused at the (*) line for 5 second because we have set it to await. Dr. AISSAOUA HABIB University Setif -1-

Use Quizgecko on...
Browser
Browser