Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 10, 2022 06:23 pm GMT

JavaScript Array and String common methods.

JavaScript is an awesome language with a lot of built-in objects (Array, Date, Math, and String) and their build-in methods (split, sort, parseInt) which make a developer's life easier.

Array -> Index-Value pair
String -> Also can work as Index-Value(character) pair

Let's see in details -

const jsString = 'abc'

can be considered equivalent (for one dimension array only) to -

const jsArray = ['a', 'b', 'c']

Example:

jsString.indexOf('a') // 0jsArray.indexOf('a')  // 0 or,jsString[0] // ajsArray[0]  // ajsString == jsArray // false - because array pass reference'a,b,c' == ['a', 'b', 'c'] // true (loose check)

Common Methods:
There are some useful methods those work on arrays as well as in strings in javascript. So, if you learn them, can easily apply for both. Those are -

.slice()
.indexOf()
.lastIndexOf()
.concat()
.includes()
.length
.toString()
.valueOf()
[...strOrArray]

Like -
JavaScript array slice and string slice

Remember: A String always carries its value whereas an array always carries reference. That's why there are some methods(not all) of the array that changes the actual value of the variable. But for string, there are no methods that can change its actual value.

Array Methods:
Here listed some methods for array that modifies the original array value directly. These methods never can be applied for string -

.splice()
.push()
.pop()
.shift()
.unshift()
.reverse()
.fill()

These array methods don't modify the array but used only for array -

.map()
.filter
.reduce()

String Methods:
Only for string-

.substr() // similar to splice
.substring() // similar to slice
.charAt()
.match()
.trim()

If you want to use string methods for an array, you can convert that array to a string and vice versa you can use array methods for string by converting that string to an array. You can easily convert each other -

Split and Join

THANKS!


Original Link: https://dev.to/yadabsd/javascript-array-and-string-common-methods-1oo0

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