Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript array `push` with square brackets instead of parentheses - no error?

I did this by accident...

var numbers = [1, 2, 3, 4];
numbers.push[5];

Why wasn't there an error message?

push needs parentheses, not square brackets. It was just a simple typo. I wasn't paying close enough attention to what I was doing... but why wasn't there an error message?

As far as I can tell, the numbers array wasn't modified in any way. It just did... nothing.

like image 907
Vince Avatar asked Jan 14 '18 23:01

Vince


1 Answers

numbers.push is simply a function but you are attempting to find the property located at key 5 from it, which will evaluate to undefined.

function test() {
  console.log("test");
}


// test[5] evaluates to `undefined` and does nothing
console.log(test[5]);

// We can even manually set this without messing up the function
test[5] = "foo";

// outputs "foo"
console.log(test[5]);

// outputs our expected value "test"
test();
like image 92
Devan Buggay Avatar answered Nov 04 '22 16:11

Devan Buggay