DEV Community

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

Posted on

3 2

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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (2)

Collapse
 
andrewbaisden profile image
Andrew Baisden •

Great breakdown.

Collapse
 
yadabsd profile image
YadabSD •

Thanks

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more