Can I pass a comparison as a function parameters? - javascript

My main question is, what type of data function parameters is accepting?
I would pass a comparison as parameters as for exemple
Function test(a) //where A is a comparison so for example
test("a" == "a")
I'm trying to get the comparison expression and not the result.
Is it something possible? Any way to do it? Thanks

Yes, you can pass functions as parameters, and it's quite a common pattern in both JS and other languages to pass "predicate" functions.
let isGreaterThan5 = v => v > 5;
let out = [1,3,5,7,9].filter(isGreaterThan5);
console.log(out);

Yes it is possible:
function isPosible(param) { // Here you define a function
return param;
}
// Below you are executing the function and printing the result
console.log(isPosible("a === a")); // Returns the whole expression
More important is to understand that you can pass any expression as argument to a function, including but not limited to: Any primitive type (string, number, boolean, undefined, null, etc..), functions (callbacks), expressions that evaluates something like your case.

Related

How to negate and atribute a function to a variable in javascript?

I'm going to make a validation of a string, using javascript isNaN build in function. But depending of other variable, I want to negate de value of the isNaN, so I can check if its a Number or Not a Number
e.g.:
I'm trying to do something like this, but in javascript, it's not valid
function validation(objectWithStrings, type){
let stringCheck = type == 1 ? isNaN : !isNaN
...
}
I want to make this so I don't need to make a lot of if / else statements in the middle of my code, I can't just call stringCheck(someString) and get if it's true or false.
Is there a way to get the function in a variable but when you call it, it return the result of the function negated?
Observation: I don't want a better way to check if a string is a number or not, I want to get a way of returning the negated value of any function.
The expression isNaN is valid javascript function but !isNaN is not. You need to pass a valid javascript function that returns the opposite of isNaN:
function validation(objectWithStrings, type){
const stringCheck = type == 1 ? isNaN : (str) => !isNaN(str)
...
}
Taking into account the observation, you can create a negate function that accepts a callback and negates the result of callback execution:
const isNumber = value => !isNaN(+value);
const negate = fn => (...args) => !fn(...args);
const isNotNumber = negate(isNumber);
console.log(isNumber('10'));
console.log(isNotNumber('10'));

Javascript Nested functions with toString

Can anyone please explain this code? This example is taken from javascript.info.
I don't understand, especially the f.toString = function(){ return sum} part.
function sum(a) {
var sum = a
function f(b) {
sum += b
return f
}
f.toString = function() { return sum }
return f
}
alert( sum(1)(2) ) // 3
alert( sum(5)(-1)(2) ) // 6
alert( sum(6)(-1)(-2)(-3) ) // 0
alert( sum(0)(1)(2)(3)(4)(5) ) // 15
I think the author of that snippet wanted to achieve one goal, that is, something like "faking" operator overloading which is possible in other languages.
Since sum returns a function reference, we could not go like
sum(5) + 5;
That would result in something weird like "function sum() { ... }5". That is because ECMAscript calls the .toString() method on objects when invoked in a Math operation. But since he overwrites the .toString() method returning sum (which is a number), it does work again.
All objects in javascript 'inherit' a field called toString that exists on the prototype of boject. After assignment toString exists as any other field on f. It is assigned a as a function, and can be invoked as such:
Basically, sum is a function that can be chained into multiple calls. toString is a method of the object that returns what should be shown if the object is used in a context that expects a string.
Personally, I think it'd be easier like this:
function sum() {
var l = arguments.length, i, a = 0;
for( i=0; i<l; i++) a += arguments[i];
return a;
}
alert(sum(1,2));
alert(sum(5,-1,2));
alert(sum(6,-1,-2,-3));
alert(sum(0,1,2,3,4,5));
Here is a snippet from MDN article about Function.toString
The Function object overrides the toString method inherited from
Object; it does not inherit Object.prototype.toString. For Function
objects, the toString method returns a string representation of the
object in the form of a function declaration. That is, toString
decompiles the function, and the string returned includes the function
keyword, the argument list, curly braces, and the source of the
function body.
JavaScript calls the toString method automatically when a Function is to be represented as a text value, e.g. when a function is
concatenated with a string.
So basically, what this "annoying" piece of code is doing is providing an implementation for Function.toString that will be used when when a string representation is required, i.e. when alert is called (alert takes a string as an argument).
For the rest of the code, it's just calling itself recursively to compute the sum of the arguments.

JavaScript - referencing arguments from within a function

