0% found this document useful (0 votes)
8 views32 pages

JavaScript Notes Part1

Uploaded by

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

JavaScript Notes Part1

Uploaded by

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

JavaScript Notes.

simple if statement

let userName = prompt("Enter your UserName: ");


if (userName === "bisu2004") {
let pwd = prompt("Enter Password: ");
if (pwd === "log123bm") {
console.log("login Successfully");
alert("Logged in Successfully");
}
}

else if ladder

alert("Enter a number between 0 to 6");


const day = prompt("Enter a number");
const a=parseInt(day);
if (a >= 0) {
if (a === 0) {
console.log("its Sunday");
} else if (a === 1) {
console.log("its Monday");
} else if (a === 2) {
console.log("its Tuesday");
} else if (a === 3) {
console.log("its Wednesday");
} else if (a === 4) {
console.log("its Thursday");
} else if (a === 5) {
console.log("its Friday");
} else if (a === 6) {
console.log("its Saturday");
}
}

Else if ladder with else

alert("Enter a number between 0 to 6");


const day = prompt("Enter a number");
let a = parseInt(day);
if (a >= 0 && a <= 6) {
if (a === 0) {
console.log("its Sunday");
} else if (a === 1) {
console.log("its Monday");
} else if (a === 2) {
console.log("its Tuesday");
} else if (a === 3) {
console.log("its Wednesday");
} else if (a === 4) {
console.log("its Thursday");
} else if (a === 5) {
console.log("its Friday");
} else {
console.log("its Saturday");
}
} else {
console.log("invalid Input!!")
}

Nested if Else

const pswd = prompt("Enter a password: ");


if (pswd.length > 6) {
if (pswd.indexOf(' ') === -1) {
console.log("The password is Valid!!");
}
else {
console.log("the Password Must not include any space!!");
}
}
else {
console.log("Password to Short");
}

we can do the above program using the AND operator

const pswd = prompt("Enter a password: ")


if (pswd.length > 6 && pswd.indexOf(' ') === -1) {
console.log("password validation successful!!");
}
else {
console.log("Invalid password!!");
}

we can do the above program using the OR operator

const pswd = prompt("Enter a password: ")


if (pswd.length > 6 || pswd.indexOf(' ') === -1) {
console.log("password validation successful!!");
}
else {
console.log("Invalid password!!");
}
if one of the condition is true then the entire if statement is true.

when we are searching for various conditions then instead of using the
nested if else. it is better to use the switch statement.

Switch statement in
JavaScript
const day = prompt("Enter day: select input between 0 and 6");
let a = parseInt(day);
if (a >= 0 && a <= 6) {
switch (a) {
case 0:
console.log("Today is Sunday");
break;
case 1:
console.log("Today is Monday");
break;

case 2:
console.log("Today is Tuesday"); break;

case 3:
console.log("Today is Wednesday"); break;

case 4:
console.log("Today is Thursday"); break;

case 5:
console.log("Today is Friday"); break;

case 6:
console.log("Today is Saturday"); break;
default:
console.log("No data to show!!");
break;
}
}
else{
console.log("invalid input!!")
}
intoduction to
arrays (creating and
updating the array).
to make an empty array
let students = [];

an array of strings
let students = ['shyam' , 'raju' , 'baburao ganpatrao apte'];

an array of numbers
let num = [11,22,44,33];

a mixed array
let data = ['cat' , true , 12 , null];

just like the string the array also has a length method to find the no
of elements present in the array.
let ar=[];
ar.length; -> will return the length of the array

arrays are indexed. the indexing starts from 0.


let ar = ['Monday', 'Tuesday'];
console.log(ar[1]); //->will return Tuesday

we can also access the characters of each element in an array using the
double square bracket method. ar[][].
let ar = ['Monday', 'Tuesday'];
console.log(ar[1][2]); -> will return 'e';

unlike strings we can modify the elements in an array;


let ar = ['rad', 'blue'];
ar[0] = 'red';
console.log(ar);

unlike java , here in JavaScript we can insert elements in an array at


