0% found this document useful (0 votes)
17 views

Angular Session-03

The document provides an overview of some important array methods in JavaScript, including map(), reduce(), filter(), forEach(), indexOf(), lastIndexOf(), and more. It discusses what each method does, provides syntax examples, and lists common uses cases. For map(), reduce(), and filter(), it explains how to pass callback functions to modify or extract data from the array. The document also covers let, const, and var, explaining how they differ in terms of scope and reassignment.

Uploaded by

shubhamsen.hzs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Angular Session-03

The document provides an overview of some important array methods in JavaScript, including map(), reduce(), filter(), forEach(), indexOf(), lastIndexOf(), and more. It discusses what each method does, provides syntax examples, and lists common uses cases. For map(), reduce(), and filter(), it explains how to pass callback functions to modify or extract data from the array. The document also covers let, const, and var, explaining how they differ in terms of scope and reassignment.

Uploaded by

shubhamsen.hzs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Angular Training

Session -2
Outlines
- Some Important Methods in Array
- var, let and const

www.webstackacademy.com www.webstackacademy.com
•flat()

Methods in Array : (39)

at filter flatMap lastIndexOf shift toSpliced

concat find forEach map slice toString

copyWithin findIndex includes pop some unshift

entries findLast indexOf push sort values

every findLastIndex join reduce splice with

fill flat keys reduceRight toLocaleString Array

reverse toReversed toSorted


Callbacks
Callbacks are functions that are passed to other functions as parameters.

They're necessary for asynchronous code, encapsulation, eliminating code repetition,


and so much more.

One of the most powerful properties of JavaScript is that functions are first-class
objects.

This means that they are like any other object and have the same properties as
standard objects.

In fact, we should think of them as nothing more than callable objects.


function fnGenerator() {
return function() {
console.log('Ran the inner function');
}
}

const fnReturned = fnGenerator();


console.log(fnReturned); // -> [Function]
fnReturned(); // -> Ran the inner function
We can also pass functions in to other functions.

function fnCaller(fn) {
fn();
}

function log() {
console.log('Calling log');
}

fnCaller(log); // -> Calling log


Callback functions allow us to do interesting things with our code. Passing
functions as parameters and returning functions allow us to:

• Eliminate code repetition


• Allow asynchronous execution
• Allow event binding, such as with user interaction
• Hide data and create a pleasant user interface
• Prevent scope pollution
function multiply(x, y) {
return x * y;
}

function callMultiply(fn, val1,


val2) {
// Your code here
}
Map() Method :

The map() method is used to get a modified version of the array or a reduced value
using callback functions

map() applies a function to each array element and creates a new array of the returned
values.

The syntax of the method is as follows:

array.map(function( currentValue, index, arr), thisValue )


The map() method accepts two parameters:
function(currentValue, index, arr):
This is a required parameter that runs on each element of array.
It contains three parameters: currentValue, index and arr.

thisValue: This parameter is optional. It holds the value of passed to the function.

The function that is be passed is given arguments by the map method in the
following order

function callbackfn (value: any, index: number, array: any[ ])


Example

var arr = [10, 20, 30, 40, 50] ;

arr1 = arr . map(a => a * 2);


console.log(arr);
console.log("doubled array:",arr1);

Uses of Map( )

A. Generic use of map()

let map = Array.prototype.map


let a = map.call('Hello World', function(x) {
return x.charCodeAt(0)
})
Mapping an array of numbers to an array of their square roots

let numbers = [3, 25, 100]


let roots =
numbers.map(function(num) {
return Math.sqrt(num)
})

Mapping an array of numbers with a function containing an argument


let numbers = [3, 25, 100]
let doubles =
numbers.map(function(num) {
return num * 2
})
Note: Since map() builds a new array, you should not use this method if:

 You are not using the array that is returned


 You are not returning any value from the callback
reduce() Method
 The reduce method reduces the array to a single value from left to right.

 This method leaves the original array unchanged.

 The syntax of the method is as follows:

arr.reduce(<function>);

 The reduce method gives arguments to the passed function in the following order:

function callbackfn( prev : any, curr : any, index: number, array: number[ ])
 For each element, the callbackfn will be passed with the previous callbackfn
function’s return value as the first argument, and the value of the element as the
second argument.

 If the array has only one value, that value is returned. For an empty array,
an error is thrown.

var arr = [10, 20, 30, 40, 50];


var val = arr.reduce((prev, curr) => prev + curr);
console.log("arr:",arr);
console.log("reduced val:", val);
uses of reduce :
Sum the values of an array :

let sum = [0, 1, 2, 3].reduce(function (accumulator,


currentValue) {
return accumulator + currentValue
}, 0)

