Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 21, 2022 08:46 am GMT

12-ES6: New Built In Functions in Javascript

Starting from ES6, Javascript has a lot of new built in functions in Arrays, Strings, Objects, Math and Number classes. In this article, we will learn about some of them.

Before we start

Before we start, i want to clarify that there are two types of methods, static methods and instance methods. Static methods are methods that are called directly on the class, while instance methods are called on the instance of the class, which we'll refer to in this article with prototype methods.

For example Array.from is a static method, which can be called from the Array class itself, whereas Array.prototype.includes is an instance method, which can be called from the actual array itself.

Array.from()

Array.from() is a static method of the Array class. It creates a new Array instance from an array-like or iterable object.

const arrayLike = {  0: 'Hasan',  1: 'Ahmad',  2: 'Mohammad',  length: 3};const array = Array.from(arrayLike);console.log(array); // ['Hasan', 'Ahmad', 'Mohammad']

We can also pass a map function as the second argument to Array.from() to map the values of the array-like object.

const arrayLike = {  0: 'Hasan',  1: 'Ahmad',  2: 'Mohammad',  length: 3};const array = Array.from(arrayLike, name => name.toUpperCase());console.log(array); // ['HASAN', 'AHMAD', 'MOHAMMAD']

Array.keys()

Array.keys() is a method of the Array class. It returns a new Array Iterator object that contains the keys for each index in the array.

const array = ['Hasan', 'Ahmad', 'Mohammad'];const iterator = array.keys();console.log(iterator.next()); // { value: 0, done: false }console.log(iterator.next()); // { value: 1, done: false }console.log(iterator.next()); // { value: 2, done: false }console.log(iterator.next()); // { value: undefined, done: true }

You can also use for...of loop to iterate over the keys.

