Calling a no param javascript function with a param - javascript

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 ?

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.

You have to check on your own:
var test = function (param) {
if (typeof param === 'undefined') {
// do something...
}
};

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]

Related

Javascript: recreating Array.from?

I came across this code for stripping Marketo forms of their included stylesheets. Let's assume that the code author is a super senior engineer. Array.from() could have been used instead of defining arrayFrom (functionally at any rate), so why use the latter?
For my part I'm trying to understand the arrayFrom definition (first line of the codeblock):
bind() sets this to the provided value, here [].slice (why?)
call() allows us to call getSelection with the this value bound by bind.
getSelection() returns a Selection object (or string in Firefox) of the selected text. This I'm unsure about.
In its use, arrayFrom gets passed an array (or NodeList) of stylesheets and returns an array of the same stylesheets (a shallow copy thereof?) no differently than if Array.from were used, so the functional bit of bind and call must be to alter the this value in a desirable way. Not sure how that acts on [].slice though.
Anyone? I'm clearly missing something.
const arrayFrom = getSelection.call.bind([].slice);
// remove element styles from <form> and children
const styledEls = arrayFrom(formEl.querySelectorAll("[style]")).concat(
formEl
);
styledEls.forEach(function (el) {
el.removeAttribute("style");
});
// create an array of all stylesheets in document
const styleSheets = arrayFrom(document.styleSheets);
// loop through stylesheets and check for ownerNode properties on each
styleSheets.forEach(function (ss) {
if (
//array of <link/> elements tied to stylesheets
[mktoForms2BaseStyle, mktoForms2ThemeStyle].indexOf(ss.ownerNode) !=
-1 ||
formEl.contains(ss.ownerNode)
) {
ss.disabled = true;
}
});
Nowadays we would just use Array.from. But your questions are about the construct that is used:
const arrayFrom = getSelection.call.bind([].slice);
First of all, this has nothing to do with getSelection, as the expression is not binding that, but the call function. This call function is on the Function prototype, so the above leads to the same result as:
const arrayFrom = Function.prototype.call.bind(Array.prototype.slice);
call is a function that allows one to call another function with the possibility to provide a this-argument to it. Here we define that the function to be called should be slice. The first argument we will provide to arrayFrom will be like the first argument we would provide to call, i.e. the object on which slice should be called. This gives it a similar behaviour as Array.from.
It may help to replace bind by this function that does a similar thing:
function arrayFrom(arrayLike) {
return Function.prototype.call.call(Array.prototype.slice, arrayLike);
}
It is confusing, but we invoke call with call so that we can provide a this argument to it (defining the function we want to call), making the second argument the this-argument that call (the first one) deals with.

How Javascript know that a variable passed as parameter of function is an "event"

javascript engine know the type of variables through their values:
<script>
var x=5.01; //x if float
var x="abc"; //x is string
var x=true; //x is Boolean
</script>
but here:
<script>
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
}
</script>
My question is:
how come event ( passed as a function parameter ) is known as event object without explicit or implicit expression to define it???
what makes it an event object and not other type like float integer..??
Notice: here where fileLoad is called:
<input type=file id=profilepic accept="image/*" name=profilepic onchange="loadFile(event)">
what makes it an event object and not other type like float integer..??
Nothing. There's no reason you couldn't write:
loadFile(42);
in which case event within that call would be the number 42, not an event.
The only thing that makes event an event object during the call to loadFile is the code that's calling it. For instance, if it's hooked up as an event handler to a DOM element, the DOM event handling code in the browser calls that handler with an event object as the first argument.
If you want to enforce type safety in your code, you need something other than JavaScript such as TypeScript (which compiles to JavaScript), Flow, JSDoc+IDE support, etc. These all layer a static type system on top of JavaScript which can help you catch errors where a function is expecting (say) an event object but you're calling it with a number instead.
The value of a function argument is determined when the function is called.
When something calls the function it may or may not pass an event object.
If it does. Great. If it doesn't then you'll get an exception because it will fail to read event.target from the argument.
The argument name event is just a variable name. It doesn't enforce type safety.
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
}
loadFile(2020);
I think it's because JavaScript is weakly-typed. It just checks if the parameter has the necessary properties to run the function and it does so to the best of its capacities, and more often than not you end up with bugs rather than errors. So use TypeScript instead lol.
Javascript doesn't enforce any types. It's up to you, the programmer, to know what type your function is going to get. You can always check what type your parameters are using typeof to make sure it matches what you expect.