Flatten an array of arrays

let flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(accumulator, currentValue)
{
return accumulator.concat(currentValue)
}, [ ] )
Group objects by a property
let people = [
{ name: 'Matt', age: 25 },
{ name: ‘ Asma ', age: 23 },
{ name: ‘ Cami ', age: 29 }
];

function groupBy ( objectArray , property) {


return objectArray.reduce(function (acc, obj) {
let key = obj [property]
if (!acc [key]) {
acc [key] = []
}
acc[key].push(obj)
return acc
}, {})
}

let groupedPeople = groupBy(people, 'age')


Using reduce and map() together
we need to count array elements that satisfy a certain condition
1. Map the array into an array of zeros and ones.
2. Reduce the array of zeros and ones into the sum.

var arr = ['Hello', 1, true, NaN, 'Bye'];


var countArr = arr.map( ele => typeof ele === 'string' ? 1 : 0);
var sum = countArr.reduce((prev, curr)=> prev + curr);
console.log("arr:",arr);
console.log("array from map:", countArr);
console.log("number of Strings:",sum);
reduceRight()
The reduceRight() method is just like reduce() except that it iterates from right to left
instead of left to right.

var arr = [6, 4, 5, 6, 7, 7];


var reduced = arr.reduce(function(curr, next) {
return curr + next;
}, 0);
var reducedRight = arr.reduceRight(function(curr, next) {
return curr + next;
}, 0)
console.log(reduced);
console.log(reducedRight);
every()
The every() array method checks to see if every single element in the array satisfies the
condition you have passed it.

var arr = [6, 4, 5, 6, 7, 7];


arr.every(function(element) {
return element % 2 === 0; //checks to see if even
}); // false
some()
The some() method is almost exactly like the every() method, with the exception
that it checks to see if at least one element satisfies the condition you have set for it.

var arr = [6, 4, 5, 6, 7, 7];

arr.some(function(element) {
return element % 2 === 0; //checks to see if even
}); //true
filter()

If the element passes the test, you push that element to a new array.
var arr = [6, 4, 5, 6, 7, 7];
var x = arr . filter(function(element) {
return element/2 > 3;
})
forEach()
A method that is very similar to a for loop.
For every element found in the array, the forEach() method executes a callback
function on it.

var arr = [6, 4, 5, 6, 7, 7];


arr.forEach(function(element) {
console.log(element * 2);
})
indexOf() and lastIndexOf()
 If you need to search for a particular element in an array, you can do that with
indexOf() and lastIndexOf().
 indexOf() returns the first index of the search parameter if it’s found, otherwise it
returns a -1.
 In lastIndexOf(), it gives us the last index of the search element in the array. Again,
if not found, it’ll return -1.

isArray()
 This method checks to see if the object passed to it is an array or not.
Returns a boolean.
Earlier before 2015, the only keyword available to declare variables was the var keyword.

ES6 -> let ,const

Scope of var, let and const

var : Function in which the variable is declared


let: Block in which the variable is declared
const: Block in which the variable is declared

let is similar to var. It allows us to declare variables in our local scope.


The differences are that let is:
 not hoisted
 block-scoped
Rules of Thumb:

 Don’t use var, because let and const is more specific

 Default to const, because it cannot be re-assigned or re-declared

 Use let when you want to re-assign the variable in future

 Always prefer using let over var and const over let
Unchanging Values With const

Example 1
const taxRate = 0.1;
const total = 100 + (100 * taxRate);
// Skip 100 lines of code
console.log(`Your Order is ${total}`); total}`);

var taxRate = 0.1;


var total = 100 + (100 * taxRate);
// Skip 100 lines of code
console.log(`Your Order is ${total}`);
Example 2
const taxRate = 0.1;
const shipping = 5.00;
let total = 100 + (100 * taxRate) + shipping;
// Skip 100 lines of code
console.log(`Your Order is ${total}`);
Changing the value of a const variable
const discountable = [];
const cart = [
{
item: 'Book',
discountAvailable: false,
},
{
item: 'Magazine',
discountAvailable: true,
},
];
// Skip some lines
for (let i = 0; i < cart.length; i++) {
if (cart[i].discountAvailable) {
discountable.push(cart[i]);
}
}
console.log(discountable););
d
What is Javascript hoisting?
Hoisting is Javascript’s default behavior of moving all declarations to the top
of their functional scope.

Hoisting variables

JS hoists the declaration of a variable up and allows it to be used. This


way, a variable can be declared after it has been used.
Hoisting functions

func();

function func() {
var a = 1;
var b = 2;
var c = 3;
console.log(a + " " + b + " " + c);
}
Thank You

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy