Question

why does this work ?

<html>
<body id = "body">
<div id="para">hello world, invalid js API signature doesn't throw error !!!</div>
<script>
var temp = document.getSelection("parameter");
</script>
</body>
</html>

getSelection() does not take any parameter as per standard signature. I have tested this and it does not throw any error on JS console either.

Was it helpful?

Solution

JavaScript doesn't complain if you call a function with the wrong number of arguments. If there are fewer arguments passed than declared, the extra parameters have the value undefined. If there are more, they are simply ignored. This is a feature and not a bug!

Inside the JavaScript function you have access to the arguments value which is an array-like structure holding all the arguments passed to it. If you wanted you could define all your functions to take 0 parameters and use arguments[0], arguments[1], etc instead of the named parameters you previously had (though i don't see why one would do that) and the functions would still work exactly the same.

The benefits of having this arguments structure and no limits on how many arguments you call a function with allows you to do very powerfull things, like the bind polyfill found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

OTHER TIPS

If I have the following JavaScript function

function foo(first, last){
    return "from Foo";
}

JavaScript will execute and will return for all of the following

foo();
foo(2);
foo("abc");
foo("abc", 3, 5);

If you want to deal with all the passed parameter. you can get those from "arguments". MDN link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top