4

I recently had an issue with some javascript that goes against every bone of my programming background. Javascript does this often to me, so I'm not that surprised.

I have a function as such...

function x(param1, booleanParam, arrayParam){
    ....
}

I was getting a runtime error saying that arrayParam.length was not defined. On debugging I saw this was true and went to find out why. Turns out I had forgotten a comma in my function call as such...

x(param1, true [arrayJunk]);

The problem I'm having is figuring out why this call was made at all? Why isn't this a compile error, how does Javascript see this and think, "Yeah, that seems like it might work!"

Thanks in advance for any enlightenment you can share!

1
  • This is a case where using the Array constructor instead of the literal syntax would have provided a useful SyntaxError, but then you have the potential issue of passing a single numeric argument causing a different silent bug. Commented Jun 4, 2012 at 16:55

4 Answers 4

3

That's an indexing expression.
It's the same syntax as someArray[someIndex].

It will end up passing undefined as the second parameter too, unless arrayJunk happens to be the name of a property of boolean primitives.

Sign up to request clarification or add additional context in comments.

7 Comments

Is true not a reserved word in javascript? How can it try to do an index on a primative?
@Shaded: In Javascript, everything is an object. For example, true["toString"]() will return "true".
Not everything is an object; 1, true and "23443" are primitives. Only things where typeof returns "object" are real objects. But everything can be converted into an object, and that's what the JS engine does
@SLaks: Well, almost everything. null and undefined don't have properties.
null does not auto convert into an object
|
2

What happens is the following:

  • JavaScript engine converts true into a Boolean object (not the primitive)
  • It then tries to access the property name stored in arrayParam from that object
  • Property doesn't exist, so it returns undefined

If arrayParam was the string "toString", it would return a function object

Comments

0

In this case the expression was being interpreted as an index. Essentially the same as

someArray[42]

So it was being seen as a function call with 2 parameters instead of 3

Comments

0

Many dynamic languages don't check if you pass too many or too few arguments to a function.

While this can sometimes mask errors, it also allows you to roll your own defalut parameter scheme.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.