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

I did this by accident...var numbers = [1, 2, 3, 4];numbers.push[5];Why wasn't there an error mes

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.

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.

Share asked Jan 14, 2018 at 23:18 VinceVince 4,2323 gold badges37 silver badges59 bronze badges 2
  • 1 because that simply evaluates to undefined - any property (functions are just properties in javascript anyway) can have properties ... – Jaromanda X Commented Jan 14, 2018 at 23:20
  • 3 Because it is just accessing the property named 5 on the property named push. There isn't a syntax error there, just a logic one – Patrick Evans Commented Jan 14, 2018 at 23:21
Add a ment  | 

1 Answer 1

Reset to default 9

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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744932888a4601844.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信