Skip to main content

Command Palette

Search for a command to run...

[JavaScript] Functions Accepting Callback functions

Published
•View as Markdown
[JavaScript] Functions Accepting Callback functions
const oneWord = function (str) {
  return str.replace(/ /g, '').toLowerCase();
};

const upperFirstWord = function (str) {
  const [first, ...others] = str.split(' ');
  return [first.toUpperCase(), ...others].join(' ');
};

// Higher-Order function
const transformer = function (str, fn) {
  console.log(`Original String: ${str}`);
  console.log(`Transformed string: ${fn(str)}`);
  console.log(`Transformed by: ${fn.name}`);
};

transformer('JavaScript is the best!', upperFirstWord);
console.log('-'.repeat(40));
transformer('JavaScript is the best!', oneWord);

// JS uses callbacks all the time
const high5 = function () {
  console.log('👋');
};

document.body.addEventListener('click', high5);

['Jonas', 'Martha', 'Adam'].forEach(high5);

functions accepting callback.PNG

% (7 times button-clicked)

JavaScript

Part 1 of 50

More from this blog

Jayden's Blog

166 posts