#1) AT() – The at() method returns an indexed element from an array.
Description:
The at() method returns the same as [].
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let fruit = fruits.at(2);
document.getElementById(“demo”).innerHTML = fruit;
Output:
Apple
#2) CONCAT()
Description:
The concat() method concatenates (joins) two or more arrays.
The concat() method returns a new array, containing the joined arrays.
The concat() method does not change the existing arrays.
Code:
const arr1 = [“Cecilie”, “Lone”];
const arr2 = [“Emil”, “Tobias”, “Linus”];
const children = arr1.concat(arr2);
document.getElementById(“demo”).innerHTML = children;
Output:
Cecilie,Lone,Emil,Tobias,Linus
#3) CONSTRUCTOR()
Description:
The constructor property returns the function that created the Array prototype.
For JavaScript arrays the constructor property returns:
function Array() { [native code] }
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let text = fruits.constructor;
document.getElementById(“demo”).innerHTML = text;
Output:
function Array() { [native code] }
#4) copyWithin()
Description:
The copyWithin() method copies array elements to another position in the array.
The copyWithin() method overwrites the existing values.
The copyWithin() method does not add items to the array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.copyWithin(2,0);
Output:
Banana,Orange,Banana,Orange
#5) ENTRIES()
Description:
The entries() method returns an Array Iterator object with key/value pairs:
[0, “Banana”]
[1, “Orange”]
[2, “Apple”]
[3, “Mango”]
The entries() method does not change the original array.
The entries() method is not supported in Internet Explorer.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
const f = fruits.entries();
for (let x of f) {
document.getElementById(“demo”).innerHTML += x + “<br>”;
}
Output:
0,Banana
1,Orange
2,Apple
3,Mango
#6) EVERY()
Description:
The every() method executes a function for each array element.
The every() method returns true if the function returns true for all elements.
The every() method returns false if the function returns false for one element.
The every() method does not execute the function for empty elements.
The every() method does not change the original array
Code:
const ages = [32, 33, 16, 40];
document.getElementById(“demo”).innerHTML = ages.every(checkAge);
function checkAge(age) {
return age > 18;
}
Output:
false
#7) FILL()
Description:
The fill() method fills specified elements in an array with a value.
The fill() method overwrites the original array.
Start and end position can be specified. If not, all elements will be filled.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.fill(“Kiwi”);
Output:
Kiwi,Kiwi,Kiwi,Kiwi
#8) FILTER()
Description:
The filter() method creates a new array filled with elements that pass a test provided by a function.
The filter() method does not execute the function for empty elements.
The filter() method does not change the original array.
Code:
const ages = [32, 33, 16, 40];
document.getElementById(“demo”).innerHTML = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
Output:
32,33,40
#9) FIND()
Description:
The find() method returns the value of the first element that passes a test.
The find() method executes a function for each array element.
The find() method returns undefined if no elements are found.
The find() method does not execute the function for empty elements.
The find() method does not change the original array.
Code:
const ages = [3, 10, 18, 20];
document.getElementById(“demo”).innerHTML = ages.find(checkAge);
function checkAge(age) {
return age > 18;
}
Output:
20
#10) findIndex()
Description:
The findIndex() method executes a function for each array element.
The findIndex() method returns the index (position) of the first element that passes a test.
The findIndex() method returns -1 if no match is found.
The findIndex() method does not execute the function for empty array elements.
The findIndex() method does not change the original array.
Code:
const ages = [3, 10, 18, 20];
document.getElementById(“demo”).innerHTML = ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Output:
3
#11) flat()
Description:
The flat() method concatenates sub-array elements.
Code:
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
document.getElementById(“demo”).innerHTML = newArr;
Output:
1,2,3,4,5,6
#12) flatMap()
Description:
The flatMap() method maps all array elements and creates a new flat array.
flatMap() creates a new array from calling a function for every array element.
flatMap() does not execute the function for empty elements.
flatMap() does not change the original array.
Code:
const myArr = [1, 2, 3, 4, 5,6];
const newArr = myArr.flatMap((x) => x * 2);
document.getElementById(“demo”).innerHTML = newArr;
Output:
2,4,6,8,10,12
#13) forEach()
Description:
The forEach() method calls a function for each element in an array.
The forEach() method is not executed for empty elements.
Code:
let text = “”;
const fruits = [“apple”, “orange”, “cherry”];
fruits.forEach(myFunction);
document.getElementById(“demo”).innerHTML = text;
function myFunction(item, index) {
text += index + “: ” + item + “<br>”;
}
Output:
0: apple
1: orange
2: cherry
#14) from()
Description:
The Array.from() method returns an array from any object with a length property.
The Array.from() method returns an array from any iterable object.
Code:
let text = “ABCDEFG”
const myArr = Array.from(text);
document.getElementById(“demo”).innerHTML = myArr;
Output:
A,B,C,D,E,F,G
#15) INCLUDES()
Description:
The includes() method returns true if an array contains a specified value.
The includes() method returns false if the value is not found.
The includes() method is case sensitive.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.includes(“Banana”, 3);
Output:
false
#16) indexOf()
Description:
The indexOf() method returns the first index (position) of a specified value.
The indexOf() method returns -1 if the value is not found.
The indexOf() method starts at a specified index and searches from left to right.
By default the search starts at the first element and ends at the last.
Negative start values counts from the last element (but still searches from left to right).
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let index = fruits.indexOf(“Apple”);
document.getElementById(“demo”).innerHTML = index;
Output:
2
#17) isArray()
Description:
The isArray() method returns true if an object is an array, otherwise false.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let result = Array.isArray(fruits);
document.getElementById(“demo”).innerHTML = result;
Output:
true
#18) join()
Description:
The join() method returns an array as a string.
The join() method does not change the original array.
Any separator can be specified. The default is comma (,).
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let text = fruits.join();
document.getElementById(“demo”).innerHTML = text;
Output:
Banana,Orange,Apple,Mango
#19) keys()
Description:
The keys() method returns an Array Iterator object with the keys of an array.
The keys() method does not change the original array.
keys() is not supported in Internet Explorer.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
const keys = fruits.keys();
let text = “”;
for (let x of keys) {
text += x + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
3
#20) lastIndexOf()
Description:
The lastIndexOf() method returns the last index (position) of a specified value.
The lastIndexOf() method returns -1 if the value is not found.
The lastIndexOf() starts at a specified index and searches from right to left.
By defalt the search starts at the last element and ends at the first.
Negative start values counts from the last element (but still searches from right to left).
Code:
const fruits = [“Apple”, “Orange”, “Apple”, “Mango”];
let index = fruits.lastIndexOf(“Apple”);
document.getElementById(“demo”).innerHTML = index;
Output:
2
#21) length()
Description:
The length property sets or returns the number of elements in an array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let length = fruits.length;
document.getElementById(“demo”).innerHTML = length;
Output:
4
#22) map()
Description:
map() creates a new array from calling a function for every array element.
map() does not execute the function for empty elements.
map() does not change the original array.
Code:
const numbers = [4, 9, 16, 25];
document.getElementById(“demo”).innerHTML = numbers.map(Math.sqrt);
Output:
2,3,4,5
#23) POP()
Description:
The pop() method removes (pops) the last element of an array.
The pop() method changes the original array.
The pop() method returns the removed element.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.pop();
document.getElementById(“demo”).innerHTML = fruits;
Output:
Banana,Orange,Apple
#24) prototype()
Description:
prototype allows you to add new properties and methods to arrays.
prototype is a property available with all JavaScript objects.
Code:
// Add a new method
Array.prototype.myUcase = function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase();
}
};
// Use the method on any array
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.myUcase();
document.getElementById(“demo”).innerHTML = fruits;
Output:
BANANA,ORANGE,APPLE,MANGO
#25) push()
Description:
The push() method adds new items to the end of an array.
The push() method changes the length of the array.
The push() method returns the new length.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.push(“Kiwi”);
document.getElementById(“demo”).innerHTML = fruits;
Output:
Banana,Orange,Apple,Mango,Kiwi
#26) reduce()
Description:
The reduce() method executes a reducer function for array element.
The reduce() method returns a single value: the function’s accumulated result.
The reduce() method does not execute the function for empty array elements.
The reduce() method does not change the original array.
Code:
const numbers = [175, 50, 25];
document.getElementById(“demo”).innerHTML = numbers.reduce(myFunc);
function myFunc(total, num) {
return total – num;
}
Output:
100
#27) reduceRight()
Description:
The reduceRight() method executes a reducer function for each array element.
The reduceRight() method works from right to left.
The reduceRight() method returns a single value: the function’s accumulated result.
The reduceRight() method does not execute the function for empty elements.
Code:
const numbers = [175, 50, 25];
document.getElementById(“demo”).innerHTML = numbers.reduceRight(myFunc);
function myFunc(total, num) {
return total – num;
}
Output:
-200
#28) reverse()
Description:
The reverse() method reverses the order of the elements in an array.
The reverse() method overwrites the original array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.reverse();
Output:
Mango,Apple,Orange,Banana
#29) shift()
Description:
The shift() method removes the first item of an array.
The shift() method changes the original array.
The shift() method returns the shifted element.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.shift();
document.getElementById(“demo”).innerHTML = fruits;
Output:
Orange,Apple,Mango
#30) slice()
Description:
The slice() method returns selected elements in an array, as a new array.
The slice() method selects from a given start, up to a (not inclusive) given end.
The slice() method does not change the original array.
Code:
const fruits = [“Banana”, “Orange”, “Lemon”, “Apple”, “Mango”];
const citrus = fruits.slice(1, 3);
document.getElementById(“demo”).innerHTML = citrus;
Output:
Orange,Lemon
#31) some()
Description:
The some() method checks if any array elements pass a test (provided as a callback function).
The some() method executes the callback function once for each array element.
The some() method returns true (and stops) if the function returns true for one of the array elements.
The some() method returns false if the function returns false for all of the array elements.
The some() method does not execute the function for empty array elements.
The some() method does not change the original array.
Code:
const ages = [3, 10, 18, 20];
document.getElementById(“demo”).innerHTML = ages.some(checkAdult);
function checkAdult(age) {
xreturn age > 18;
}
Output:
true
#32) sort()
Description:
The sort() sorts the elements of an array.
The sort() overwrites the original array.
The sort() sorts the elements as strings in alphabetical and ascending order.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits.sort();
Output:
Apple,Banana,Mango,Orange
#33) splice()
Description:
The splice() method adds and/or removes array elements.
The splice() method overwrites the original array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
// At position 2, add 2 elements:
fruits.splice(2, 0, “Lemon”, “Kiwi”);
document.getElementById(“demo”).innerHTML = fruits;
Output:
Banana,Orange,Lemon,Kiwi,Apple,Mango
#34) toString()
Description:
The toString() method returns a string with array values separated by commas.
The toString() method does not change the original array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
let text = fruits.toString();
document.getElementById(“demo”).innerHTML = text;
Output:
Banana,Orange,Apple,Mango
#35) unshift()
Description:
The unshift() method adds new elements to the beginning of an array.
The unshift() method overwrites the original array.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.unshift(“Lemon”, “Pineapple”);
document.getElementById(“demo”).innerHTML = fruits;
Output:
Lemon,Pineapple,Banana,Orange,Apple,Mango
#36) valueOf()
Description:
The valueOf() method returns the array itself.
The valueOf() method does not change the original array.
fruits.valueOf() returns the same as fruits.
Code:
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
const myArray = fruits.valueOf();
document.getElementById(“demo”).innerHTML = myArray;
Output:
Banana,Orange,Apple,Mango
JS Statement
#37) break
Description:
The break statement breaks out of a switch or a loop.
In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch.
In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).
Code:
let text = “”;
for (let i = 0; i < 5; i++) {
if (i == 3) break;
text += i + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
#38) class
Description:
A class is a type of object template.
The class statement initiates a JavaScript class.
Properties and methods are assigned in the constructor() method.
The constructor() method is called each time a class object is initialized.
Code:
class Car {
constructor(brand) {
this.carName = brand;
}
}
myCar = new Car(“Ford”);
document.getElementById(“demo”).innerHTML = “My car is a ” + myCar.carName;
Output:
My car is a Ford
#39) const
Description:
The const statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called “declaring” a variable:
const name = “Volvo”;
Code:
// Create an Array:
const cars = [“Saab”, “Volvo”, “BMW”];
// Change an element:
cars[0] = “Toyota”;
// Add an element:
cars.push(“Audi”);
// Display the Array:
document.getElementById(“demo”).innerHTML = cars;
Output:
Toyota,Volvo,BMW,Audi
#40) continue
Description:
The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop.
The difference between continue and the break statement, is instead of “jumping out” of a loop, the continue statement “jumps over” one iteration in the loop.
However, when the continue statement is executed, it behaves differently for different types of loops:
In a while loop, the condition is tested, and if it is true, the loop is executed again.
In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is tested to find out if another iteration should be done
The continue statement can also be used with an optional label reference.
Note: The continue statement (with or without a label reference) can only be used inside a loop.
Code:
let text = “”;
for (let i = 0; i < 5; i++) {
if (i === 3) continue;
text += i + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
4
#41) debugger
Description:
The debugger statement stops the execution of JavaScript, and calls the debugger.
Code:
let x = 15 * 5;
debugger;
document.getElementById(“demo”).innerHTML = x;
Output:
75
#42) do…while Loop
Description:
The do…while statements combo defines a code block to be executed once, and repeated as long as a condition is true.
The do…while is used when you want to run a code block at least one time.
Code:
let text = “”;
let i = 0;
do {
text += i + “<br>”;
i++;
}
while (i < 5);
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
3
4
#43) for Loop
Description:
The for statement defines a code block that is executed as long as a condition is true.
Code:
let text = “”;
for (let i = 0; i < 5; i++) {
text += i + “<br>”;
}
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
3
4
#44) for…in Loop
Description:
The for…in statements combo iterates (loops) over the properties of an object.
The code block inside the loop is executed once for each property.
Code:
const person = {fname:”John”, lname:”Doe”, age:25};
let text = “”;
for (let x in person) {
text += person[x] + ” “;
}
document.getElementById(“demo”).innerHTML = text;
Output:
John Doe 25
#45) for…of Loop
Description:
The for…of statements combo iterates (loops) over the values of any iterable.
The code block inside the loop is executed once for each value.
Code:
let text = “”;
const cars = [‘BMW’, ‘Volvo’, ‘Mini’];
for (let x of cars) {
text += x + ” “;
}
document.getElementById(“demo”).innerHTML = text;
Output:
BMW Volvo Mini
#46) function
Description:
The function statement declares a function.
A declared function is “saved for later use”, and will be executed later, when it is invoked (called).
In JavaScript, functions are objects, and they have both properties and methods.
A function can also be defined using an expression.
Code:
function myFunction() {
document.getElementById(“demo”).innerHTML = “Hello World!”;
}
myFunction();
Output:
Hello World!
#47) if…else
Description:
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
The if/else statement is a part of JavaScript’s “Conditional” Statements, which are used to perform different actions based on different conditions.
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to select one of many blocks of code to be executed
Code:
let hour = new Date().getHours();
if (hour < 20) {
document.getElementById(“demo”).innerHTML = “Good day”;
}
Output:
Good day
#48) let
Description:
if…elseThe let statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called “declaring” a variable:
let carName;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carName = “Volvo”;
You can also assign a value to the variable when you declare it:
let carName = “Volvo”;
Code:
let x = 5;
let y = 6;
document.getElementById(“demo”).innerHTML = x + y;
Output:
11
#49) return
Description:
The return statement stops the execution of a function and returns a value.
Code:
document.getElementById(“demo”).innerHTML = myFunction(“John”);
function myFunction(name) {
return “Hello ” + name;
}
Output:
Hello John
#50) switch Statement
Description:
The switch statement executes a block of code depending on different cases.
The switch statement is a part of JavaScript’s “Conditional” Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.
The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed.
The switch statement is often used together with a break or a default keyword (or both). These are both optional:
The break keyword breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. If break is omitted, the next code block in the switch statement is executed.
The default keyword specifies some code to run if there is no case match. There can only be one default keyword in a switch. Although this is optional, it is recommended that you use it, as it takes care of unexpected cases.
Code:
function myFunction() {
var text;
var fruits = document.getElementById(“myInput”).value;
switch(fruits) {
case “Banana”:
text = “Banana is good!”;
break;
case “Orange”:
text = “I am not a fan of orange.”;
break;
case “Apple”:
text = “How you like them apples?”;
break;
default:
text = “I have never heard of that fruit…”;
}
document.getElementById(“demo”).innerHTML = text;
}
Output:
Enter “Banana” in the input box and called the myFunction in the button.
#51) throw
Description:
The throw statement allows you to create a custom error.
The throw statement throws (generates) an error.
The technical term for this is:
The throw statement throws an exception.
The exception can be a JavaScript String, a Number, a Boolean or an Object:
throw “Too big”; // throw a text
throw 500; // throw a number
throw false; // throw a boolean
throw person; // throw an object
Code:
function myFunction() {
const message = document.getElementById(“message”);
message.innerHTML = “”;
let x = document.getElementById(“demo”).value;
try {
if(x == “”) throw “is Empty”;
if(isNaN(x)) throw “not a number”;
if(x > 10) throw “too high”;
if(x < 5) throw “too low”;
}
catch(err) {
message.innerHTML = “Input ” + err;
}
}
Output:
Enter input no and it displays a message based on that number
#52) try…catch…finally
Description:
When an error occurs, JavaScript will stop and generate an error message.
Code:
try {
adddlert(“Welcome guest!”);
}
catch(err) {
document.getElementById(“demo”).innerHTML = err.message;
}
Output:
adddlert is not defined
#53) var
Description:
The var statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called “declaring” a variable:
var carName;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carName = “Volvo”;
You can also assign a value to the variable when you declare it:
var carName = “Volvo”;
Code:
var carName = “Volvo”;
document.getElementById(“demo”).innerHTML = carName;
Output:
Volvo
#54) while Loop
Description:
The while statement creates a loop (araund a code block) that is executed while a condition is true.
The loop runs while the condition is true. Otherwise it stops.
Code:
let text = “”;
let i = 0;
while (i < 5) {
text += i + “<br>”;
i++;
}
document.getElementById(“demo”).innerHTML = text;
Output:
0
1
2
3
4
#55) endsWith()
Description:
The endsWith() method returns true if a string ends with a specified string.
Otherwise it returns false.
The endsWith() method is case sensitive.
Code:
let text = “Hello world”;
let result = text.endsWith(“world”);
document.getElementById(“demo”).innerHTML = result;
Output:
true
#56) startsWith()
Description:
The startsWith() method returns true if a string starts with a specified string.
Otherwise it returns false.
The startsWith() method is case sensitive.
Code:
let text = “Hello world, welcome to the universe.”;
let result = text.startsWith(“Hello”);
document.getElementById(“demo”).innerHTML = result;
Output:
true
#57) substr()
Description:
The substr() method extracts a part of a string.
The substr() method begins at a specified position, and returns a specified number of characters.
The substr() method does not change the original string.
To extract characters from the end of the string, use a negative start position.
Code:
let text = “Hello world!”;
let result = text.substr(1, 4);
document.getElementById(“demo”).innerHTML = result;
Output:
ello
#58) trim()
Description:
The trim() method removes whitespace from both sides of a string.
The trim() method does not change the original string.
Code:
let text = ” Hello World! “;
let result = text.trim();
document.getElementById(“demo1”).innerHTML = text;
document.getElementById(“demo2”).innerHTML = result;
Output:
Hello World!
Hello World!
#59) Call()
Description:
The call() method calls the function directly and sets this to the first argument passed to the call method and if any other sequences of arguments preceding the first argument are passed to the call method then they are passed as an argument to the function.
Syntax:
call(objectInstance)
call(objectInstance, arg1, /* …, */ argN)
Code:
let nameObj = {
name: “Tony”
}
let PrintName = {
name: “steve”,
sayHi: function (age) {
console.log(this.name + ” age is ” + age);
}
}
PrintName.sayHi.call(nameObj, 42);
Output:
Tony age is 42
#60) Apply()
Description:
The apply() method calls the function directly and sets this to the first argument passed to the apply method and if any other arguments provided as an array are passed to the call method then they are passed as an argument to the function.
Syntax:
apply(objectInstance)
apply(objectInstance, argsArray)
Code:
let nameObj = {
name: “Tony”
}
let PrintName = {
name: “steve”,
sayHi: function (…age) {
console.log(this.name + ” age is ” + age);
}
}
PrintName.sayHi.apply(nameObj, [42]);
Output:
Tony age is 42
#61) Bind()
Description:
The bind() method creates a new function and when that new function is called it set this keyword to the first argument which is passed to the bind method, and if any other sequences of arguments preceding the first argument are passed to the bind method then they are passed as an argument to the new function when the new function is called.
Syntax:
bind(thisArg)
bind(thisArg, arg1, arg2, /* …, */ argN)
Code:
let nameObj = {
name: “Tony”
}
let PrintName = {
name: “steve”,
sayHi: function () {
// Here “this” points to nameObj
console.log(this.name);
}
}
let HiFun = PrintName.sayHi.bind(nameObj);
HiFun();
Output:
Tony
#62) Rest Syntax
Description:
The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
Code:
function sum(…theArgs) {
let total = 0;
for (const arg of theArgs) {
total += arg;
}
return total;
}
console.log(sum(1, 2, 3));
// Expected output: 6
console.log(sum(1, 2, 3, 4));
// Expected output: 10
Output:
6
10
#63) Spread Syntax
Description:
The spread (…) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
Spread syntax looks exactly like rest syntax. In a way, spread syntax is the opposite of rest syntax. Spread syntax “expands” an array into its elements, while rest syntax collects multiple elements and “condenses” them into a single element.
Code:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(…numbers));
// Expected output: 6
console.log(sum.apply(null, numbers));
// Expected output: 6
Output:
6
6
#64) Object Destructuring
Description:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Code:
let { property1: variable1, property2: variable2 } = object;
let person = {
firstName: ‘John’,
lastName: ‘Doe’,
currentAge: 28
};
let { firstName, lastName, middleName = ”, currentAge: age = 18 } = person;
console.log(middleName); // ”
console.log(age); // 28
Output:
‘’
28
#65) Array Destructuring
Description:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Code:
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// Expected output: 10
console.log(b);
// Expected output: 20
[a, b, …rest] = [10, 20, 30, 40, 50];
console.log(rest);
// Expected output: Array [30, 40, 50]
Output:
> 10
> 20
> Array [30, 40, 50]
#66) Callback function
Description:
A callback is a function passed as an argument to another function
This technique allows a function to call another function
A callback function can run after another function has finished
Code:
function myDisplayer(some) {
document.getElementById(“demo”).innerHTML = some;
}
function myFirst() {
myDisplayer(“Hello”);
}
function mySecond() {
myDisplayer(“Goodbye”);
}
myFirst();
mySecond();
Output:
Goodbye
#67) Async
Description:
Async: It simply allows us to write promises-based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event loop. Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then JavaScript automatically wraps it in a promise which is resolved with its value.
Code:
const getData = async() => {
let data = “Hello World”;
return data;
}
getData().then(data => console.log(data));
Output:
Hello World
#68) await
Description:
Await: Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.
Code:
const getData = async() => {
let y = await “Hello World”;
console.log(y);
}
console.log(1);
getData();
console.log(2);
Output:
12Hello World
#69) async await
Description:
See above
Code:
function asynchronous_operational_method() {
let first_promise = new Promise((resolve, reject) => resolve(“Hello”));
let second_promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(” GeeksforGeeks..”);
}, 1000);
});
let combined_promise = Promise.all([first_promise, second_promise]);
return combined_promise;
}
async function display() {
let data = await asynchronous_operational_method();
console.log(data);
}
display();
Output:
[ ‘Hello’, ‘ GeeksforGeeks..’ ]
#70) Promises
Description:
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
Code:
let myPromise = new Promise(function(myResolve, myReject) {
// “Producing Code” (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// “Consuming Code” (Must wait for a fulfilled Promise)
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Output:
N/A