ES6, ES7, ES8 & Writing Trendy JavaScript Pt4 – Contains, Pads, Loops & Maps




ES6 made JavaScript higher and extra mature programming language. It introduced many options that made developers’ lives simpler. This half will provide help to perceive ES6 options comparable to contains(), padStart(), padEnd(), new loops and in addition map() and … Map. Discover the world of ES6 and learn to write Trendy JavaScript!

ES6, ES7, ES8 & Writing Trendy JavaScript Part 1 (Scope, let, const, var).

ES6, ES7, ES8 & Writing Trendy JavaScript Part 2 (Template literals, Destructuring & Default Params).

ES6, ES7, ES8 & Writing Trendy JavaScript Part 3 (Unfold, Relaxation, Units & Object Literal).

ES6, ES7, ES8 & Writing Trendy JavaScript Part 5 (WeakMap, WeakSet and Export & Import).

ES6, ES7, ES8 & Writing Trendy JavaScript Part 6 (Arrow capabilities & Guarantees).

ES6, ES7, ES8 & Writing Trendy JavaScript Part 7 (Async/await & Courses).

Array.contains()

If you happen to work usually with arrays, you could discover this ES6 characteristic helpful. This technique known as contains() gives a quick technique to discover if an array accommodates particular merchandise, or worth. You don’t have to make use of loops or another iterators and bloat your work with pointless code. As an alternative, you need to use contains(), specify the worth or merchandise you might be searching for and let JavaScript do the remaining.

What’s extra, it’s also possible to specify at which index ought to contains() begin to search for that worth or merchandise. In that case, contains() technique won’t begin from the start of the array, which is the default. As an alternative, it’s going to begin from the index you specified and ignore all values or gadgets that exist within the array earlier than this index.

As I discussed, contains() technique takes the start of the array because the default place to begin from. Which means the index is non-obligatory parameter and you’ll omit it if you happen to don’t use it. The one required parameter is the worth or merchandise you might be searching for. If the worth exists, contains() will return true. In any other case, it’s going to return false.

///
// Contains() instance No.1:
const includesExample = ['Ruby', 'JavaScript', 'Python', 'C++', 'Swift', 'Brainfuck']

console.log(includesExample.contains('JavaScript'))
// Outputs: true

console.log(includesExample.contains('C'))
// Outputs: false


///
// Contains() instance No.2: Utilizing index parameter
const includesExample = ['Ruby', 'JavaScript', 'Python', 'C++', 'Swift', 'Brainfuck']

console.log(includesExample.contains('Python', 1))
// Outputs: true

console.log(includesExample.contains('Python', 3))
// Outputs: false (Python is on the 2nd index)

String.padStart() and String.padEnd()

The 2 lesser identified string strategies launched in ES6 are padStart() and padEnd(). Nevertheless, simply because these two should not as often called different ES6 options doesn’t imply they will not be helpful typically. They’ll. These two strategies might help you obtain one particular job in quicker and simpler means, additionally utilizing much less code.

They means padStart() and padEnd() work is that they add particular characters to current string. The padStart() provides new characters at the start of the string whereas the padEnd() on the finish. You specify the quantity of characters these strategies ought to add by way of a parameter known as targetLength.

There’s one factor it’s essential to keep in mind about this parameter. It’s not the size within the phrases of the variety of characters you wish to add. It’s the complete size of string you wish to change. So, let’s say you may have a string with eight characters and wish to broaden this string it with 4 extra characters utilizing both padStart() or padEnd().

On this case, the worth you’ll move as targetLength can be 12 (eight plus extra 4 characters). And, as I discussed, the padStart() would add the brand new characters at the start, the padEnd() would add them on the finish. What if you happen to unintentionally specify size that’s smaller than the size of the unique string? Nothing will occur.

JavaScript will return the unique string with none change. And, what if you happen to specify solely targetLength and never what character you wish to use? JavaScript will use empty house () as default character.

