1

Does javascript not check function parameters when invoking.

This function "test" below fires even though it is being called with no parameter.

<input type="button" value="test" onclick="test()">

test = function(param){
 alert("test");   
}

fiddle :

http://jsfiddle.net/Yazpj/1912/

Should an error not being thrown or does the javascript engine/parser not even check function parameters when finding what to call. Does this have any implications for overriding functions ?

1
  • 1
    As your own tests point out, Javascript does not check the arguments. Commented Sep 9, 2014 at 15:55

3 Answers 3

4

No, JavaScript does not check parameters.

Extra parameters will be ignored. Parameters declared but not passed will have a value of undefined. All passed parameters (declared or otherwise) will appear in the arguments pseudo-array.

There are no implications for overriding functions because JS does not support overriding functions.

Libraries such as jQuery that have methods with multiple signatures use a single function that figures out the type of the passed parameters and then performs the required action.

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

1 Comment

It's probably worth noting that all arguments passed to a function, regardless of the parameters in the function signature, are contained in the arguments object.
0

You have to check on your own:

var test = function (param) {
    if (typeof param === 'undefined') {
        // do something...
    }
};

Comments

0

Javascript is a really flexible language and this is just one example of it. Unless you are not accessing the param it won t rise any error e.g. param.sender

As for your override question it is sort of true. Every Javascript function has a arguments variable which is the array of passed parameters. if you give name the parameter defining the function JS just give it to you according to order.

But overriding is another story the overriding is achieved by checking the arguments element sometimes just length of the array sometimes type of the individual item.

For example; when you call $("#name").val() as there is no item it just return the value if arguments has values this time jQuery user proper assignment e.g. element.value = arguments[0]

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.