I have been using jQuery for a year, but I still don’t understand how this code works:
alert($('#elementID').val()); // It gets the value of element
$('#elementID').val('setting Value'); // the same function is setting value
some other functions of jquery also do the same like .html()
I want to know how this thing is achieved? How do they overload a javascript function?
There are no overloads in javascript, so feats like this are performed using optional parameters. JavaScript allows you to call functions without specifying parameters. For example:
This example was written to point out arguments collection which you get in every function. Every function can fetch it’s parameters as a collection and can accordingly perform it’s logic. However, displayed example would be written differently in real world:
Each parameter which you do not pass to a function gets “value” of
undefined(notnull). This lets you use the shortest logical expression. You can use any value inifstatement. Variables which arenullorundefinedwill simply be evaluated asfalse.As a comment below pointed out if
textparameter is empty stringif (text)would return false. For that reason, for text parameters check parameters by type.It would be beneficial for you to also read about
nullandundefineddifferences.