///
// padStart() instance No.1:
const padStartExample = 'string'

// Make the unique string 18 characters lengthy (add 12 '*' characters)
console.log(padStartExample.padStart(18, '*'))
// Outputs: '************string'


//
// padStart() instance No.2: Shorter than the unique
const padStartExample = 'string'

// Specify size smaller than the size of the unique string
console.log(padStartExample.padStart(4, '*'))
// Outputs: 'string'


//
// padStart() instance No.3: No character specified
const padStartExample = 'string'

// Omit the character parameter
console.log(padStartExample.padStart(10))
// Outputs: '    string'


///
// padEnd() instance No.1:
const padEndExample = 'string'

// Make the unique string 14 characters lengthy (add 4 '*' characters)
console.log(padEndExample.padEnd(12, '*'))
// Outputs: 'string******'


///
// padEnd() instance No.2: Shorter than the unique
const padEndExample = 'string'

// Specify size smaller than the size of the unique string
console.log(padEndExample.padEnd(4, '*'))
// Outputs: 'string'


///
// padEnd() instance No.3: No character specified
const padEndExample = 'string'

// Omit the character parameter
console.log(padEndExample.padEnd(13))
// Outputs: 'string       '

for…of and for…in loops

Loops are nothing new in JavaScript. There have been loops you may use even earlier than ES6, comparable to for, whereas and do whereas. Nevertheless, some folks had been satisfied that these weren’t sufficient. Because of this, ES6 launched two new loops, for...of and for...in. Each these loops for all iterable JavaScript objects.

This implies, you need to use them for objects comparable to strings, arrays, Sets and Maps. There are two variations between for...of and for...in it’s essential to keep in mind. First, the for...of iterates over values which are inside the item. The for...in iterates over the enumerable properties of an object. Second, for...in may iterate over object literal.

///
// for...in instance No.1: Array and enumerable properties
const forInExample = ['bazz', true, 21]

for (let prop in forInExample) {
  // Output all enumerable properties of the array
  console.log(prop)
}

// Outputs:
// '0'
// '1'
// '2'


///
// for...in instance No.2: Array and values
const forInExample = ['bazz', true, 21]

for (let prop in forInExample) {
  // Output all enumerable properties of the array
  console.log(forInExample[prop])
}

// Outputs:
// 'bazz'
// 'true'
// '21'


///
// for...in instance No.3: Object literal and enumerable properties
const forInExample = {foo: 'bazz', lang: 'JavaScript', x: 13, age: 21}

for (let prop in forInExample) {
  // Output all properties inside the item literal
  console.log(prop)
}

// Outputs:
// 'foo'
// 'lang'
// 'x'
// 'age'


///
// for...in instance No.4: Object literal and enumerable properties with values
const forInExample = {foo: 'bazz', lang: 'JavaScript', x: 13, age: 21}

for (let prop in forInExample) {
  // Output all properties in addition to their values
  console.log(`Property ${prop} has worth of ${forInExample[prop]}.`)
}

// Outputs:
// 'Property foo has worth of bazz.'
// 'Property lang has worth of JavaScript.'
// 'Property x has worth of 13.'
// 'Property age has worth of 21.'


///
// for...in instance No.5: String
const forInExample = 'JavaScript'

for (let character in forInExample) {
  // Output all characters of the string
  console.log(character)
}

// Outputs:
// '0'
// '1'
// '2'
// '3'
// '4'
// '5'
// '6'
// '7'
// '8'
// '9'


///
// for...in instance No.5: String and sq. bracket notation
const forInExample = 'JavaScript'

for (let character in forInExample) {
  // Output all characters of the string
  console.log(forInExample[character])
}

// Outputs:
// 'J'
// 'a'
// 'v'
// 'a'
// 'S'
// 'c'
// 'r'
// 'i'
// 'p'
// 't'

