DEV Community

boopalan
boopalan

Posted on

Arrays length, pop and at functions

Suppose if you want to get the length of an array, how we will get it,
we usually do looping and get the count of the length

const fruits = ['banana', 'mango', 'jack','graph']
count = 1
for (const f of fruits){
    count += 1
}

console.log(count)
Enter fullscreen mode Exit fullscreen mode

but length will doing all the whole just in one line

const fruits = [banana', 'mango', 'jack','graph']
console.log(fruits.lenght)
Enter fullscreen mode Exit fullscreen mode

In array at method helps to indexing and also it supports negative indexing

By default when we use the square brackets to get the arrays elements it does not
support the negative indexing but at method helps for the negative indexing also,

in programming logic some scenarios negative indexing helps in many places

example

indexing


const fruits = ['banana', 'mango', 'jack','graph']
console.log(fruits[2]) //jack
console.log(fruits.at(2)) //jack
Enter fullscreen mode Exit fullscreen mode

negative indexing

const fruits = ['banana', 'mango', 'jack','graph']
console.log(fruits[-2]) //jack
console.log(fruits.at(-2)) //jack
Enter fullscreen mode Exit fullscreen mode

if you use the out of the index in any of thus method both methods it always get the
undefined

const fruits = ['banana', 'mango', 'jack','graph']
console.log(fruits[8]) // undefined
console.log(fruits.at(8)) // undefined

const fruits = ['banana', 'mango', 'jack','graph']
console.log(fruits[-8]) //  undefined
console.log(fruits.at(-8)) // undefined

Enter fullscreen mode Exit fullscreen mode

join function

this function helps to join the each elements to gather and return a string


const fruits = ['banana', 'mango', 'jack','graph'];
const joinedFruits = fruits.join(" ");
console.log(joinedFruits) 
// 'banana mango jack graph'

const joinedFruits = fruits.join("*");
console.log(joinedFruits) 
// 'banana*mango*jack*graph'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)