JS5 ClassNotes (1) PDF
Document Details
Uploaded by Deleted User
Apna College
Tags
Summary
This document is a set of class notes on JavaScript, covering functions, arrow functions, forEach, map, filter, and reduce methods. The notes also include practice questions and examples.
Full Transcript
Functions in JS Block of code that performs a specific task, can be invoked whenever needed lege Col pna A Functions in JS Function Definition Function Call function fu...
Functions in JS Block of code that performs a specific task, can be invoked whenever needed lege Col pna A Functions in JS Function Definition Function Call function functionName( ) { functionName( ); //do some work lege } Col pna A function functionName( param1, param2...) { //do some work } Arrow Functions ge Compact way of writing a function olle a C const functionName = ( param1, param2...) => { } //do some work Apn const sum = ( a, b ) => { return a + b; } Let‘s Practice Qs. Create a function using the “function” keyword that takes a String as an argument & returns the number of vowels in the string. lege Col na Qs. Create an arrow function to perform the same task. Ap forEach Loop in Arrays arr.forEach( callBackFunction ) CallbackFunction : Here, it is a function to execute for each element in the array lege l *A callback is a function passed as an argument to another function. a Co arr.forEach( ( val ) => { console.log(val); Ap n }) Let‘s Practice Qs. For a given array of numbers, print the square of each value using the forEach loop. lege Col pna A Some More Array Methods Map Creates a new array with the results of some operation. The value its callback returns are used to form new array lege Col a arr.map( callbackFnx( value, index, array ) ) Ap let newArr = arr.map( ( val ) => { n return val * 2; }) Some More Array Methods Filter Creates a new array of elements that give true for a condition/filter. ge Eg: all even elements olle let newArr = arr.filter( ( ( val ) => { na C }) return val % 2 === 0; Ap Some More Array Methods Reduce lege Col Performs some operations & reduces the array to a single value. It returns na that single value. Ap Let‘s Practice Qs. We are given array of marks of students. Filter our of the marks of students that scored 90+. lege Col na Qs. Take a number n as input from user. Create an array of numbers from 1 to n. p A Use the reduce method to calculate sum of all numbers in the array. Use the reduce method to calculate product of all numbers in the array.