const array = ['Hasan', 'Ahmad', 'Mohammad'];for (const key of array.keys()) {  console.log(key); // 0, 1, 2}

Array.values()

Works exactly like Array.keys() but returns the values instead of the keys.

const array = ['Hasan', 'Ahmad', 'Mohammad'];const iterator = array.values();console.log(iterator.next()); // { value: 'Hasan', done: false }console.log(iterator.next()); // { value: 'Ahmad', done: false }console.log(iterator.next()); // { value: 'Mohammad', done: false }console.log(iterator.next()); // { value: undefined, done: true }

Of course you can use for...of loop to iterate over the values.

const array = ['Hasan', 'Ahmad', 'Mohammad'];for (const value of array.values()) {  console.log(value); // 'Hasan', 'Ahmad', 'Mohammad'}

Array.entries()

Array.entries() is a method of the Array class. It returns a new Array Iterator object that contains the key/value pairs for each index in the array.

const array = ['Hasan', 'Ahmad', 'Mohammad'];const iterator = array.entries();for (const entry of iterator) {  console.log(entry); // [0, 'Hasan'], [1, 'Ahmad'], [2, 'Mohammad']}

Actually it could be useful if you want to get the value and index at once, we can destructure the entry.

const array = ['Hasan', 'Ahmad', 'Mohammad'];for (const [index, value] of array.entries()) {  console.log(index, value); // 0 'Hasan', 1 'Ahmad', 2 'Mohammad'}

Array.prototype.includes()

Array.includes() is a method of the Array class. It returns true if the array includes the specified element, otherwise false.

const array = ['Hasan', 'Ahmad', 'Mohammad'];console.log(array.includes('Hasan')); // trueconsole.log(array.includes('Ali')); // false

This would work with objects and arrays but only if they are reference types.

const array = [  { name: 'Hasan' },  { name: 'Ahmad' },  { name: 'Mohammad' }];console.log(array.includes({ name: 'Hasan' })); // false

Let's see an example with a reference type.

const hasan = { name: 'Hasan' };const array = [  hasan,  { name: 'Ahmad' },  { name: 'Mohammad' }];console.log(array.includes(hasan)); // true

Array.prototype.flat()

Array.flat() is a method of the Array class. It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

const array = [1, 2, [3, 4, [5, 6]]];console.log(array.flat()); // [1, 2, 3, 4, [5, 6]]

We can specify the depth of the flattening.

const array = [1, 2, [3, 4, [5, 6]]];console.log(array.flat(2)); // [1, 2, 3, 4, 5, 6]

Array.prototype.flatMap()

Array.flatMap() is a method of the Array class. It first maps each element using a mapping function, then flattens the result into a new array. It is identical to a map() followed by a flat() of depth 1, but flatMap() is often quite useful, as merging both into one method is slightly more efficient.

const array = [1, 2, 3, 4];console.log(array.flatMap(x => [x * 2])); // [2, 4, 6, 8]

Array.prototype.find()

Array.find() is a method of the Array class. It returns the value of the first element in the array that matches the provided callback function. Otherwise, it returns undefined.

const array = [  { name: 'Hasan', age: 25 },  { name: 'Ahmad', age: 30 },  { name: 'Mohammad', age: 35 }];console.log(array.find(person => person.age === 30)); // { name: 'Ahmad', age: 30 }

Array.prototype.findIndex()

Array.findIndex() is a method of the Array class. It returns the index of the first element in the array that matches the provided callback function. Otherwise, it returns -1.

const array = [  { name: 'Hasan', age: 25 },  { name: 'Ahmad', age: 30 },  { name: 'Mohammad', age: 35 }];console.log(array.findIndex(person => person.age === 30)); // 1

Array.prototype.copyWithin()

Array.copyWithin() is a method of the Array class. It shallow copies part of an array to another location in the same array and returns it without modifying its length.

const array = [1, 2, 3, 4, 5];console.log(array.copyWithin(0, 3)); // [4, 5, 3, 4, 5]

We can also specify the start and end index.

const array = [1, 2, 3, 4, 5];console.log(array.copyWithin(0, 3, 4)); // [4, 2, 3, 4, 5]

Array.prototype.fill()

Array.fill() is a method of the Array class. It fills all the elements of an array from a start index to an end index with a static value. The end index is not included.

const array = [1, 2, 3, 4, 5];console.log(array.fill(0)); // [0, 0, 0, 0, 0]

We can also specify the start and end index.

const array = [1, 2, 3, 4, 5];console.log(array.fill(0, 2, 4)); // [1, 2, 0, 0, 5]

Object.entries()

Object.entries() is a method of the Object class. It returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

const object = {  name: 'Hasan',  age: 25};console.log(Object.entries(object)); // [['name', 'Hasan'], ['age', 25]]

Object.fromEntries()

Object.fromEntries() is a method of the Object class. It transforms a list of key-value pairs into an object.

It's actually the reverse of Object.entries().

const entries = [  ['name', 'Hasan'],  ['age', 25]];console.log(Object.fromEntries(entries)); // { name: 'Hasan', age: 25 }

Object.keys()

Object.keys() is a method of the Object class. It returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

const object = {  name: 'Hasan',  age: 25,};console.log(Object.keys(object)); // ['name', 'age']

Object.values()

Object.values() is a method of the Object class. It returns an array of a given object's own enumerable property values, iterated in the same order that a normal loop would.

const object = {  name: 'Hasan',  age: 25,};console.log(Object.values(object)); // ['Hasan', 25]

Object.assign()

Object.assign() is a method of the Object class. It copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

const object1 = {  name: 'Hasan',  age: 25,};const object2 = {  name: 'Ahmad',  age: 30,};const object3 = {  name: 'Mohammad',  age: 35,};const object = Object.assign(object1, object2, object3);console.log(object); // { name: 'Mohammad', age: 35 }

It is also assigns all the properties of the source objects to the target object, even if the target object already has the same property.

const object1 = {  name: 'Hasan',  age: 25,};const object2 = {  name: 'Ahmad',  age: 30,};Object.assign(object1, object2);console.log(object1); // { name: 'Ahmad', age: 30 }

So it can be used to create a new object and copy the properties of the source objects to it.

Object.is()

Object.is() is a method of the Object class. It determines whether two values are the same value.

console.log(Object.is(1, 1)); // trueconsole.log(Object.is(1, '1')); // falseconsole.log(Object.is(NaN, NaN)); // true// checking for objects typesconsole.log(Object.is({}, {})); // false// checking by referenceconst object = {};console.log(Object.is(object, object)); // true

Object.freeze()

Object.freeze() is a method of the Object class. It freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.

const object = {  name: 'Hasan',  age: 25,};Object.freeze(object);object.name = 'Ahmad';delete object.age; // doesn't workconsole.log(object); // { name: 'Hasan', age: 25 }

In simple words, it does not allow you to change the object.

Object.seal()

Object.seal() is a method of the Object class. It seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable. seal() returns the same object that was passed in.

const object = {  name: 'Hasan',  age: 25,};Object.seal(object);object.name = 'Ahmad'; // alloweddelete object.age; // not allowedconsole.log(object); // { name: 'Ahmad', age: 25 }

The difference between Object.seal() and Object.freeze() is that Object.seal() allows you to change the values of the properties but Object.freeze() does not.

String.prototype.trimStart()

String.prototype.trimStart() is a method of the String class. It removes whitespace from the beginning of a string.

const name = ' Hasan '; // length: 7console.log(name.trimStart()); // 'Hasan ' length: 6

String.prototype.trimEnd()

String.prototype.trimEnd() is a method of the String class. It removes whitespace from the end of a string.

const name = ' Hasan '; // length: 7console.log(name.trimEnd()); // ' Hasan' length: 6

String.prototype.trim()

Because we talked about String.prototype.trimStart() and String.prototype.trimEnd(), we should also talk about String.prototype.trim().

String.prototype.trim() is a method of the String class. It removes whitespace from both sides of a string.

const name = ' Hasan '; // length: 7console.log(name.trim()); // 'Hasan' length: 5

String.prototype.padStart()

String.prototype.padStart() is a method of the String class. It pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start (left) of the current string.

const name = 'Hasan';console.log(name.padStart(10)); // '     Hasan'

We can also pass a second parameter to specify the string to pad the current string with, this can be useful when working with numbers.

const number = 25;console.log(number.toString().padStart(10, '0')); // '0000000025'

String.prototype.padEnd()

String.prototype.padEnd() is a method of the String class. It pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the end (right) of the current string.

const name = 'Hasan';console.log(name.padEnd(10)); // 'Hasan     '

We can also pass a second parameter to specify the string to pad the current string with, this can be useful when working with numbers.

const number = 25;console.log(number.toString().padEnd(10, '0')); // '2500000000'

String.prototype.matchAll()

String.prototype.matchAll() is a method of the String class. It returns an iterator of all results matching a string against a regular expression, including capturing groups.

// match all the words in a stringconst string = 'Hello World!';const regex = /\w+/g;const matches = string.matchAll(regex);for (const match of matches) {  console.log(match);}// outputs: [ 'Hello', index: 0, input: 'Hello World!', groups: undefined ] [ 'World', index: 6, input: 'Hello World!', groups: undefined ]

String.prototype.replaceAll()

String.prototype.replaceAll() is a method of the String class. It returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. If pattern is a string, only the first occurrence will be replaced.

const string = 'Hello World!';console.log(string.replaceAll('l', 'a')); // 'Heaao Warad!'

String.prototype.repeat()

String.prototype.repeat() is a method of the String class. It constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

const string = 'Hello World!';console.log(string.repeat(3)); // 'Hello World!Hello World!Hello World!'

String.prototype.includes()

String.prototype.includes() is a method of the String class. It determines whether one string may be found within another string, returning true or false as appropriate.

const string = 'Hello World!';console.log(string.includes('World')); // true

String.prototype.startsWith()

String.prototype.startsWith() is a method of the String class. It determines whether a string begins with the characters of a specified string, returning true or false as appropriate.

const string = 'Hello World!';console.log(string.startsWith('Hello')); // true

It is a case sensitive method.

const string = 'Hello World!';console.log(string.startsWith('hello')); // false

You may also pass a second parameter to specify the position to start searching from.

const string = 'Hello World!';console.log(string.startsWith('World', 6)); // true

String.prototype.endsWith()

String.prototype.endsWith() is a method of the String class. It determines whether a string ends with the characters of a specified string, returning true or false as appropriate.

const string = 'Hello World!';console.log(string.endsWith('World!')); // true

It is a case sensitive method.

const string = 'Hello World!';console.log(string.endsWith('world!')); // false

You may also pass a second parameter to specify the position to end searching at.

const string = 'Hello World!';console.log(string.endsWith('Hello', 5)); // true

A final word

I mostly listed all or at least most of the new built in functions, but i want to say something, you're not meant to try to memorize all of them, you're meant to know that they exist and when you need them, you can look them up, Google will help you, but some of these methods you'll know by heart because you'll use them a lot.

Conclusion

We've gone through a lot of new built in functions, and we've seen how they can be used in our code, and how they can make our code more readable and easier to understand.

Buy me a Coffee

If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.

Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

Bonus Content

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)


Original Link: https://dev.to/hassanzohdy/12-es6-new-built-in-functions-in-javascript-1hno

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To