-1

I have an array of objects with a length of at most 4 and at least 1. Here, I check which elements exist and do things accordingly.

function sendToGroup(receiver_group) {
  if (receiver_group[0] !== undefined){
    console.log(receiver_group[0])
  }

  if(receiver_group[1] !== undefined){
    console.log(receiver_group[1])
  }

  if(receiver_group[2] !== undefined){
    console.log(receiver_group[2])
  }

  if(receiver_group[3] !== undefined){
    console.log(receiver_group[3])
  }
}

When I give the array of 2 elements to this function, I see first and second element as expected in the console output but I also see an undefined in the line of

console.log(receiver_group[2])

How is this even possible? If it is undefined(which it is) this logging code should not get executed.

Edit: Chrome says the length of the array is 2. Which It is. receiver_group is an array. which has the content of

[{id:12, name:"name", age:"21"}, {id:22, name:"name", age:25}]

Also same thing doesn't happen for the item 4 which has the index of 3.

John Vandivier
  • 2,158
  • 1
  • 17
  • 23
Akil Demir
  • 150
  • 1
  • 11

1 Answers1

4

It is also printing undefined, if I execute the below code:

if(1==2){}

In the console you can type a name of a variable (for example try typing window) and it prints info about it. When you run any void function (like console.log) from the console, it also prints out info about the return value, undefined in this case.

So, the undefined printed after logging [0] and [1] value is the correct behavior as it is trying to print the return value which is undefined.

Please refer to the answer: Chrome/Firefox console.log always appends a line saying undefined

Srijan
  • 257
  • 1
  • 8
  • My point was It should not even enter the inside of if statement. Because What I am saying is log the output if it is not undefined in the code. – Akil Demir Mar 02 '19 at 20:55
  • 1
    @AkilDemir The point of this answer is that perhaps it isn't entering that statement at all -- the `undefined` could be triggered by the *second* log -- if you are running this code directly in the console rather than from a .js file. As an experiment, replace `console.log(receiver_group[2])` by `console.log("test")`. Is `"test"` printed? – John Coleman Mar 02 '19 at 20:57
  • I am running the code from .js file and not only logging, the code under the console.log is also running. I mean tries to run but since receiver_group[2] is undefined It can't and gives error. – Akil Demir Mar 02 '19 at 21:04