Recently i found myself attaching function arguments to a variable inside the function scope so that i was not referencing the argument every time it was used.
Is there any benefit to this practice?
For example:
function populateResultCount(count){
var count = count;
return $('.resultCounter').text(count);
};
Could easily be re-written like so:
function populateResultCount(count){
return $('.resultCounter').text(count);
};
And would still function correctly.
There's no functional difference between the two. Go with the simpler version.
If you're not using the argument that's passed in, there is no difference. In your first example, you can potentially confuse future maintainers because of var count = count, i.e., you're declaring a variable that has the same name as the argument, and that isn't a best practise.
So, if you can, use your second form. Its intent is clearer and there is no room for confusion.
I can see no benefit to this unless you are manipulating the data somehow. Your variable without the additional assingment can still not be accessed outside of the function.
function Test (count) {
this.increment = function() {
count++;
}
this.getCount = function() {
return count;
}
}
var test = new Test(10);
<button onclick="test.increment(); alert(test.getCount());">Increment</button>
You can do something like that even with the argument. So I think they are same.
All the other answers are correct: There's no reason to "re-assign" a passed argument inside the function.
The only thing I can think of, where you'd mess with reassigning arguments, is if you have optional arguments/default values
function xyz(optionalArgument) {
optionalArgument = optionalArgument || "no argument given";
...
}
But in that case, it'd be better to write it as
function xyz( /* optionalArgument */ ) {
var optionalArgument = arguments[0] || "no argument given";
...
}
Note that the || trick will give you the right-hand side's value, if the left-hand side is a falsy value. I.e. if you're ok with the optional argument being something that's falsy (like explicitly passing null, 0, etc), you'd have to do something like var arg = typeof arguments[x] === 'undefined' ? defaultValue : arguments[x];

Javascript not passing all the parameters

is that possible to call Javascript function without supply all the parameters?
I come across a line of code doesn't make much sense unless I assume that in Javascript supply all the parameters are not required?
The parameter been missed is a boolean value, so could I further assume that undefined boolean value in Javascript equal to 'false'?
Yes, the other parameters will just be undefined if they're not passed in :)
For example:
function myFunc(param1, param2) {
alert(param1);
alert(param2);
}
This is a valid call:
myFunc("string"); //alerts "string" then undefined
Give it a try here. If the check in your question is something like if(!param2), it'll evaluate to true, since undefined ~= false for most purposes. It's worth noting this is not only acceptable, it's very common, almost every library or framework expects only some of the parameters to be passed into most of their functions.
Adding to Nick's response, you could have:
// set the value to false if not passed
if (typeof(param2) === "undefined") param2 = false;
You may also use Variadic Functions in javascript. You can actually pass any type/number of parameters to any javascript function and use arguments to retrieve those parameters.
function PrintList()
{
for (var i = 0; i < arguments.length; i++)
{
document.write(arguments[i] + "<br />");
}
}
// Calls to Function
PrintList('Google');
PrintList('Google', 'Microsoft', 'Yahoo');
PrintList('Google', 'Microsoft', 'Yahoo', 'Adobe');

How is it legal to use a function name as the argument to another function in JavaScript?

I was gearing up for Javascript, reading the tutorials at W3Schools and came across this code:
function sortNumber(a, b)
{
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
It sorts the elements in the Array, pretty simple. But how can we pass sortNumber ( a function name) as a parameter to the sort function?
The original example
But how can we pass sortNumber ( a function name) as a parameter to the sort function?
Functions are first-class objects in JS and can be passed around as parameters or variables. Are you clear how the sort itself is working?
Surprisingly, JavaScript has its roots in a language called Scheme.
Scheme allows certain functions (called 'lambda functions') to be passed around as though they were a variable.
JavaScript handles functions in much the same way scheme did. (Some people say that "functions are first-class-citizens in JavaScript.")
For example, you can write:
// Assign a function to foo
var foo = function () { alert('bar'); };
// Call foo like a function
foo();
The result would be that the message 'bar' is shown.
The classic example of lambdas is the "Adder" example:
adder = function (x) {
return function (y) {
x + y
}
};
add5 = adder(5);
add5(1); // == 6
Hope this helps.
If you look at the documentation for the sort function within Javascript, the parameter that it accepts, which is optional is a function that can be used to determine the sort.
The function returns a positive, negative or zero value allowing the sort function to determine where everything needs to go.
You're actually passing a reference to the function itself, not its name. If you were passing its name, you would enclose it in quotes like this: "sortNumber".
sort() (as the documentation says) takes an optional argument which specifies the sorting function.
Functions are first class citizens in javascript.
Sort can take an optional paramater, a function that returns a -1, 0 or 1(whether a greater, equal to or lessthan b)
Using a-b returns a positive, zero or negative number, to do this.
The answer is available on W3Schools as well :
http://www.w3schools.com/jsref/jsref_sort.asp
the Array sort() method takes one parameter which is a function handler.
A variable in javascript can contain a anytype of value, that includes functions. If you use the name of the function without the parenthesis, your referencing the function, and not actually calling it.

Categories

Resources