Call or Return

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn about the callOrReturn function, which is a useful utility function in JavaScript. This function can be used to determine whether the given argument is a function or not. If the argument is a function, it will be called with the rest of the arguments. Otherwise, it will simply return the given argument. By the end of this lab, you will be able to use this function to simplify your code and improve its readability.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28186{{"`Call or Return`"}} javascript/data_types -.-> lab-28186{{"`Call or Return`"}} javascript/arith_ops -.-> lab-28186{{"`Call or Return`"}} javascript/comp_ops -.-> lab-28186{{"`Call or Return`"}} javascript/spread_rest -.-> lab-28186{{"`Call or Return`"}} end

A Function That Calls or Returns Another Function

To begin practicing coding, open the Terminal/SSH and type node.

Here's a function called callOrReturn that takes an argument and calls it if it's a function, otherwise, it returns it. Here's how it works:

  • The function takes two parameters: fn and ...args. fn is the argument to be checked, and ...args is the list of arguments to be passed to the function if it's called.
  • It uses the typeof operator to check if the given argument is a function.
  • If the argument is indeed a function, it calls the function using the spread operator (...) to pass the rest of the given arguments. Otherwise, it simply returns the argument.
  • Here's an example of how to use the callOrReturn function:
const callOrReturn = (fn, ...args) =>
  typeof fn === "function" ? fn(...args) : fn;

callOrReturn((x) => x + 1, 1); // 2
callOrReturn(1, 1); // 1

In the first example, callOrReturn(x => x + 1, 1) calls the function x => x + 1 with the argument 1, which returns 2. In the second example, callOrReturn(1, 1) simply returns 1 since it's not a function.

Summary

Congratulations! You have completed the Call or Return lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like