When does javascript makes use of Function?? I thought:
function anyfunc(){}
would the same if:
console.log(anyfunc === Function)
but that returns false, why? isn't anyfunc a Function?
CodePudding user response:
And also "Socrates" === "man"
is false. For the same reason.
What you are looking for is
anyfunc instanceof Function
Function
is a class. And in javascript, classes are variables like other.
Which means that you could wonder what is the type of "Function" itself. In some language it would have been "Class". But in js classes are implemented as functions. Which makes it hairy. Because then Function is a Function! Function instanceof Function
is true!
Which is normally not the case for any x instanceof x
.
In many languages "Class" would be an instance of "Class" (the object representing the class is itself an object, so derive from Class). But since in javascript classes are in reality functions... that makes the answer to your question tricky.
But well, retain that somefunc !== Function
. Those are two different variables, with two differents values. But somefunc instanceof Function
CodePudding user response:
A function is used to take input and output something else. Example:
function myFunc() {
console.log("Hello this is myFunc");
}
This will log "Hello this is myFunc" in the console. You can take in parameters and use them as variables. Example:
function myFunc(x, y) {
console.log(x * y);
}
myFunc(5, 5);
This will output 25.
What you were trying to do:
console.log(anyfunc === Function) Can be achieved like so:
const myfunc = function() {
console.log("hello");
}
if(typeof myfunc === "function") {
alert("Yes, myfunc is a function");
}