index n without inserting element at index n-(n-1);
let ar = ['Monday', 'Tuesday'];
ar[10] = 190;
console.log(ar);
there are basically 4
main methods to perform
any action on an array.
these are
1) Push 2)Pop 3)Shift
4)Unshift
// more methods include concat->
merge arrays | includes-> looks for a
value| indexOf-> just like
string.indexOf | join -> creates a
string from an array | reverse->
reverses an array | slice-> copies a
portion of array | splice->
removes/replaces elements | sort->
sorts an array
// Push- elements get added at the last index
let movieLine = ['alan', 'rick'];
movieLine.push('oliver');
// we can also add more than two elements at a same time using the
Push() method.
movieLine.push('james', 'hagrid', 'harry');

// Pop- removes an element from the last index


// movieLine.pop(); it does not require any argument. it just removes
the element present in the last index.

// if we want to store the popped element we can do it by defining a


variable for it
// let popElement = movieLine.pop();

// Shift- removes an element from the starting index


// movieLine.shift();
// if we want to store the popped element we can do it by defining a
variable for it
// let shiftElem = movieLine.shift();

// unshift-adds an element at the staring index.


// movieLine.unshift('ron', 'hermione', 'dumbeldore')

//concat method-merging two arrays to form a new array


// let age = [11, 22, 33, 44, 55]
//let newArray = age.concat(movieLine);

//includes method-> looks for a value. it returns either true or false


//let check = movieLine.includes('harry');

//indexOf method-> just like string.indexOf if element not found then


it returns -1
//let present = movieLine.indexOf('harry');

//reverse method-> reverses an array


// let reverseArray = movieLine.reverse();

// slice methods-> gets a potion of array. it takes a starting and


ending index as arguments.
let colors = ['red', 'blue', 'green', 'purple', 'magenta', 'cyan',
'indigo'];
// let coolColors = colors.slice(4);it will return magenta cyan and
Indigo
// if we dont provide the staring and the ending index then it will
create a copy of the array;
let duplicateArray = colors.slice();

// when the arguments are passed then then the slice method will start
from starting index and will stop at [endindex-1]
let warmColors = colors.slice(2, 4); // will return elements present at
index 2 and 3.

// we can also use negative index


let demoColors = colors.slice(-5);

//splice-> removes/replaces elements . it takes three arguments one is


the index where you want to insert or delete , the second argument is
about the no. of elements you want to delete from that posn onwards and
third is the element that you want to replace or insert.

// we can add an element like this


let months = ['jan', 'feb', 'April', 'may', 'June'];
months.splice(2, 0, 'march');

// now we can delete a particular element using the splice method.


months.splice(5, 1); // June will be deleted.

// we can also insert multiple elements in a array after a particular


index
months.splice(5, 0, 'June', 'July', 'aug', 'sept');

//reference type and equality test.


// when we are comparing two different arrays having same elements with
=== equality or == equality it returns false becoz JavaScript does not
see the elements rather the memory location;
let nums = [11, 22, 33];
// let numCopy=[11,22,33];
// if we check for nums==numCopy or nums===numCopy it will return false
becoz both are having same memory reference.

// if we declare numCopy as below it wont return false.


let numCopy = nums;
// now any operations of nums also changes the state of numCopy. as
both are having same memory allocation.

// multi-dimensional array
let ar = [[1, 2, 3, 4], [5, 6, 7, 8], ['a', 'b']];

//introductions to
objects
// 1)objects are collections of properties
// 2)Properties are a key value pair
// 3)rather than accessing data using an index we use custom key

// creating a object
const personData = {
firstName: 'Biswajeet',
lastName: 'Mohapatra',
age: 19,
2002: 'birthYear',
countryOfOrigin: 'india',
skills: ['java', 'python', 'html', 'javaScript', 'css', 'MySql']
}
// there are two methods for accessing the value of an Object
// 1) by using square bracket with inverted quotes;
let userName1 = personData["firstName"];
// 2) by using dot operator;
let userName2 = personData.firstName;

// using square bracket we can access in dynamically;


// let userYear = prompt("Enter a year: ");
if (personData[userYear] === personData[2002]) {
alert("its " + personData.firstName + " birth year");
}
else {
alert("year entered not present in object personData")
}

// modifying data present in an object


// 1)using the .operator
personData.age = 18;
// 2) using square bracket
personData.countryOfOrigin = 'Bhubaneswar , odisha , india';

// we can also add new properties to the object by


//1) using .operator
personData.middleName = null;
//2) using square bracket
personData['Branch'] = 'Computer Science Engg';

