JavaScript Array & String Methods

What is a Method?

A method in JavaScript is a function that is a property of an object. When working with strings or arrays, methods allow us to perform useful operations like searching, modifying, or transforming the data.

String Methods

MethodDescriptionExample
lengthReturns the number of characters'hello'.length → 5
charAt()Returns character at index'hello'.charAt(1) → 'e'
charCodeAt()Returns UTF-16 code'A'.charCodeAt(0) → 65
includes()Checks if string contains a substring'hello'.includes('he') → true
startsWith()Checks if string starts with substring'hello'.startsWith('he') → true
endsWith()Checks if string ends with substring'hello'.endsWith('lo') → true
toUpperCase()Converts to uppercase'hello'.toUpperCase() → 'HELLO'
toLowerCase()Converts to lowercase'HELLO'.toLowerCase() → 'hello'
slice()Extracts a section'hello'.slice(1,4) → 'ell'
substring()Extracts characters'hello'.substring(1,4) → 'ell'
replace()Replaces first match'hello'.replace('l', 'x') → 'hexlo'
replaceAll()Replaces all matches'hello'.replaceAll('l', 'x') → 'hexxo'
trim()Trims whitespace' hello '.trim() → 'hello'
trimStart()Trims start whitespace' hello'.trimStart() → 'hello'
trimEnd()Trims end whitespace'hello '.trimEnd() → 'hello'
split()Splits string into array'a,b,c'.split(',') → ['a','b','c']
concat()Concatenates strings'hello'.concat(' world') → 'hello world'
repeat()Repeats string'ha'.repeat(3) → 'hahaha'
padStart()Pads string at start'5'.padStart(3, '0') → '005'
padEnd()Pads string at end'5'.padEnd(3, '0') → '500'

Array Methods

MethodDescriptionExample
lengthReturns number of elements[1,2,3].length → 3
push()Adds item to end[1,2].push(3) → [1,2,3]
pop()Removes last item[1,2,3].pop() → [1,2]
shift()Removes first item[1,2,3].shift() → [2,3]
unshift()Adds item to start[1,2].unshift(0) → [0,1,2]
concat()Joins arrays[1].concat([2,3]) → [1,2,3]
join()Creates string[1,2].join('-') → '1-2'
slice()Extracts portion[1,2,3].slice(1,3) → [2,3]
splice()Add/remove elements[1,2,3].splice(1,1,9) → [1,9,3]
indexOf()First index of item[1,2,3].indexOf(2) → 1
lastIndexOf()Last index of item[1,2,2].lastIndexOf(2) → 2
includes()Checks presence[1,2].includes(2) → true
reverse()Reverses array[1,2,3].reverse() → [3,2,1]
sort()Sorts array['b','a'].sort() → ['a','b']
fill()Fills with value[1,2,3].fill(0) → [0,0,0]
copyWithin()Copies part within[1,2,3,4].copyWithin(1, 2) → [1,3,4,4]
map()Creates new array[1,2].map(x => x*2) → [2,4]
filter()Filters items[1,2,3].filter(x => x > 1) → [2,3]
reduce()Reduces to value[1,2,3].reduce((a,b)=>a+b) → 6
forEach()Loops through items[1,2].forEach(x => console.log(x))
some()Checks if any match[1,2,3].some(x => x > 2) → true
every()Checks if all match[1,2].every(x => x > 0) → true
find()Finds first match[1,2,3].find(x => x > 1) → 2
findIndex()Index of first match[1,2,3].findIndex(x => x > 1) → 1
flat()Flattens array[1,[2,3]].flat() → [1,2,3]
flatMap()Maps and flattens[1,2].flatMap(x => [x, x*2]) → [1,2,2,4]