The wonder of Javascript’s array

Array is one of the most important and elegant features in Javascript. Developers, especially those coming from statically typed languages like Java or C# tend to overlook the built-in methods of Javascript’s array.

Photo by Junsheng Chen on Unsplash
let a = new Array
let b = new Array(1, 2, 3)
let c = []
let d = ['a', 'b', 'c']
let a = [1, '🐓', '🥚', () => {}]
console.log(typeof a[0]) //number
console.log(typeof a[1]) //string
console.log(typeof a[2]) //string
console.log(typeof a[3]) //function

Four ways to loop through an array

const a = ['🐓', 'and', '🥚']
for (let i = 0; i < a.length; i++) {
console.log(a[i])
}
//🐓
//and
//🥚
const a = ['🐓', 'and', '🥚']
for (const item of a) {
console.log(item)
}
//🐓
//and
//🥚
const a = ['🐓', 'and', '🥚']
const b = a.map((item, index) => {
console.log(index, item)
return index
})
//0 🐓
//1 and
//2 🥚
console.log(b)
//[0, 1, 2]
const a = ['🐓', 'and', '🥚']
a.forEach((item, index) => {
console.log(index, item)
return item //legal syntax, but will be ignored
})
//0 🐓
//1 and
//2 🥚

Using array as queue

const a = []
a.push('🥚') //a = ['🥚']
a.push('🐣') //a = ['🥚', '🐣']
a.push('🐓') //a = ['🥚', '🐣', '🐓']
let item = a.shift()
//item = '🥚'
//a = ['🐣', '🐓']
item = a.shift()
//item = '🐣'
//a = ['🐓']
item = a.shift()
//item = '🐓'
//a = []

Using array as stack

const a = []
a.push('🥚') //a = ['🥚']
a.push('🐣') //a = ['🥚', '🐣']
a.push('🐓') //a = ['🥚', '🐣', '🐓']
let item = a.pop()
//item = '🐓'
//a = ['🥚', '🐣']
item = a.pop()
//item = '🐣'
//a = ['🥚']
item = a.pop()
//item = '🥚'
//a = []

Inserting items

const a = [1, 2, 3]
const b = [10, 11]
a.concat(b)
console.log(a)
//[1, 2, 3, 10, 11]
const a = [1, 2, 3]
const length = a.unshift(0)
console.log(a)
//[0, 1, 2, 3]
console.log(length)
//4
const a = [1, 2, 3]
a.splice(1, 0, 1.4) // a = [1, 1.4, 2, 4]
a.splice(2, 0, 1.5) // a = [1, 1.4, 1.5, 2, 4]

Removing items

const a = [1, 2, 3, 4]
a.splice(1,2)
console.log(a)
//[1, 4]

Conclusion

Software developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store