Now, let’s use the identical set of examples utilizing for...of. Effectively, virtually. As I discussed, for...of can’t be used with object literal. So, we should skip that one. Discover the variations between the instance above and beneath. Particularly discover the results of utilizing sq. bracket notation (array[prop]), and the final instance with strings. As you’ll be able to see the for...in will return values whereas for...of will return undefined.

///
// for...of instance No.1: Array and values
const forOfExample = ['bazz', true, 21]

for (let prop of forOfExample) {
  // Output all worth saved contained in the array
  console.log(prop)
}

// Outputs:
// 'bazz'
// 'true'
// '21'


///
// for...of instance No.2: Array, values and sq. bracket notation
const forOfExample = ['bazz', true, 21]

for (let prop of forOfExample) {
  // Output all enumerable properties of the array
  console.log(forOfExample[prop])
}

// Outputs:
// undefined
// undefined
// undefined


///
// for...of instance No.3: String
const forOfExample = 'JavaScript'

for (let character of forOfExample) {
  // Output all characters of the string
  console.log(character)
}

// Outputs:
// 'J'
// 'a'
// 'v'
// 'a'
// 'S'
// 'c'
// 'r'
// 'i'
// 'p'
// 't'


///
// for...of instance No.4: String and sq. bracket notation
const forOfExample = 'JavaScript'

for (let character of forOfExample) {
  // Output all characters of the string
  console.log(character)
}

// Outputs:
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined
// undefined

Aspect notice: It may not be a good suggestion to make use of for...in loop with arrays. The reason being that when for...in iterates over an array it could accomplish that in an inconsistent order. That means, if you happen to use for...in a number of occasions, you could get the gadgets inside an array in several order. So, if the order of things is essential, utilizing both for...of or forEach shall be a greater factor to do.

map()

One characteristic introduce by ES6, that could be very usually utilized by JavaScript developers, is map(). This technique gives a quite simple and fast technique to iterate over an array and do one thing with its content material. You specify what you wish to do with the content material through callback operate that you just move into the map() technique.

The callback technique accepts three arguments. These arguments are: 1) the worth of present array merchandise, 2) the index of present array merchandise and three) the entire array over which the map is iterating. Sounds too easy, proper? Effectively, it’s easy. That’s additionally in all probability why map() technique grew to become so common.

I discussed that map() is without doubt one of the favourite instruments of many JavaScript developers. That is very true for JavaScript developers working with frameworks comparable to React. In React, map() strategies are sometimes used for iterating over some information and creating parts comparable to lists (code instance no.3).

///
// map() instance no.1: Array with strings
const mapExample = ['foo', 'bar', 'bazz', 'buzzy']

mapExample.map((arrayItem, index, array) => {
  console.log(`${arrayItem} is on index ${index} in array [${array}].`)
})

// Outputs:
'foo is on index 0 in array [foo,bar,bazz,buzzy].'
'bar is on index 1 in array [foo,bar,bazz,buzzy].'
'bazz is on index 2 in array [foo,bar,bazz,buzzy].'
'buzzy is on index 3 in array [foo,bar,bazz,buzzy].'


///
// map() instance no.2: Some basic math
const mapExample = [1, 2, 3, 5, 8, 13, 21]

mapExample.map((arrayItem, index, array) => {
  // Output numbers contained in the array as squared
  console.log(Math.pow(arrayItem, 2))
})

// Outputs:
// 1
// 4
// 9
// 25
// 64
// 169
// 441


///
// map() instance no.3: React
import React from 'react'
import ReactDOM from 'react-dom'

// Array with some person information
const mapExample = [
  {
    name: 'Joe',
    age: 23,
    id: 1
  },
  {
    name: 'Amanda',
    age: 22,
    id: 2
  },
  {
    name: 'Daryl',
    age: 36,
    id: 3
  }
]