// Nesting arrays and objects


// objects inside an array
const comments = [
{
//comment 1
username: 'tammy',
text: 'lololo',
votes: 9
},
{
//comment 2
username: "fishboi",
text: 'glub glub glun',
votes: 12
}
]
// we can acess the object present inside the array like the following
const commentUser2 = comments[1].username;
// or we can try using square bracket
const commentUser1 = comments[0]['username'];
loops in JavaScript
//1. for loop 2)while loop
3)for ... of loop
4)for ... in loop
1) for loop
//syntax
// for([initialExpression];
// [condition];
// [incrementExpression]
// )
// for (let i = 1; i <= 10; i++) {
// console.log(i); //-> will print all 10 digits
// }

// let j = 1;
// while (j <= 10) {
// console.log(j);
// j++;
// }

//infinite loops
// do not try this code:
// for(let i=1;i>0;i++){
// console.log(i);
// }

// looping over arrays;


// const animals = ['lion', 'tiger', 'leopard', 'cheetah'];
// for (let i = 0; i < animals.length; i++) {
// console.log(i, animals[i]);
// }

// nesting for loops


// for (let i = 1; i <= 3; i++) {
// console.log(`i is: ${i}`);
// for (let j = 1; j <= 5; j++) {
// console.log(` j is: ${j}`);
// }
// }
const comments = [
{
//comment 1
username: 'tammy',
text: 'lololo',
votes: 9,
userData: [
{
age: 19,
country: 'India'
}
]
},
{
//comment 2
username: "fishboi",
text: 'glub glub glun',
votes: 12,
userData: [
{
age: 18,
country: 'India'
}
]
}
]
//iterating over this array containing objects
for (let i = 0; i < comments.length; i++) {
let showUser = comments[i].userData;
//console.log(showUser);
for (let j = 0; j < showUser.length; j++) {
if (showUser[j].age > 18) {
console.log(showUser);
}
else {
console.log(showUser, `does not have age greater than
${18}`)
}
}
}

2) while loop
syntax
initialExpression
while(initialExpression<=condition){
condition;
incrementExpression;
}

let j = 1;
while (j <= 10) {
console.log(j);
j++;
}

if it is unknown to us that upto where the loop must run then at that
time only we should use while loop. orelse it is better to use the for
loop

suppose you want to validate or set a password with a otp or secret key
then at that time we should use while loop

const SecretKey = '839471';


let UserPassword = 'log123bm';
let AskClient = prompt('Enter your secret key: ');
while (SecretKey !== AskClient) {
AskClient = prompt('Enter your secret key: ');
}
const NewPwd = prompt("Enter new password: ");
UserPassword = NewPwd;
alert("password sucessfully Changed!!")

the Break keyword-> whenever our condition is satisfied and we want to


move out of the loop then for that we use break keyword.

let us create a program that repeats anything we say until we say to


stop
let input = prompt("Say something: ");
while (true) {
input = prompt(input);
if (input.toLowerCase() === 'stop') {
break;
}
}
alert('alright you win!!');

Number Guessing Game using


JavaScript
alert("you can type 'q' or 'Q' to quit the game inbetween ");
const maxValue = prompt("Enter the Maximum Value");
let count = 0;
let CompGuess = Math.floor(Math.random() * maxValue) + 1;
while (true) {
let userInput = prompt(`Enter a value between 1 and ${maxValue}`);
//userInput = parseInt(userInput); //changing from str to int
if (parseInt(userInput) > maxValue) {
alert("invalid input. Number entered greater than max value");
break;
}
else if (userInput.toLowerCase() === 'q') {
alert("Game stopped!! you choose to exit");
break;
}
else {
if (parseInt(userInput) < CompGuess) {
alert("guess too low!!");
count++;
}
else if (parseInt(userInput) > CompGuess) {
alert("guess too high");
count++;
}
else if (parseInt(userInput) === CompGuess) {
alert(`you got it right it took you ${count} times`);
break;
}
}
}

3)for...of loop
syntax
for(variable of iterable){
statement;
}
const sites = ['reddit', 'rockstar_games', 'facebook'];
for (let items of sites) {
console.log(`Visit the site ${items} at https//:${items}.com/`)
}
it is better to use on the nested arrays to make the readability of the
code better

