DEV Community

Discussion on: 10 Awesome JavaScript Shorthands

Collapse
jessycormier profile image
Jessy Cormier • Edited

If you don't need the this context you can shorten even further when you use arrow functions.

in your example

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(fruit => console.log( fruit ));
Enter fullscreen mode Exit fullscreen mode

it can be shortened to

let fruits = ['🍉', '🍊', '🍇', '🍎'];
fruits.forEach(console.log);
Enter fullscreen mode Exit fullscreen mode

The params of your forEach (item, index) will get passed to the console.log function :)

if you are using custom functions to pass into things like .forEach you can go from this example:

function printMessage(msg) { 
  console.log(msg); 
}
Enter fullscreen mode Exit fullscreen mode

to this

const printMessage = (msg) => console.log(msg);
Enter fullscreen mode Exit fullscreen mode

Hope that helps someone!

Edit: adding example of printMessage

['🍉', '🍊', '🍇', '🍎'].forEach(printMessage);
Enter fullscreen mode Exit fullscreen mode

Final note: doing this kind of extraction/abstraction of functionality can help better describe what's happening in your code without needing to add code comments and it can help you unit test your code later on with more context. When you build a larger system, you could have these type of helper functions extracted out of your main code as well. 🚀

Collapse
palashmon profile image
Palash Mondal Author

Thanks for sharing! 😊