Search code examples
javascriptarrays

javascript array empty and undefined


I have a question about empty and undefined in array

please see my codes bottom

const arr = []
arr[1]=1
arr[2]=2
arr[3]=3
arr[5]=5
console.log(arr[4])// console: undefined
console.log(arr)// console: [empty, 1,2,3,empty,5]

so I didn't understand difference between two colsole result

why console.log(arr[4]) is undefined but console.log(arr)'s index 4 is empty?

please help me thank you


Solution

  • When you read a property which doesn’t exist you get the value undefined. That’s standard JS.

    When you log a whole array, you aren’t reading the property explicitly, so the console helpfully distinguishes between “has no value” and “explicitly has the undefined value”.