accessing each student from a class (nested array)


const ClassRoom = [
['ram', 'shyam', 'gyan'],
['raghu', 'ulasit', 'raman'],
['bisu', 'namita', 'raj']
]
for (let row of ClassRoom) {
for (let student of row) {
console.log(student);
}
}
// we cannot iterate of over a object using for...of loop
// but we can use the for..in loop to iterate over the objects

4)for in loop
const scores = {
ram: 90,
shyam: 80,
deep: 89,
raja: 39,
hari: 74
}
for (let student in scores) {
console.log(`${student} scored ${scores[student]} in Maths`);
}

// wap to find the days according given input.store the days in an


object and access it using the for..in loop

function returnDay(num) {
const days = {
1: 'Monday',
2: 'Tuesday',
3: "Wednesday",
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'
}
if (num >= 1 && num <= 7) {
for (let key in days) {
if (parseInt(key) === num) {
return days[key];
}
}
}

else {
return null;
}
}
let res = returnDay(3);
console.log(res);

// this can also be done using the Object keyword


//1)Object.keys(scores) --> returns array of all the properties which
here are the names
let a = Object.keys(scores);

//2)Object.values(scores) --> returns the array of all the properties


values
let b = Object.values(scores);
//3)Object.entries(score) --> returns a nested array of each properties
with corresponding values
let c = Object.entries(scores);

Todo List using JavaScript


const todoList = [];
// let userInput = prompt("what do you want to Do: ");
while (true) {
let userInput = prompt("what do you want to Do: ");
if (userInput.toLowerCase() === "new") {
let UserTask = prompt("Enter a todo: ");
todoList.push(UserTask);
alert('Task added sucessfully!!');
}
else if (userInput.toLowerCase() === "list") {
for (let i = 0; i < todoList.length; i++) {
console.log(`${i}:${todoList[i]}`)
}
}
else if (userInput.toLowerCase() === "delete") {
const ItemIndex = prompt("Enter the index of the item: ");
let popedItem = todoList.splice(ItemIndex, 1);
console.log(`${popedItem} deleted sucessfully!!`);
alert("item deleted sucessfully!!");
}
else if (userInput.toLowerCase() === "quit") {
console.log("session ended!!");
break;
}
else {
alert("select a valid input")
}
}

functions in
JavaScript
functions allow us to write reusable , modular code. we define a chunk
of code that we can then executes at a later point. function are
recommended to be used all the time.

step 1--> defining a function using function keyword


function functionName(parameter){
do something;
}
function greet() {
console.log("hello user!!");
}
arguments // these are the inputs that are passed during the function
call to the function header. so that the function can do the work
dynamically

function GreetUser(firstName) { // here firstName is the parameter


alert(`Hi, ${firstName}!`);
}
const person = prompt("Enter your name: ");
GreetUser(person); // here person is the argument

functions with multiple arguments.


let us create a functions that accepts two arguments and finds the
greatest number between them;

function GreatestNumber(num1, num2) {


if (parseInt(num1) > parseInt(num2)) {
alert(`${num1} is greater.`);
}
else if (parseInt(num1) < parseInt(num2)) {
alert(`${num2} is greater.`);
}
else {
alert(`Both numbers are equal!!`);
}
}
const num1 = prompt("Enter first Number: ");
const num2 = prompt("Enter second Number: ");
GreatestNumber(num1, num2);

return keyword
return is used to send the data back to the function call. any code
written after the return is unreachable.

function Add(num1, num2) {


let sum = (parseInt(num1) + parseInt(num2));
return sum;
}
const num1 = prompt("Enter first Number: ");
const num2 = prompt("Enter second Number: ");
let result = Add(num1, num2);
alert(`the sum of ${num1} and ${num2} = ${result}`);

function scope
// scope--->(variable visibility) the location where a variable is
defined dictates where we have access to that variable.

let bird = 'parrot';


function birdWatch() {
let bird = 'sparrow'; // here in this case we are accessing the
bird variable outside the function block.
// still then it is showing parrot in console as we are using the
global variable bird
}
birdWatch();
console.log(bird);

let bird = 'parrot';


