Chapter 4. Function()
Conceptual Overview of Using Function() Objects
A function is a container of code statements that can be invoked
using the parentheses () operator.
Parameters can be passed inside of the parentheses during invocation so
that the statements in the function can access certain values when the
function is invoked.
Below, we create two versions of an addNumbers function object—one using the
new operator and another using the more
common, literal pattern. Both are expecting two parameters. In each case,
we invoke the function, passing parameters in the parentheses () operator.
<!DOCTYPE html><html lang="en"><body><script> var addNumbersA = new Function('num1', 'num2', 'return num1 + num2'); console.log(addNumbersA(2, 2)); // logs 4 // could also be written the literal way, which is much more common var addNumbersB = function(num1, num2) {return num1 + num2;}; console.log(addNumbersB(2, 2)); // logs 4 </script></body></html>
A function can be used to return a value, construct an object, or as a mechanism to simply run code. JavaScript has several uses for functions, but in its most basic form, a function is simply a unique scope of executable statements.
Function() Parameters
The Function() constructor takes
an indefinite number of parameters, but the last parameter expected by the
Function() constructor is a string containing statements that comprise the body of the function. Any parameters passed to the constructor before the last will be available to the function ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access