what does higher-order function mean in javascript? [duplicate] - javascript

This question already has answers here:
Higher order functions - Javascript
(2 answers)
Closed 9 years ago.
javascript book "eloquent javascript"
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
show(isNotNaN(NaN));
someone explain it and as title of question says what is higher-order function, what does this code do ?

When most people think of functions they accept objects or values as parameters and similarly return an object or value, such as function addTwoNumbers(int x, int y).
In mathematics and computer science, a "higher-order function" is just like any other function, except that in addition to arguments that are values it can also accept a function as an argument.
...that's all a higher-order function is, really :)
In the example you posted, negate is a higher-order function because it has a parameter func which is a function (or rather, assigned to a function).
negate goes further: it doesn't merely call func and negate its result, instead it returns an anonymous function (that's the inner return function(x) bit).
So the isNotNaN variable then has the type (and value) of that earlier anonymous function.

Higher-order function is a function that:
Take one or more functions as input.
Give another function as output.
What does your code do? it negates the function isNan (to isNotNan). It accept a function (isNan), and then output the negation (isNotNan). It's just that simple.

Related

Functions Considered as Objects in JavaScript [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I am new to JavaScript (and StackOverflow) and am hoping to get some help on a problem that has bothered me for some time. I understand that functions are considered objects in JS. A function is different from an object in the sense that it can execute code.
This may be a very simple and straightforward question to some of you veteran folks. I don't understand how the code works below. Essentially there is a function count() that returns an anonymous counter function. keepCount points to the anonymous function (an object, of course) that count() returns.
function count() {
var num = 0;
return function(correct) {
if (correct)
num++;
return num;
}
}
var keepCount = count();
keepCount(true); // num is 1
keepCount(true); // num is 2
keepCount(true); // 3
keepCount(true); // 4
console.log(keepCount(true)); // Call it again and print. It is 5.
My question: What is causing the result of num to be 'saved' or recorded with each function call? Isn't num a variable local to count() — the outer function? num does not appear to be a property of the anonymous function. I suspect the answer has something to do with the fact that functions are considered objects in JS, and that a local variable can be continuously updated in the variable object of count(). A new variable object is not produced for count() with each call of the anonymous function.
I would also appreciate comments on the formatting of this question and all. I want to be sure that I am following StackOverflow guidelines properly. I also hope that the details of the question make sense. Please let me know if anyone requires clarification.

Why passing extra arguments to a function works in JavaScript? [duplicate]

This question already has answers here:
What happens if I call a function with more arguments than it is defined to accept?
(5 answers)
Closed 5 years ago.
Let's say I've defined a function :
function myAwesomeFunction(x){
console.log(x);
}
now, what I expect is, if I'll call it like this: myAwesomeFunction(1) or myAwesomeFunction('lol') or myAwesomeFunction('whatever'), it'll work and it does.
but how does it work, even when I pass extra arguments to the function and simply ignores all arguments except the first one :
myAwesomeFunction('why so', 'serious?')
we don't even have any optional arguments in the above function?(i.e, like (x, y=''))
function myAwesomeFunction(x){
console.log(x);
}
myAwesomeFunction(1);
myAwesomeFunction('lol');
myAwesomeFunction('whatever');
myAwesomeFunction('why so', 'serious?')
myAwesomeFunction('why', 'so', 'serious?')
You can call a Javascript function with any number of parameters, regardless of the function's definition.
Any named parameters that weren't passed will be undefined.
Javascript treats your parameters as an array. More specifically it's the arguments array, Named parameters in function declarations are just pointers to members of arguments. More info here
When you defined the function, you gave it one parameter x
The language is designed to look for a single argument for each parameter, and ignore the others.
However, you are able to access the other arguments via the special arguments object.
Try typing console.log(arguments) within your function body and seeing what happens...

Clever JavaScript to bypass eval method [duplicate]

This question already has an answer here:
What's going on in this piece of Javascript?
(1 answer)
Closed 6 years ago.
[]["constructor"]["constructor"](<string representing JavaScript code>)()
In JavaScript the "constructor" property returns the prototype of an object. In this case the prototype of [] is the Array class. Accessing the "constructor" property of the Array class returns the Function object. The constructor of Function object then returns a function and the body of that function is the last parameter, which is passed to the constructor. This results in the creation of a function that uses the provided string as the function's body (i.e. code), which is then instantly executed.
As stated in the paragraph above from: https://www.trustwave.com/Resources/SpiderLabs-Blog/Angler-Exploit-Kit-%E2%80%93-Gunning-For-the-Top-Spot/?page=1&year=0&month=0
The above line of code was used to execute obfuscated JavaScript code without using the 'eval' method. After reading this paragraph, I can't quite grasp this clever line of code. Can anyone explain what is actually happening?
Note the constructor of an Array instance is obviously Array:
[].constructor === Array
and further, the constructor of Array is Function:
[].constructor.constructor === Array.constructor === Function
Now in JavaScript, Function(source) returns a function instance whose source is given by the parameter. For example:
Function("alert(1337)");
will create (and is analogous to):
function() {
alert(1337);
}
Your code will instantiate such a function and immediately call it with (). And that's exactly how eval behaves.
So, if it helps, you could reduce your code example to:
Function(source)();

difference between javascript function declaration [duplicate]

This question already has an answer here:
Anonymous function vs normal function
(1 answer)
Closed 9 years ago.
I know this type of question gets asked a lot, but I haven't seen any question with this type of declaration
(function(){
myFuncName=function(myVar){
// some logic
};
}());
how does that differ from
function myFuncName(myVar){
// some logic
}
The first one is an anonymous function and there is no way you can reference to and call it later on, so you just executes instantly ( ) once it had been created!
(function(){
alert(1)
}())
The second one is a reference function that you can call it anytime later. It wont gets executed unless you call it explicitly
What your doing is creating an anonymous function that also has a closure in it. Read more about closures here.
Basically a closure means that you have declared a function inside of another function. Which will let you access local variables after the first function exits.
Normally you would not be able to do this since they would be out of scope.
As for the other part. You can find a very useful guide to what's happening here Why do you need to invoke an anonymous function on the same line?.
To sum it up though, you have created an anonymous self-invoking function expression.
The self-invoking comes from the fact that () immediately follows the function expression.
Here's a link which explains the the function declarations in javascript.

Javascript Call And Apply used together [duplicate]

This question already has answers here:
call and apply in javascript [duplicate]
(2 answers)
Closed 8 years ago.
I know the call and apply in javascript but how does exactly the difference between javascript Call and Apply..?? and another thing i found some code use this together like this:
function doSomething() {
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
are is the same as..
Array.prototype.slice.apply(arguments)
Why we want to use call and apply together?
No, it is not the same. Array.prototype.slice.apply(arguments) applies the slice function on the current argument object, while Function.prototype.call.apply(Array.prototype.slice, arguments); calls the slice function on the array which is provided as the first argument.
Maybe things like this will become easier with new EcmaScript syntax. Your doSomething is equivalent to
function doSomething(array, ...)
array.slice(...); // assuming array is really an array
}
whereas the second is equivalent to
function (...) {
arguments.slice(); // assuming argument objects are actual arrays
}
ase the same
Array.prototype.slice.apply(arguments)
yes, i think its the same too..!!

Categories