Prepend Function Arguments

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of function partials in JavaScript and learn how to create a higher-order function that allows us to easily prepend arguments to a given function. Through practical examples and exercises, we will understand how partial functions work and how they can be used to simplify our code and make it more modular.


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/BasicConceptsGroup -.-> javascript/str_manip("`String Manipulation`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28553{{"`Prepend Function Arguments`"}} javascript/data_types -.-> lab-28553{{"`Prepend Function Arguments`"}} javascript/arith_ops -.-> lab-28553{{"`Prepend Function Arguments`"}} javascript/comp_ops -.-> lab-28553{{"`Prepend Function Arguments`"}} javascript/str_manip -.-> lab-28553{{"`Prepend Function Arguments`"}} javascript/spread_rest -.-> lab-28553{{"`Prepend Function Arguments`"}} end

Function Arguments Prepended with Partial

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

The function partial is used to create a new function that calls fn with partials as the first arguments.

  • Use the spread operator (...) to prepend partials to the list of arguments of fn.
const partial =
  (fn, ...partials) =>
  (...args) =>
    fn(...partials, ...args);
const greet = (greeting, name) => greeting + " " + name + "!";
const greetHello = partial(greet, "Hello");
greetHello("John"); // 'Hello John!'

Summary

Congratulations! You have completed the Prepend Function Arguments lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like