0

The following code snippet is very simple (from https://mochajs.org/#synchronous-code). It feels stupidbut, why does [1,2,3] evaluates to undefined when used with literal notation, and not when used in a myArray variable?

var assert = require('assert')  // "mocha": "^3.0.2"
var should = require('should')  // "should": "^11.1.0"

describe('Array', function () {
  describe('#indexOf()', function () {
    var myArray = [1, 2, 3]
    it('Should return -1 when the value is not present', function () {
      myArray.indexOf(0).should.equal(-1)     // a - success
      [1, 2, 3].indexOf(0).should.equal(-1)   // b - fails test
    })
  })
})

When I run the test, line 'b' fails as follows:

Array
  #indexOf()
    1) Should return -1 when the value is not present

 1) Array #indexOf() Should return -1 when the value is not present:
    TypeError: Cannot read property 'indexOf' of undefined

    ... Error trace just points the line where it fails, nothing else ...

I would a appreciate some light on this disturbing, but surely easy-to-answer, question. Cheers.

Carlos Araya
  • 861
  • 2
  • 10
  • 17

1 Answers1

2

Fiddle that allows you to test it out:

Your missing a semi-colon and it's disrupting your tests. I'm not an expert at the edge cases but you can read about them online: Why should I use a semicolon after every function in javascript?

myArray.indexOf(0).should.equal(-1) ;   
[1, 2, 3].indexOf(0).should.equal(-1);  
Community
  • 1
  • 1
Nix
  • 57,072
  • 29
  • 149
  • 198
  • That question explains why `;` should be used when using function expressions. In this case, each `something.should.whatever()` return an object. Indeed, should just extends the `something`'s `Object.prototype`. Anyway, why does the test pass when line 'a' and 'b' are swaped? – Carlos Araya Sep 22 '16 at 12:28
  • Like i said I'm not an expert on how various runtimes parse javascript you asked why it was failing, and it's because you didn't terminate your statement. Best practice is to use semi-colons, and my guess is when the literal comes second its collapsing it and trying to do a property lookup because it sees `[xxx]` which is a way to look up a property on an object. **its a guess** – Nix Sep 22 '16 at 12:35