function birdWatch() {
bird = 'sparrow'; // here in this case we are accessing the bird
variable outside the function block.
// but this time it will be showing the updated value of the bird
or the value of bird inside the function. this is happening because the
global variable can be accessed inside the function and any changed
made to it will reflect even outside the function.
}
birdWatch();
console.log(bird);

block scope
// if out variables are declared inside any kind of block then
// it is accessible only to that block
let count = 9;
if (count >= 9) {
let count = 1;
console.log(Count); //1
}
console.log(Count); //9

lexical scope
function bankRobbery() { // grand parent
const heros = ['iron man', 'Thor', 'captain America'];
function cryForHelp() { // parent
function inner() { //child
for (let hero in heros) {
console.log(`HELP ME , ${hero.toUpperCase()}`);
}
}
inner();
}
cryForHelp();
}
// in the lexical scope when we are nesting functions or blocks inside
each other then the properties of grandparent can be used in parent
function and the properties of parent can be used in child but the
reverse situation is not possible

function Expression
it is another way of expressing functions
const add = function (n1, n2) {
return n1 + n2;
}
add(3, 4);
in this way we are declaring the functions as a variables

Higher Order Function


functions that can operate i/with other functions.
they can accept other functions as arguments and return a function
1) passing functions as
arguments
function greet() {
console.log("hello");
}
function callFunction(func) {
func();
func();
}
callFunction(greet); // hello will be printed twice

create a function callTenTimes() which takes a rollDie() function as


argument and return a value.

function rollDie() {
let outCome = Math.floor(Math.random() * 6) + 1;
console.log(outCome);
}
function callTenTimes(func) {
for (let i = 0; i < 10; i++) {
func();
}
}
callTenTimes(rollDie);

2) returning a function
function callRandom() {
const randomNum = Math.random();
if (randomNum > 0.5) {
return function () {
console.log('i am a good function');
}

}
else {
return function () {
console.log('i am a bad function');
}
}
}
generating different function according to given inputs
function isAgeBetween(min, max) {
return function (age) {
if (age >= min && age <= max) {
console.log("true")
}
else {
console.log('false');
}
}
}
const child = isAgeBetween(0, 17);
const Adult = isAgeBetween(18, 59);
const Senior = isAgeBetween(60, 120);

Methods
we can add functions as properties on objects. we call them methods
const math = {
add: function (num1, num2) {
return num1 + num2;
},
subtract: function (num1, num2) {
return num1 - num2;
},
multiply: function (num1, num2) {
return num1 * num2;
},
divide: function (num1, num2) {
return num1 / num2;
}
};

there is also a shorthand


method that is recommended
to be used
const math = {
add(num1, num2) {
return num1 + num2;
},
sub(num1, num2) {
return num1 - num2;
},
mul(num1, num2) {
return num1 * num2;
},
div(num1, num2) {
return num1 / num2;
}
}

The mysterious keyword


'This'  use the ‘this’
keyword to access other
properties in the same
object
const person = {
FirstName: 'robert',
lastName: 'downey jr',
FullName() {
return `${this.FirstName} ${this.lastName}`;
}
}
person.FullName(); //robert downey jr
person.FirstName; //robert
person.lastName; //downey jr

person.FirstName = 'john';
person.FullName(); //john downey jr
// the value of ‘THIS’ depends on the invocation context of the
function it is used in.

Try / Catch block-->


sometimes due to some
breakpoints our program is
unable to run fully. it
stops at the break point.
in order to avoid that we
can use the try/catch
block
function say(msg) {
try {
console.log(msg.toUpperCase());
}
catch (e) { // storing the error type in variable e
console.log("please input a string!!");
console.log(e);
}
}
say();
console.log("reached the end!!");

array CallBack
methods(vv imp)

use the new arrow function syntax


understand and use these methods -->
foreach
map
filter
find
reduce
some
every

the forEach() method--> accepts a callback function. Calls the function


once per element in the array.it accepts a function as a argument

const numArray = [9, 8, 7, 6, 5, 4, 3, 2, 1];


numArray.forEach(function (n) {
console.log(n * n);//81,64,49,36.....
});
console.log('***********')

numArray.forEach(function (elem) {
if (elem % 2 === 0) {
console.log(elem);//8,6,4,2
}
});

