Can a function take a function as an argument javascript?


A JavaScript function does not perform any checking on parameter values (arguments).


Function Parameters and Arguments

Earlier in this tutorial, you learned that functions can have parameters:

function functionName(parameter1, parameter2, parameter3) {
  // code to be executed
}

Function parameters are the names listed in the function definition.

Function arguments are the real values passed to (and received by) the function.


Parameter Rules

JavaScript function definitions do not specify data types for parameters.

JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received.


Default Parameters

If a function is called with missing arguments (less than declared), the missing values are set to undefined.

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:

Example

function myFunction(x, y) {
  if (y === undefined) {
    y = 2;
  }
}

Try it Yourself »



The Arguments Object

JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the function was called (invoked).

This way you can simply use a function to find (for instance) the highest value in a list of numbers:

Example

x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
  let max = -Infinity;
  for (let i = 0; i < arguments.length; i++) {
    if (arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}

Try it Yourself »

Or create a function to sum all input values:

Example

x = sumAll(1, 123, 500, 115, 44, 88);

function sumAll() {
  let sum = 0;
  for (let i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
}

Try it Yourself »

If a function is called with too many arguments (more than declared), these arguments can be reached using the arguments object.


Arguments are Passed by Value

The parameters, in a function call, are the function's arguments.

JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations.

If a function changes an argument's value, it does not change the parameter's original value.

Changes to arguments are not visible (reflected) outside the function.


Objects are Passed by Reference

In JavaScript, object references are values.

Because of this, objects will behave like they are passed by reference:

If a function changes an object property, it changes the original value.

Changes to object properties are visible (reflected) outside the function.



Example: Function as Parameter

// program to pass a function as a parameter

function greet() {
    return 'Hello';
}

// passing function greet() as a parameter
function name(user, func)
{

    // accessing passed function
    const message = func();

    console.log(`${message} ${user}`);
}

name('John', greet);
name('Jack', greet);
name('Sara', greet);

Output

Hello John
Hello Jack
Hello Sara

In the above program, there are two functions: name() and greet().

  • The name() function takes two parameters.
  • The greet() function is passed as an argument to the name() function.

Functions are data, and therefore can be passed around just like other values. This means a function can be passed to another function as an argument. This allows the function being called to use the function argument to carry out its action. This turns out to be extremely useful.

Examples best illustrate this technique, so let's look at a couple now.

11.3.1. Example: setTimeout¶

The built-in function setTimeout allows a programmer to pass a function, specifying that it should be called at a later point in time. Its basic syntax is:

setTimeout(func, delayInMilliseconds);

Example

Suppose we want to log a message with a 5 second delay. Since five seconds is 5000 milliseconds (1 second = 1000 milliseconds), we can do so like this:

function printMessage() {
   console.log("The future is now!");
}

setTimeout(printMessage, 5000);

repl.it

Console Output

Try It!

Is the call to printMessage actually delayed? Don't just take our word for it, try this yourself. Play with our example to change the delay.

The function printMessage is passed to setTimeout the same as any other argument.

A common twist often used by JavaScript programmers is to use an anonymous function as an argument.

Example

This program has the same behavior as the one above. Instead of creating a named function and passing it to setTimeout, it creates an anonymous function within setTimeout's argument list.

setTimeout(function () {
   console.log("The future is now!");
}, 5000);

Examples like this look odd at first. However, they become easier to read over time. Additionally, code that passes anonymous functions is ubiquitous in JavaScript.

11.3.2. Example: The Array Method map¶

The array method map allows for every element in an array to be mapped or translated, using a given function. Here's how to use it:

let mappedArray = someArray.map(functionName);

When the map method executes, the following actions occur:

  1. The first element in someArray is passed into functionName as an argument.
  2. functionName executes and returns a new value.
  3. The return value is added to mappedArray.
  4. Steps 1 - 3 repeat for each element in someArray.

When complete, mappedArray, contains each of the individual return values from the mapping function, functionName.

Example

let nums = [3.14, 42, 4811];

let timesTwo = function (n) {
   return n*2;
};

let doubled = nums.map(timesTwo);

console.log(nums);
console.log(doubled);

Console Output

[3.14, 42, 4811]
[ 6.28, 84, 9622 ]

Notice that map does not alter the original array.

When using map, many programmers will define the mapping function anonymously in the same statement as the method call map.

Example

This program has the same output as the one immediately above. The mapping function is defined anonymously within the call to map.

let nums = [3.14, 42, 4811];

let doubled = nums.map(function (n) {
   return n*2;
});

console.log(doubled);

Console Output

11.3.3. Check Your Understanding¶

Question

Similar to the map example above, finish the program below to halve each number in an array.

let nums = [3.14, 42, 4811];

// TODO: Write a mapping function
// and pass it to .map()
let halved = nums.map();

console.log(halved);

repl.it

Question

Use the map method to map an array of strings. For each name in the array, map it to the first initial.

let names = ["Chris", "Jim", "Sally", "Blake", "Paul"];

// TODO: Write a mapping function
// and pass it to .map()
let firstInitials = names.map();

console.log(firstInitials);

repl.it

Can I use a function as an argument in JavaScript?

Passing a function as an argument to the function is quite similar to the passing variable as an argument to the function. so variables can be returned from a function.

Can a function take a function as an argument?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions.

Can a function call be an argument?

Calling the function involves specifying the function name, followed by the function call operator and any data values the function expects to receive. These values are the arguments for the parameters defined for the function. This process is called passing arguments to the function.

Can you use a function in a function JavaScript?

Nested functions A function is called “nested” when it is created inside another function. It is easily possible to do this with JavaScript. Here the nested function getFullName() is made for convenience. It can access the outer variables and so can return the full name.