// Create foremost App element
const App = () => {
  return (
    <ul>
      {/* Use map() to iterate over mapExample and generate record of customers */}
      {mapExample.map((arrayItem) => {
        return <li key={arrayItem.id}>{arrayItem.identify} ({arrayItem.age})</li>
      })}
    </ul>
  )
}

// Render the App element in DOM
ReactDOM.render(<App />, doc.getElementById('root'))

Map

Apart to the map() technique, ES6 additionally launched a Map as an object. Maps can be utilized to retailer information within the type of key-value pairs. Just like arrays, Maps are iterable. Nevertheless, that is the place the similarity ends. Map doesn’t have size property. If you wish to know the quantity of things contained in the Map, you need to use dimension property. That is just like sets.

One other factor that distinguishes Maps from arrays is that Map doesn’t have map() technique. Small paradox. If you wish to iterate over Map, it’s essential to use both for...of, for...in or forEach loops. Taking into consideration what you now learn about for...in, the protected choices are both for...of or forEach.

If you wish to create new Map you need to use the Map() constructor. That is one other similarity Maps share with units. And, similar to with units, you’ll be able to initialize the Map both with values (key-value pairs) or empty, and add values later utilizing set() technique.

If you create Map with values, keep in mind to wrap them with sq. brackets ([]). Lastly, it’s also possible to create a brand new Map by merging two current Maps. To do that you need to use the spread operator.

///
// Map instance no.1: Initializing Map empty and including values later
const mapExample = new Map()

mapExample.set(0, 'John')
mapExample.set(1, 'Dick')
mapExample.set(2, 'Timothy')

for (let [key, value] of mapExample) {
  console.log(key + ': ' + worth)
}

// Outputs:
'0: John'
'1: Dick'
'2: Timothy'


///
// Map instance no.2: Initializing Map with values
const mapExample = new Map([[1, 'Sticky'], [2, 'Flocky'], [3, 'Flecky']])

for (let [key, value] of mapExample) {
  console.log(key + ': ' + worth)
}

// Outputs:
'0: Sticky'
'1: Flocky'
'2: Flecky'


///
// Map instance no.3: Map and forEach loop
const mapExample = new Map([[1, 'Foo'], [2, 'Bar'], [3, 'Bazz']])

mapExample.forEach((worth, key) => {
  console.log(key + ': ' + worth)
})

// Outputs:
'0: Foo'
'1: Bar'
'2: Bazz'


///
// Map instance no.4: Merging Maps with unfold operator
// Bear in mind to make use of completely different keys!
const mapExampleOne = new Map([[1, 'Foo']])
const mapExampleTwo = new Map([[2, 'Bazz']])

// Merge mapExampleOne and mapExampleTwo into new Map
const mapExampleThree = new Map([...mapExampleOne, ...mapExampleTwo])

mapExampleThree.forEach((worth, key) => {
  console.log(key + ': ' + worth)
})

// Outputs:
'1: Foo'
'2: Bazz'

Epilogue: ES6, ES7, ES8 & Writing Trendy JavaScript Pt4

Congratulations! You’ve simply completed the fourth a part of this collection. On this half, you’ve discovered about contains(), padStart(), padEnd(), new loops, map() and Map. Good job! As you discover the depths of ES6 and trendy JavaScript, you get higher and higher. That being stated, you aren’t on the finish, but. There’s nonetheless quite a bit you’ll be able to find out about ES6.

There’s nonetheless house for bettering your information of JavaScript. So, what’s subsequent? Within the subsequent half, you’ll find out about options comparable to arrow capabilities, export and import statements, guarantees, async/await and in addition about lessons. Till then, write some code and follow what you’ve discovered up to now.

If you happen to appreciated this text, please subscribe so you do not miss any future submit.








If you would like to assist me and this weblog, you’ll be able to change into a patron, or you should buy me a espresso 🙂







Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#ES6 #ES7 #ES8 #Writing #Trendy #JavaScript #Pt4 #Contains #Pads #Loops #Maps