const movies = [
{
Title: "Avengers Endgame",
rating: 9.5
},
{
Title: "Avengers: Age of Ultron",
rating: 8
},
{
Title: "Captain America: Civil War",
rating: 6
}
];
// suppose I want the each title of each movies having rating greater
than or equal 8
movies.forEach(function (movie) {
if (movie.rating >= 8) {
console.log(`Movie Name:${movie.Title} Rating:$
{movie.rating}/10`);
// it will return
//Movie Name:Avengers Endgame Rating:9.5/10
//Movie Name:Avengers: Age of Ultron Rating:8/10

}
});

//Maps--> Creates a new Array with the results of calling a callback on


every element in the array

// suppose we want an array that contains the cube of each Element of


numArray

const numArray = [9, 8, 7, 6, 5, 4, 3, 2, 1];


const cube = numArray.map(function (elem) {
return Math.pow(elem, 3);
});
console.log(cube); //[729, 512, 343, 216, 125, 64, 27, 8, 1]

// suppose we want to create an array of the movie titles


const titles = movies.map(function (movie) {
return movie.Title;
});
console.log(titles); //['Avengers Endgame', 'Avengers: Age of Ultron',
'Captain America: Civil War']

Arrow Functions =>


syntactically
compact alternative
to regular function
expression
const SideSquare = (x) => {
return x * x;
}

const sum = (x, y) => {


return x + y;
}

// Implicit Returns
const isEven1 = function (num) {
return num % 2 === 0;// regular function expression
}

const isEven2 = (num) => {


return num % 2 === 0;// arrow functions with parens around parem.
}

const isEven3 = num => {


return num % 2 === 0; // arrow function with no paren around parem
}

const isEven4 = num => (


num % 2 === 0 // implicit return
);

const isEven5 = num => num % 2 === 0 // one-linear implicit return

//implicit returns only work when we have only one line of code to
evaluate

//using the arrow function display the movies having rating >6

const newMovie = movies.forEach((movie) => {


if (movie.rating > 6) {
console.log(movie);

});
//using the arrow function create a new array containing the titles of
each movie
console.log('----------------------------------')
const movieTitles = movies.map((movie) => {
return movie.Title;
});

now doing the above program using implicit method


const movieTitles = movies.map((movie) => (
movie.Title
));

// using one-linear implicit method

// const movieTitles = movies.map(movie => movie.Title)

// The settimeOut(Function,delay time) and


setinterval(function ,timeInterval) method

// suppse i want to start a program after a delay of 3 sec then I for


that I can use the setTimeout() function
const startCode = setTimeout(() => {
console.log("hello World!!")
}, 3000); // it takes the time in milliseconds

// suppse i want run the porgram again and again after n seconds then
for that I can use the setInterval() function

const randomLoop = setInterval(() => {


console.log(Math.floor(Math.random() * 5) + 1);
}, 3000);
// now in order to stop the interval we can use the
clearInterval(variable) function that takes the setInterval stored
variable as argument
clearInterval(randomLoop);

the filter() method


=> runs through the
array and creates a
new array of
elements which pass
through the function
or condition.
//suppose I want to find all the prime numbers present in the FewNums
and store it in another array
const FewNums = [11, 22, 21, 13, 3, 2, 27];
const PrimeNums = FewNums.filter((num) => {
let c = 2;
for (let i = 2; i <= FewNums.length / 2; i++) {
if (num % i === 0) {
c++;
break
}
}
if (c === 2) {
return num;
}

}); // it will return only 11 and 13 and these two numbers will be
stored in the PrimeNums as a array elements
The every() method
(just like and
operator) => test
whether all the
elements in the
array pass the
provided
functions .it
returns a Boolean
value.
const words = ['dog', 'dig', 'log', 'bag', 'wag'];
const check = words.every((word) => {
return word.length === 3; //true
});

const check1 = words.every((word) => {


let lastLetter = word[word.length - 1];
return lastLetter === 'g'; //true
});
const check2 = words.every((word) => {
return word[0].toLowerCase() === 'd'; //false
});
The some()
method(just like or
operator) => test
whether any of the
elements in the
array pass the
provided
functions .it
returns a Boolean
value.
const check3 = words.some((word) => {
return word[0].toLowerCase() === 'd'; //true
});

reduce() method=>
executes a reducer
function on each
element of the array
resulting in single
value.
syntax===>
Array.reduce((accumulator,current Value)=>{
return accumulator+current value;
});

const ArrayNum = [11, 22, 33, 44];


const Summation = ArrayNum.reduce((total, price) => {
return total + price;
});

// we can also provide initial value to accumulator


const Summation1 = ArrayNum.reduce((total, price) => {
return total + price;
}, 100); //here 100 is the initial value of accumulator so it will
return 210

const Prices = [
{
product: 'bulb',
amount: 90
},
{
product: 'geyser',
amount: 5000
},
{
product: "washing Machine",
amount: 17000
}
];
// suppose I want to find the product with highest prices of the
objects of the array
const highest = Prices.reduce((HighestPrice, currentPrice) => {
if (currentPrice.amount > HighestPrice.amount) {
return currentPrice;
}
else {
return HighestPrice;
}
}) //{product: 'washing Machine', amount: 17000}
Newer JavaScript
Features

1// Default Params(the old


way)
// suppose we create a function rollDice() that takes the argument for
the Number of side and returns a value between 1 and that value passed
function rollDice(numSide) {
if (numSide === undefined) {
numSide = 6;
}
return Math.floor(Math.random() * numSide) + 1;
}
// if the user doesn’t provide any argument then it takes the value 6
as default

