How Javascript Handles Function Parameters

I recently had a problem with some javascript that runs counter to every area of ​​my programming. Javascript does this often for me, so I'm not surprised.

I have a function as such ...

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

I was getting a runtime error saying arrayParam.length not defined. When debugging, I saw that this was true, and found out why. Turns out I forgot the comma in my function call as such ...

 x(param1, true [arrayJunk]); 

The problem I am facing is finding out why this call was made at all? Why is this not a compilation error, as Javascript sees it and thinks: "Yes, it looks like it might work!"

Thanks in advance for any enlightenment you can share!

+4
source share
4 answers

This is an indexing expression.
This is the same syntax as someArray[someIndex] .

In the end, undefined will be passed as the second parameter, if arrayJunk not a property name of Boolean primitives.

+3
source

The following happens:

  • JavaScript engine converts true to a Boolean object (not a primitive)
  • Then it tries to access the property name stored in arrayParam from this object
  • The property does not exist, so it returns undefined

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

+2
source

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

 someArray[42] 

Thus, it was considered as a function call with 2 parameters instead of 3

0
source

Many dynamic languages ​​do not check if you pass too many or too few arguments to a function.

Although this can sometimes mask errors, it also allows you to collapse your own defalut parameter schema.

0
source

Source: https://habr.com/ru/post/1415994/


All Articles