DEV Community

Cover image for JavaScript Array and String common methods.
YadabSD
YadabSD

Posted on

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'


Enter fullscreen mode Exit fullscreen mode

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



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


Enter fullscreen mode Exit fullscreen mode

Example:



jsString.indexOf('a') // 0
jsArray.indexOf('a')  // 0 or,

jsString[0] // a
jsArray[0]  // a

jsString == jsArray // false - because array pass reference
'a,b,c' == ['a', 'b', 'c'] // true (loose check)


Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden

Great breakdown.

Collapse
 
yadabsd profile image
YadabSD

Thanks