Could you tell me what is function(el)?

I have some code:
hideLoadMask : function(response,config){
//Once the response is processed for a particular request it will be removed from the processing array
this.loadMaskRequestQueue =
this.loadMaskRequestQueue.filter(function (el) {
return el.requestID !== response.requestID;
});
}
Here in el contains the data like:
loadingText: "Loading...Please wait."
requestID: 1
When I call hideLoadMask(), I pass response="Loading...Please wait."
Could you tell me what is function(el), how my response parameter's value became as a field to el, what is requestID.
Please clarify my doubts.
It's an inline anonymous function definition that serves as a callback to the .filter() method.
The .filter() method takes a callback that it calls to carry out it's operation. You can either define a named function elsewhere and then pass that function's name or you can define the callback function inline with this type of syntax.
The el in the function(el) signifies that the .filter() method will call the callback with at least argument (the array element currently being filtered) and this is the argument that the callback wishes to use. If you check the documentation for .filter() here, you will see that it actually passes three arguments to the callback, but this particular callback only cares to use the first argument so that's the only one it bothers to declare.

Explanation for index and value inputs to anonymous function in javascript

I have a question on how anonymous functions work in Javascript.
I saw this beautiful piece of code to toggle "disabled" from an html element [from this post link to stack overflow ]:
$('#el').prop('disabled', function(i, v) { return !v; });
The inputs to the anonymous function i and v are the index and the value.
Why is that? Is it because of .prop() or is this somehow a property of the anonymous functions? Are there other inputs available?
Thanks
SOLUTION: The answer to my question is in the docs for .prop() api.jquery.com/prop/:
It's just how the jQuery .prop() method is implemented. If it sees that the second parameter is a function, it calls your function for each matched element, passing the element index and the attribute value.
Inventing an API in JavaScript involves making decisions like that for all situations involving a callback that the API clients will use. There are no hard-and-fast rules in general, though some contexts have conventions that should probably be followed when possible. An example is the Node world, where it's very common for callbacks to get passed two arguments, a (possibly null) error and the data relevant to the operation.
It is how the prop() function is defined in jQuery. Or more accurately, how the callback for prop() is defined.
Why is that? Is it because of .prop() or is this somehow a property of
the anonymous functions? Are there other inputs available?
No, not "properties" of anonymous function , parameters of anonymous callback function. Yes, additional parameters could possibly be defined for, passed to, called at function.
i : index is index of elements from selector #el passed ; v : value is value of disabled property of selected DOM element #el disabled
the anonymous function is passed as a paremeter to the jquery prop method (callback). jquery will do its magic behind and call that function passing those parameters to it in order to you be able to work with them.

JavaScript: Sending comma separated string of parameters to a javascript function

I am having a function in javascript as
function add(v1,v2){
var add=v1+v2;
}
Now I am calling this function as below -
write.out(var param="1,2";);
write.out(window[add](param););
Using the above call, it's not working. What it does is it gives the complete string "1,2" as value to the first param(v1) of the function.
Its working if I call the function in following way -
write.out(var param1="1";);
write.out(var param2="2";);
write.out(window[add](param1,param2););
I want to achieve it using the first way where i can send the parameters as a comma separated string of parameters.
Can some one help me out how this can be done...
Thanks!!!
You can make usage of ECMAscripts .apply(), which calls a function and accepts an array of paramters.
window['add'].apply(null, param.split(','));
That way, we execute the add function, setting its context to null (you could also change that if you need) and pass in the two paramters. Since we need an Array, we call split() on the string before.
So basically, the above line is the same as
add(1,2);
Since you're haveing that function in the global context (window), we don't even need to write it that explicitly.
add.apply(null, param.split(','));
will just be fine.

Categories