DEV Community

Aditya Singh
Aditya Singh

Posted on

Function Composition in JavaScript! ๐Ÿ› ๏ธ

Function composition is a powerful technique to build clean, readable code by combining simple functions. Hereโ€™s a practical example:

  1. Trim whitespace from a username
  2. Convert the name to uppercase
  3. Generate a greeting message
  4. Check out this code snippet:
let username = "  Harley  ";
const trim = (name) => name.trim();
const convertToUpper = (name) => name.toUpperCase();
const generateMessage = (name) => `Hello ${name}, Good Morning!`;

const result = generateMessage(convertToUpper(trim(username))); // it goes right to left
console.log(result); // "Hello HARLEY, Good Morning!"

Enter fullscreen mode Exit fullscreen mode

By composing these functions, you can transform data step-by-step in a clear and efficient manner. This approach is not only elegant but also helps in maintaining and scaling your code.

Try it out and let me know what you think! ๐Ÿ˜Š๐Ÿ‘‡

Top comments (0)