// default Param(the new


way)
function rollDice1(numSide = 6) {
return Math.floor(Math.random() * numSide) + 1;
}
// now in this case we are providing the default value for the
parameter in the function header;

// There is a rule that default param should only be given after to


the 2nd variable in an argument. like.........

//suppose I want to create a function greetUser() that accepts a name


and msg as input.
function greetUser(msg = 'hey There', name) {
console.log(`${msg} ${name}!!`);
}
greetUser('kane'); // it will show kane undefined!!, as the value is
getting accepted by the msg variable. and name does not have a default
value.

greetUser("hello", 'biswajeet'); // now in this case we will be getting


hello BISWAJEET!!, and the default msg value is getting updated.
2) spread(...) in
function Calls===>
Expands an iterable
(array,string,etc)
into a list of
argument
const nums1 = [1, 2, 3, 4];
Math.max[nums1]; // it will return NaN as the max function accepts
individual arguments as input but we are passing a array.

// now inorder to find the max of an array we can spread the elements
of the array
Math.max(...nums1); // it will return 4 as it is taking each element of
nums1 as a single argument

// we can also spread string literals


console.log(...'hello'); // will provide us (h e l l o)

// spread with array


literals==> create a new
array using an existing
array. spreads the element
from one array to another.
const ar1 = [1, 2, 3];
const ar2 = [4, 5, 6];
const ar3 = [...ar1, ...ar2];
console.log(ar3); //[1,2,3,4,5,6]
spread in object
literals==> copies
properties from one object
into another object literal
const feline = {
legs: 4,
family: 'felidae'
};
const canine = {
family: 'canine',
furry: true
};
const dog = { ...canine, isPet: true };
//{family: 'canine', furry: true, isPet: true}
const lion = { ...feline, genus: 'panthera' };
//{legs: 4, family: 'felidae', genus: 'panthera'}
const catDog = { ...canine, ...feline };
//{family: 'felidae', furry: true, legs: 4}

const loginFormData = {
username: 'mbiswajeet55@gmail.com',
Name: 'Biswajeet Mohapatra',
password: '3dhbk12'
};
const user = {
...loginFormData,
id: 2241013320,
isAdmin: false
}
console.log(user); //it will display the following data
//{username: 'mbiswajeet55@gmail.com', Name: 'Biswajeet Mohapatra',
password: '3dhbk12', id: 2241013320, isAdmin: false}

THE REST PARAMS===>


// before going to rest param we need to know about The argument
object. the argument object is available inside every function.
//it is an array like object. it has a length property but it does not
have methods like push and pop.
//it contains all the argument passed to the function.
//it is not available inside arrow function.

function sumAll() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
};
const res = sumAll(11, 22, 33); //66
console.log(res);

// as the arguments object does not behave like a array to solve that
we have the rest params(...)
//it collects all the remaining arguments into an actual array
function sumAll2(...numsArray) {
let total = 0;
for (let n of numsArray) {
total += n;
}
return total;
};
const res2 = sumAll(57, 22, 33); //66
console.log(res2); //112

// as the rest param is a real array so we can use the array methods on
it

You might also like