Search This Blog

2023/09/11

Javascript : Array Length

length is a property of arrays in JavaScript that returns or sets the
number of elements in a given array.

Code:
var names= ["sagar","sangram","sachin"]
console.log(names.length)

/*we can set array length it will increase array by appending undefined
element at end*/
names.length =6;
console.log(names)

/*now array size got increased to 6 it added empty element to end to match
set size*/
console.log("Last:",names[5])

names[5] = "swapnil"
console.log("Last:",names[5])
console.log(names)

names.length =4;
console.log(names)

Output:
3
[ 'sagar', 'sangram', 'sachin', <3 empty items> ]
Last: undefined
Last: swapnil
[ 'sagar', 'sangram', 'sachin', <2 empty items>, 'swapnil' ]
[ 'sagar', 'sangram', 'sachin', <1 empty item> ]

Explanation:
when we can set array length it will increase array by appending undefined
element at end.When we set last element in increased array to string
"swapnil" by strar[5] = "swapnil" other element which got added due to
increase in length remain unchanged that is undefined or empty slot.When we
set array length to value less than its current array length array get
contracted in sence.When we set array length was 6 it become 6 element array
but when it is set to 4 ,5th & 6th element get removed.

Note:
names.length =-2; or names.length = 2.3 will give an error saying
'RangeError: Invalid array length'.

No comments:

Post a Comment