Understanding all JavaScript methods in Object,Class, Function and Array
Complete guide to JavaScript methods I
Table of contents
- Object method
- Adding a method to an object
- Accessing method
- Class method
- JavaScript in-built method
- Major method :
- toLocalString() :
- toString() :
- keys() :
- values() :
- valueOf() :
- entries() :
- length :
- Object method
- Object.create() :
- Object.assign() :
- Object.defineProperties() :
- Object.defineProperty() :
- Object.getOwnPropertyDescriptors() :
- Object.getOwnPropertyDescriptor() :
- Object.propertyIsEnumerable() : ***
- Object.getOwnPropertyNames() : ***
- Object.getOwnPropertySymbols() :
- Object.hasOwnProperty() :
- Object.getPrototypeOf() :
- Object.setPrototypeOf() :
- Object.fromEntries() :
- Object.preventExtensions() :
- Object.seal() :
- Object.freeze() :
- Object.is() :
- Function method :
- Function.call() :
- Function.apply() : ***
- Passing many arguments :
- For function borrowing : ***
- More view on function borrowing with html ***
- With built in function like Math.max() :
- To append an array to one another :
- Use of chain constructor with apply() : *** { has relationship to thisArgument in forEach() }
- Similarities between call() and apply() :
- More view on apply() with html ***
- For comparison in tech like git vs github ***
- More view on this and apply()***
- Function.bind() :
- Array method :
- Array.from() :
- Create new array from nodelist :
- How to clone (have a copy) an array :
- Array.fromAsync() :
- Array.forEach() :
- Array.isArray() :
JavaScript Method is a property/tool of an object, that performs a certain function or task.
Over the years ,these methods had been use to executes various functionalities like drop down, slide over, scroll all over, list items, e.t.c which helps to accomplish real time robotics projects with the trajectories to solve world problems.
The goal of this article, is to simplify the use and application of JavaScript methods in Object, Class, Fuction and Array. Then take us to the nitty-gritty understanding of how methods in JavaScript works and its functionalities.
It also include key highlight, reference and important site for furthermore complex understanding of JavaScript methods.
Object method
It's a function property in an object scope.
// object containing major types of method
const person = {
name: 'John',
greet: function() {
let reply = 'Good morning ' + this.name
console.log(reply);
},
//short syntax
greetBack() {
return "How are you " + this.name + " ?"
},
//Compose Method
["reply" + 2]() {
console.log('I am fine ' + this.name)
},
//Async Method
kate: async function() {
console.log(this.name + ', Boss want to see you');
},
async boss() {
let reply = 'Have your seat, ' + this.name
await console.log(reply);
},
//Generator Method
increment: function* () {
let index = 5;
while (true) {
yield console.log(index++);
}
},
async *decrement () {
yield console.log(4);
},
};
person.greet(); //Good morning John
console.log(person.greetBack()); //How are you John ?
person.reply2(); // I am fine John
person.kate(); //John, Boss want to see you
person.boss(); //Have your seat, John
person.increment().next(); //5
person.decrement().next(); //4
Adding a method to an object
#1
var a = new objectName();
a.methodName = function(){}
#2
var a = new objectName();
a.prototype.methodName = function(){}
#3
function objectName() {
this.methodName = function(){}
}
var a = new objectName();
#4
function objectName() {}
objectName.prototype.methodName = function(){}
var a = new objectoName();
#5
var a = {
method: function(){}
}
Accessing method
This is a means of getting the method name from the object name.
objectName.methodName()
const client = {
name: 'Jane Doe',
greet() {
return `Good morning Mrs ${client.name}`;
}
}
//Accessing Property
client.name; //Jane Doe
//Accessing Method
client.greet(); //Good morning Mrs Jane Doe
Class method
class Greeting {
msg = "Good morning friend's";
//Method
morningGreet() {
return this.msg;
}
}
class Person extends Greeting {
speak() {
return super.morningGreet();
}
}
//instance of class
const john = new Person();
console.log(john.speak());
class Person {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
//Static Method
static createAnonymous(gender) {
let name = gender == "female" ? "Jane Doe" : "John Doe";
let req = new Person(name);
return console.log(req);
}
//Private Method
#occupation = "UI/UX";
#biodata;
#status() {
let req = "She is an elegant " + this.#occupation + " by profession and well mannered person."
return console.log(req)
}
//Private Static Method
static #age() {
let req = 'Jane Doe is 20 year old beautiful woman.'
return console.log(req)
}
//returning request of both private and static method with getProfile()
getProfile() {
let statusA, statusB;
//calling private and static private method in statusA and statusB
statusA = Person.#age();
statusB = this.#status();
let req = statusA + statusB;
return console.log(req);
}
}
Person.createAnonymous('female');
//calling instance of static method
let person = new Person();
person.constructor.createAnonymous('female');
person.getProfile();
person.createAnonymous('female') //Type Error
Note:
you can't call a private method into a static private method but you can call a static private method inside the private method.
If you attempt to call the static method from an instance of the class, you’ll get an error when using new.
JavaScript in-built method
There are several in-built methods in JavaScript. It includes:
Major method :
toLocalString() :
This is a built-in method used for language-sensitive formatting or a string representation of dates, numbers, times, currencies, and data structures like arrays in JavaScript.
They are used in some data types such as object
, date
, number
, array
.
general formula =>
objectName.toLocalString(locales, options);
locales :
It specifies what type of language(English, Spanish, French, etc.) format to use. There are several language tags which are primary language subtag and region subtag.
A simple example is the English (en) language tag with their various region:
Running an array of locales by arranging them from the highest to lowest priority; the runtime will use the first locale if supported, and then move down on the list of arrays.
List of language code system and primary language subtags in IANA Language Subtags Registry
options :
It's an object for customizing the functionality of the
toLocalString()
.
array.toLocalString() :
It converts arrays to locale-specific representation.
number.toLocaleString() :
It generate a locale-aware string representation of numbers like ordinary numbers in scientific and engineering notation, append units, display percentages, and format currencies.
use of currencies , unit and math
It's a means of using number for formatting currency, unit, scientific and engineering notation for countries.
the options in toLocalString()
varies with their values
List of country currencies code ( docs.google.com/spreadsheets/d/1cp3kliuJF66.. )
date.toLocaleString() :
It's a means of formatting a date and time.
Review more article on Number.toLocaleString( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat ) and Date.toLocaleString( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options )
Using Intl :
Int
is similar to toLocaleString()
, an instance of the constructor has to be created before formatting of number
and date
.
const numberFormat = new Intl.NumberFormat(locale, options);
const dateTimeFormat = new Intl.DateTimeFormat(locale, options);
toString() :
It generates a string
from a given object.
objectName.toString();
It doesn't change original content or value of the variable. The override method must take place to implement the result of the default toString()
in the custom object
.
It can also be use to detect object class example is [object date].
It is easier to use JSON.stringify()
console.log(JSON.stringify(computer));
It doesn't take parameters only optional for number
and bigInt
.
number.toString() :
It return string
of a specified number.
It has optional parameter; radix: it's an integer from range 2 to 36 that specify the base to use for representing the number value. It defaults is base 10.
let baseTen = 10;
//toString with parameter radix
let baseTwo = baseTen.toString(2);
console.log(baseTwo) //1010
It can also be converted to different number system.
bigInt.toString :
console.log((10n).toString()); //10
console.log((10n).toString(2)); //1010
In function, the toString()
method returns a string representing the source code of the specified function
.
keys() :
It's return an array
of the given property name of an object
or index (each length) of an array
.
Object.keys() :
This returns an array
of the property name or id of an object
.
This simply means a key "name" has a value "James Spear".
array.keys() :
It generates a new array
iterator object that iterates each key of an array
.
let letter = ["a", "b", "c"]
console.log(Object.keys(letter));
//OR loop the iterate key of letter
for (let key in letter){
console.log(key)
}
Review more on Array.key()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys
values() :
Its generate new array
iterator values of an object
or an array
.
Object.values() :
It's return an arrays of a value in an object
.
const person = {name: "John Smith"};
console.log(Object.values(person)); //[0: "John Smith"]
Previously to iterate values of an object for
...in
loop is use technically the Object.values()
returns it own enumerable properties while the for
...in
loop iterates properties in the prototype chain.
array.values() :
It generates a new array
iterator object that iterates each value of an array
.
with for...of loop :
break and continue statement can be use as well in the loop
if (key === "light-blue") break;
with next :
This call iterators.
let blue = ["sky-blue", "light-blue", "dark-blue"]
let value = blue.values();
console.log(value.next()); //sky-blue
console.log(value.next()); //light-blue
with sparse array :
It returns empty value in an array
as undefined
.
for (let key of [,"light-blue", "dark-blue"].values()) {
console.log(key)
}
calling values of non array :
let emojiLove = {
length:3,
0 :"❤",
1 :"💛",
2 :"💟",
}
for (let index of Array.prototype.values.call(emojiLove)) {
console.log(index); // ❤ 💛 💟
}
valueOf() :
ObjectName.valueOf();
It returns the primitive value of a specified object.
entries() :
It returns a new array
that contains the key/value pairs for each index in the array
.
Object.entries() :
This returns a new array
iterator object that contains the key/value pairs for each index in the array
.
The ID is not a string
property of the object
person, so it is not return.
converting object to map
looping through an object
Object can be iterated, using array
destructing with Object.entries()
, Object.values()
array.entries() :
It return new array
looping through an index and element. It has similar examples with array.values()
using symbol iterator
let num = [101,102,103];
let iterate = num[Symbol.iterator]();
The next()
return two result, value and done: a boolean value true or false; when true is if all the element has been iterated.
length :
It returns the number of code units in the string
or number of element available in the array
.
array.length and string.length :
Object length :
To determine the number of property in object
using keys
, values
, entries
and for...in
loop.
var details = {
Name: "Ndia",
PhoneNo: "8794561598",
age: 21
};
// Here we are getting the object length
var length = Object.keys(details).length;
console.log(length);
number length :
To determine the length of interger, float, the value will be converted to string including decimal number.
let num = 256.98;
Using math.ceil and math.log method :
The math.log
is use to find the logarithm of a number, which standard form principles is explained e.g 234 = 2.34 × 10^2 while math.ceil
round number to the next largest integer; this means the reciprocal of 2 round off into 3.
const getNumberLength = (num) => Math.ceil(Math.log10(num + 1));
Object method
Object.create() :
objectName.create(proto, propertiesObject);
This generate a new object
.
Proto: It an object prototype of the newly created object.
PropertiesObject: It describes other functionality of the proto which correspond to Object.defineProperties().
more review on creating an object ( https://www.google.com/amp/s/www.freecodecamp.org/news/a-complete-guide-to-creating-objects-in-javascript-b0e2450655e8/amp/ ) and ( https://www.google.com/amp/s/www.freecodecamp.org/news/javascript-create-object-how-to-define-objects-in-js/amp/ )
Object.assign() :
Object.assign(newTargetedObject, ...originalDeclaredObject)
It help copies all enumerable and own properties from the original declare objects to a new targeted object.
If the new target object have same key with the source object, the value of the target object replace the value of the source object.
more reviews on assign() and with polyfill object ( https://medium.com/theleanprogrammer/polyfill-object-assign-220d109b26be ), ( https://medium.com/beginners-guide-to-mobile-web-development/introduction-to-polyfills-their-usage-9cd6db4b1923 ), ( https://javascript.info/polyfills ), ( https://www.google.com/amp/s/www.geeksforgeeks.org/how-to-use-polyfill-in-javascript/amp/ )
Object.defineProperties() :
Object.defineProperties( objectName, properties)
This modifies or define a new properties to an existing object or new object.
There are two descriptor groups which are data and accessor that you use for defining your properties to either configure it value, accesibility, enumerability and immutability and both descriptor can't be use at the same time.
writable: this is able to create an immutable object. If not rewritable, set as false.
configurable: it help with the ability to delete an object and to change the property descriptor. If not to be deleted, set as false.
enumerable: it determine the number of time, an object will show up. To keep it out of loop, set as false.
Review more on Object.defineProperties
Object.defineProperty() :
Object.defineProperty(objectName, propertyName, descriptor)
This defines a new property or modifies an existing property directly on an object. It's very similar to Object.defineProperties ()
Review more on Object.defineProperty() and polyfill
Object.getOwnPropertyDescriptors() :
Object.getOwnPropertyDescriptors(objectName);
It request the full information for all properties and return it descriptors of the properties of a given object
.
Cloning an object with Object.getOwnPropertyDescriptors():
The Object.getOwnPropertyDescriptors helps to prevent data loss and with it we can create deep copies of objects without depending on another utility function.
Object.getOwnPropertyDescriptor() :
Object.getOwnPropertyDescriptor(objectName, propertyName);
It generates property descriptor for a specific property of an object
. It very similar to Object.getOwnPropertyDescriptors()
and just like it perform it functionality in function
, it likewise works in class
.
Object.propertyIsEnumerable() : ***
Object.propertyIsEnumerable(propertyName);
It determine the data element of an object is enumerable/exiting or not.
Review on Object.propertyIsEnumerable()
Object.getOwnPropertyNames() : ***
Object.getOwnPropertyNames(objectName);
It return an array of all properties of an object.
When symbol is use as property name, it doesn't return the property in Object.keys()
and Object.hasOwnPropertyNames()
but instead use Object.getOwnPropertySymbols()
.
const animal = { [Symbol('dove')]: '🕊', eagle: '🦅',}
Object.getOwnPropertySymbols() :
Object.getOwnPropertySymbols(objectName);
It return an array of all symbol properties of an object.
const number = { x: 80 };
const addSign = Symbol();
const minusSign = Symbol.for("minus")
number[addSign] = "➕️";
number[minusSign] = "➖"
console.log(number[minusSign]);
let getSign = Object.getOwnPropertySymbols(number);
console.log(getSign.length);
Object.hasOwnProperty() :
Object.hasOwnProperty(propertyName);
It determine a specific property of an object in order to check if the property is stored correctly.
Review more on Object.hasOwnProperty() ***
Object.getPrototypeOf() :
Object.getPrototypeOf(objectName);
It generates the prototype of the specified object. It will return null if there are no inherited properties. JavaScript is a language that uses prototypes very widely to share methods and properties of objects.
Object.setPrototypeOf() :
Object.setPrototypeOf(objectName, propertyName);
It return the prototype of one object to another or null
Test on setPrototypeOf( https://dev.to/coderslang/javascript-interview-question-47-how-object-setprototypeof-works-in-js-564j )
Object.fromEntries() :
Object.fromEntries(iterable);
It transform an iterables such as Array
and Map
to a key and value paired together as an object.
switch URL parameter string into an object:
This convert a query string of a URL to an object by changing each property to parameter.
The reverse of Object.fromEntries() are object.entries() and array manipulation method.
Review more on Object.fromEntries and ( https://medium.com/javascript-everyday/mapping-object-properties-with-the-fromentries-method-bba5f04c1b42 )
Object.preventExtensions() :
Object.preventExtensions(objectName);
It prevents the addition of new properties from ever being added to an object but can update and delete existing properties.
Object.seal() :
Object.seal(objectName);
It prevent adding, removing and reconfiguring of property in a specified object but can still update the value of existing properties.
Object.freeze() :
Object.freeze(objectName);
This prevent change in an object
; it doesn't allow new property to be added and existing property can't be removed.
Review more on Object.freeze()
Object.is() :
Object.is(valueOne, valueTwo);
It determines and check if two value are the same. It is not equivalent to ==
or ===
Object.isPrototypeOf() :
firstObject.isPrototypeOf(secondObject);
It determines whether an object exists in another object's prototype chain.
Object.isExtensible()
Object.isExtensible(objectName);
It determines whether an object is extensible(able to add new property to the object) or non-extensible(not able to add new property to the object).
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true
// preventExtensions, seal and freeze object are made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false
Object.isSealed() :
Object.isSealed(objectName);
It determines whether an object is sealed or not.
Object.isFrozen() :
Object.isFrozen(objectName);
It checks whether an object is frozen or not.
Function method :
Function.call() :
functionName.call(thisObject, argumentOne,...,argumentN);
This provide an information or value of a function called with the use of this
and many other argument
can also be called.
function Car(type, fuelType) {
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand) {
Car.call(this, "convertible", "petrol");
this.brand = brand;
console.log(`Car details = `, this);
}
function definePrice(price) {
Car.call(this, "convertible", "diesel");
this.price = price;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);
console.log(newBrand)
console.log(newCarPrice)
Argument can be passed along with the call :
const person = {
name: 'Jason Momoa',
};
function greeting(greetingMessage) {
return `${greetingMessage} ${this.name}`;
}
greeting.call(person, 'Hello'); // returns "Hello Jason Momoa!"
Returning the value in an object to a function.call :
For function borrowing :
This is simply the passing of the value of an object to another object.
To call an anonymous function :
let performance = [
{ actor: 'Toronto', portrayed: 'Hero' },
{ actor: 'Dante', portrayed: 'Villain' }
];
for (var i = 0; i < performance.length; i++) {
(function(i) {
this.display = function() {
console.log(this.actor +' is '+ this.portrayed);
}
this.display();
}).call(performance[i], i);
}
Using globalThis in non-strict mode :
Without the use of thisObject
, then any global object is replace with it.
globalThis.age = 36;
const Kent = () => `I'm ${this.age} year old.`
console.log(Kent.call());
Transforming method to utility function :
this
is use as normal function not as to access value in a function. It is similar to map(array, other)
const cut = Array.prototype.slice;
console.log(cut.call('yam'));
//[0:y, 1:a, 2:m]
// Same as "cut" in the previous example but this is best step
const unboundSlice = Array.prototype.slice;
const slice = Function.prototype.call.bind(unboundSlice);
console.log(slice('plantain'));
More view on function method ***
Steps to override function.call()
Function.apply() : ***
functionName.apply(thisObject, [argumentOne,...,argumentN]);
It is similar to call(), which return this and arguments that is provided as an array.
Passing many arguments :
Since the arguments are arrayLike, you can use rest parameter and spread syntax parameter to perform such function.
For function borrowing : ***
function sum(a, b) {
return a + b;
}
var numbers = [50, 100];
// Using apply to call sum with 'numbers' array as arguments
var result = sum.apply(null, numbers);
console.log(result);
const computer = {
name: 'hp',
isOn: false,
turnOn() {
this.isOn = true;
return `The ${this.name} is On`;
},
turnOff() {
this.isOn = false;
return `The ${this.name} is Off`;
}
};
const server = {
name: 'CentOS (linux server)',
isOn: false
};
let result = computer.turnOn.apply(server);
console.log(result);
More view on function borrowing with html ***
With built in function like Math.max() :
In order to accommodate chunk of value an array, since js engine has limit of data that can be stored with arguments limit of 65536, this step can be implemented:
To append an array to one another :
let rainbowColour = ['red', 'blue', 'yellow']
let colour = ['orange', 'green', 'indigo', 'violet']
rainbowColour.push.apply(rainbowColour, colour)
/*
//using spread syntax as well
rainbowColour.push(...colour)
*/
console.log(rainbowColour)
//['red', 'blue', 'yellow', 'orange', 'green', 'indigo', 'violet']
Use of chain constructor with apply() : *** { has relationship to thisArgument in forEach() }
Function.prototype.construct = function (Arguments) {
//create a new data type
var newObject = Object.create(this.prototype);
//To append both newObject and Arguments into the function
this.apply(newObject, Arguments);
//when it done append return result
return newObject;
};
//OR
//also important when using closure
Function.prototype.construct = function(Arguments) {
var fConstructor = this, fNewConstr = function() {
fConstructor.apply(this, Arguments);
};
fNewConstr.prototype = fConstructor.prototype;
return new fNewConstr();
};
//simple step to use chain constructor
function MyConstructor() {
for (var nthProperty = 0; nthProperty < arguments.length; nthProperty++) {
//define the value "property" with index of the myArray use
this['property' + nthProperty] = arguments[nthProperty];
}
}
var myArray = [4, 'Hello world!', false];
var myInstance = MyConstructor.construct(myArray);
console.log(myInstance.property0);
//4
console.log(myInstance.property1);
//'Hello world!'
console.log(myInstance instanceof MyConstructor);
//'true'
console.log(myInstance.constructor);
//'MyConstructor'
Similarities between call() and apply() :
function sayHello(greet, message) {
console.log(`${greet} ${this.name} ! ${message}`);
}
const person = {
name: "Judith",
};
sayHello.call(person, "Hi", "Good Morning");
// Hello Judith ! Good Morning
sayHello.apply(person, ["Hi", "Good Morning"]);
// Hello Judith ! Good Morning
More view on apply() with html ***
For comparison in tech like git vs github ***
More view on this and apply()***
Function.bind() :
functionName.bind(thisArgument, [argumentOne], [argumentTwo],[ ...])
It help create a new function from an existing function and binds it with object. This method is used to borrow method from a function without copying it(this is the best step of use method from function for another function because the method still remain in that particular function) and can as well invoke that function anytime.
Use bind with setTimeout() :
let user = {
name: 'John Dophine',
getName: function() {
console.log(this.name);
}
};
setTimeout(user.getName, 1000); //this won't work
//with anonymous function
setTimeout(function () {
user.getName();
}, 1000);
//with bind
let data = user.getName.bind(user);
setTimeout(data, 1000);
//with class constructor
class client {
constructor() {
this.name = 'John Dophine';
}
out() {
setTimeout(this.getName.bind(this), 1000);
/*
//using arrow function
setTimeout(() => this.getName(), 1000);
*/
}
getName() {
console.log(this.name);
}
};
let reload = new client();
reload.out();
Using class with bind() :
A bound function doesn't have prototype, that means it can't be use for extending classes but it preserves most of the class semantics or prototype chain, the issues is that of the static properties isn't but one can still access it due to it inheritance from the parent class.
class Juice {
constructor(...args) {
console.log(new.target === Juice);
console.log(args);
}
}
const fruitJuice = Juice.bind(null, 'milk', 'banana');
new fruitJuice('pineapple', 'orange'); // true, ['milk', 'banana', 'pineapple', 'orange']
console.log(new Juice() instanceof fruitJuice); //true
//when using extend with static properties
class Person {
static fullName = "Justin Bieber";
}
class User extends Person {
static username = "JB";
}
const userBound = User.bind(null);
console.log(userBound.fullName); // "Justin Bieber"
console.log(userBound.username); // undefined
console.log(new userBound() instanceof User); // true
Use of chain constructor with bind() :
Bound function can easily be use by new
, new.target
, instanceof
, this
but not longer in use for class extend
.
function Dress(name, colour) {
this.name = name;
this.colour = colour;
}
//function with method
Dress.prototype.toString = function () {
return console.log(`${this.name},${this.colour}`);
};
//using new for function dress()
const cloth = new Dress("sundress", "red & white");
cloth.toString();
// '"sundress', "red & white"
//using bind with function dress()
// The thisArgument value doesn't matter because it's ignored
const dressBind = Dress.bind(null, "ball gown" /*x*/);
//using new with dressBind
const newDress = new dressBind("blue");
newDress.toString();
// 'ball gown', "blue"
//to check their comparison
console.log(newDress instanceof Dress);
// true
console.log(newDress instanceof dressBind);
// true
console.log(new dressBind("mermaid", "white") instanceof Dress);
// true
//binding function dress() to an empty object
const newDresss = {};
const dresss = Dress.bind(newDresss, "slip"/*x*/);
// Can still be called as a normal function
// (although usually this is undesirable)
dresss("orange");
// The modifications to `this` is now observable from the outside
console.log(newDresss);
//"slip","orange"
If you want the bound function to be callable with or without new
, then the target function should have restriction; example new.target !== undefined
or using a class
instead.
More view on bind() explaining reference and clear more explanation
Review deep dive into bind() :
https://javascript.plainenglish.io/javascript-map-and-bind-methods-to-the-rescue-696c37d428b4
Array method :
Array.from() :
Array.from(arrayLike, mapFunction, thisArgument);
This generate new array instance from an array-like(string
) or iterable object.
arrayLike :
An array-like or iterable object to convert to an array.
Optional:
mapFunction :
It help to call on every element of the array.
thisArgument :
It is a value to be use as this when running mapFunction.
- Element & Index
Initializing a value into an array and sequence generator :
More on range using Array.from()
Create new array from nodelist :
A nodeList is an array-like object that contains a collection of DOM elements.
For to use map()
, slice()
, and filter()
on nodeList, it need to be converted to an array
first. These conversion can be done using Array.from(nodeListName);
, spread operator [...array]
, Array.prototype.slice.call(nodeListName);
// Create an array based on a property of DOM Elements
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));
It then can be iterated using Array.forEach()
method which is the easiest way.
when using map:
const element = document.querySelectorAll("select option:checked");
const values = Array.prototype.map.call(element, ({ value }) => value);
How to clone (have a copy) an array :
there are several ways to clone the contents of an array. To duplicate an array using Array.from(arrayName);
, spread operator [...array]
, arrayName.slice();
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒'];
// clone `fruits` using `Array.from()`
console.log(Array.from(fruits));
Review more on deep cloning an array
https://flexiple.com/javascript/fill-javascript-array/
Array.concat()
can be use to merge an array into an empty array, which seems like cloning an array.
const fruits = ['🍑', '🍓', '🍉', '🍇', '🍒'];
// merge `fruits` with emtpy array to
// create a new array
const moreFruits = [].concat(fruits);
console.log(moreFruits);
To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use Object.keys()
, Object.values()
, Object.entries()
. To convert an async iterable to an array, use Array.fromAsync()
.
Array.fromAsync() :
Array.fromAsync(arrayLike, mapFunction, thisArgument)
It generates new array from async iterable objects (like ReadableStream & AsyncGenerator) or iterable objects (map & set) or non async iterable.
ReadableStream :
It's interface of the Streams API ( it allows JavaScript to programmatically access streams of data collected from the server and broken down into small chunks of data and then process bit by bit to the developer ) that represents a readable stream of data, which is use to handle response streams of the Fetch API ( it is more powerful and used instead of XMLHttpRequest=>it interact with server and used mostly in Ajax [ it help join each one of HTML or XHTML / CSS / JavaScript / DOM / XML / XSLT / XMLHttpRequest object together.
Meanwhile X in Ajax represent XML but JSON is preferred because it is light weight JavaScript library( it is a data-interchange format and XML are used for packaging information in the Ajax model ) ] ) or a particular defined streams through Response object .
AsyncGenerators :
it is subclass of a special AsyncIterators class and it return Promise as an object.
function timeValue(time, value) {
return new Promise((resolve /*, reject*/) => {
setTimeout(() => resolve(value), time);
});
}
async function* generate() {
yield timeValue(2000, 1);
yield timeValue(100, 2);
yield timeValue(500, 3);
yield timeValue(250, 4);
yield timeValue(125, 5);
yield timeValue(50, 6);
}
let stringNumber = " "
async function finalize() {
for await (const value of generate()) {
console.log("value", value);
//for stringNumber
stringNumber = stringNumber + value
console.log(stringNumber);
}
}
finalize().catch((e) => console.error(e));
for...await...of : this is very similar Array.fromAsync() that helps loop through async and sync iterables.
async function* streamAsyncIterable(stream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) return;
yield value;
}
} finally {
reader.releaseLock();
}
}
// Fetches data from URL and calculates response size using the async generator.
async function getResponseSize(url) {
const response = await fetch(url);
// Will hold the size of the response, in bytes.
let responseSize = 0;
// The for-await-of loop. Async iterates over each portion of the response.
for await (const chunk of streamAsyncIterable(response.body)) {
// Incrementing the total response length.
responseSize += chunk.length;
}
console.log(`Response Size: ${responseSize} bytes`); // "Response Size: 1071472"
return responseSize;
}
getResponseSize("https://jsonplaceholder.typicode.com/photos");
Review more on Array.fromAsync() ***
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fromAsync
https://advancedweb.hu/how-to-use-async-functions-with-array-map-in-javascript/
https://medium.com/@antonioval/making-array-iteration-easy-when-using-async-await-6315c3225838
Array.forEach() :
Array.forEach(callbackFunction /* element. index. array. */), thisArgument);
It is execute each of the array from declared synchronous function or arrays. it's application can be based on displaying information, creating new data collections, and even confirming information.
it skip an empty element in an array (sparse arrays) but in for loop
, it return undefined. async
/await
doesn't work in forEach()
but it does in for loop.
Alternative use of array iteration with forEach()
are map()
, every()
, reduce()
, some()
.
cars = [' 🚕 ' ,' 🚙 ' ,' 🚗 ',' 🚘 ', ' 🚖 ', ' 🚔 ']
const info = (element, index, array) => {
return console.log(`The model of this ${element} with ID number of " ${index} " and list of others ${array} at Car Speed Ltd is for sales...`);
}
cars.forEach(info);
//using destructusing
const person = [
{name: 'Paul', age: 32, status: 'beloved'},
{name: 'Peter', age: 35, status: 'dearly beloved'},
{name: 'John', age: 34, status: 'my belove'}
]
person.forEach(({name, age}) => {
return console.log(`What a great man named ${name} at the ${age}.`);
});
//using class for "this"
class Unique {
constructor(items) {
this.items = items;
}
append(newItems) {
newItems.forEach(function(newItem) {
if (!this.items.includes(newItem)) {
this.items.push(newItem);
}
}, this);
}
}
const uniqueColors = new Unique(['blue']);
console.log(uniqueColors.items); // => ['blue']
uniqueColors.append(['red', 'blue']);
console.log(uniqueColors.items);
//using function for "this"
function Counter() {
this.count = 0;
let self = this;
return {
increase: function () {
self.count++;
},
current: function () {
return self.count;
},
reset: function () {
self.count = 0;
}
}
}
var counter = new Counter();
var numbers = [1, 2, 3];
var sum = 0;
numbers.forEach(function (e) {
sum += e;
this.increase();
}, counter);
console.log(sum); // 6
console.log(counter.current()); // 3
//forEach() syntax
array.forEach((element, index, array) => { /* ... */ }, thisValue)
array.forEach(function(element, index, array) { /* ... */ }, thisValue)
thisArgument :
it's an executed value in callback function.
changing from for loop to forEach() :
forEach()
is use for loop iterators like map()
, set()
. break
& continue
doesn't function in forEach()
, it throws error.
How to create a copy of an object :
There are several ways to create a copy of an object. this is just one means by using forEach()
Flatening a nested array when using forEach() :
Array.flat()
is best to use to construct a nested array into a single array.
using forEach() with non array object :
const arrayLike = {
length: 2,
0: "null",
1: 7,
2: 4,
3: 5, // ignored by forEach() since length is 3
};
Array.prototype.forEach.call(arrayLike, (value) => console.log(value));
// "null"
// 7
it's work with map()
https://codepen.io/hubspot/pen/wvpEGRL
for compatibility :
This method is a JavaScript extension to the ECMA-262 standard, which may not be present in other implementations of the standard(some browsers). It can only function, when this code is added at the top.
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
fun.call(thisp, this[i], i, this);
}
};
}
while for map()
is program this way; several method with different compatibility.
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array(len);
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this);
}
return res;
};
}
https://stackabuse.com/guide-to-javascripts-foreach-method/
https://codesweetly.com/javascript-foreach-method
https://wesbos.com/javascript/09-gettin-loopy/49-looping-and-iterating-array-foreach
Array.isArray() :
Array is actually an object
Array.isArray(checkArray);
It checked if the passed value is an array(through array literal syntax or the array constructor and return TRUE
) and doesn't check the value prototype chain, nor the array constructor join with it.
// all following example calls return true
Array.isArray([]);
Array.isArray([12345]);
Array.isArray(new Array());
Array.isArray(new Array("apple", "ball", "cup", "dog"));
Array.isArray(new Array(8080));
// Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following example calls return false
Array.isArray();
Array.isArray("[]");
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(12345);
Array.isArray("Array");
Array.isArray(true);
Array.isArray(false);
Array.isArray(new UnArray(123));
/* This is not an array, because it was not created using the array literal syntax or the Array constructor */
Array.isArray({ __proto__: Array.prototype });
Array.isArray
is preferable used over instance of
because it works in many forms.
const iframe = document.createElement("iframe");
document.body.appendChild(iframe);
const winArray = window.frames[window.frames.length - 1].Array;
const arr = new winArray(10, 20, 30);
// Correctly checking for Array
Array.isArray(arr); // true
/* The prototype of arr is winArray.prototype, which is a different object from Array.prototype */
arr instanceof Array; // false
Watch out for part2 …