The typeof
operator in JavaScript returns "function" for functions.
But, JavaScript functions can best be described as objects.
JavaScript functions have both properties and methods.
The arguments.length
property returns the number of arguments received when the function was invoked:
Example
return arguments.length;
}
The toString()
method returns the function as a string:
Example
return a * b;
}
var txt = myFunction.toString();
A function defined as the property of an object, is called a method to the object.
A function designed to create new objects, is called an object constructor.
Arrow Functions
Arrow functions allows a short syntax for writing function expressions.
You don't need the function
keyword, the return
keyword, and the curly brackets.
Example
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Arrow functions do not have their own this
. They are not well suited for defining object methods.
Arrow functions are not hoisted. They must be defined before they are used.
Using const
is safer than using var
, because a function expression is always constant value.
You can only omit the return
keyword and the curly brackets if the function is a single statement. Because of this, it might be a good habit to always keep them:
Example
Arrow functions are not supported in IE11 or earlier.
Practice Excercise Practice now