Function Expressions in JavaScript#
I’m currently learning JavaScript, and here are a few things I learned about function expressions in JavaScript ;)
Anonymous vs Named Functions#
// An anonymous function ==> lambda function in Python
const clickHandler = function(){
console.log('The user clicked this button.')
}
// Named Function
const keyHandler = function keyHandler() {
console.log('This is a named function.')
}
clickHandler()
The user clicked this button.
keyHandler()
This is a named function.
const cars = [{make: 'toyota', id: 'Rav4'}, {make: 'tesla', id: 'S'}]
// Arrow Function
let ids = cars.map(car => car.id)
console.log(ids)
[ 'Rav4', 'S' ]
// An equivalent named function
ids = cars.map(function getId(car){
return car.id
})
console.log(ids)
[ 'Rav4', 'S' ]
Takeaways:#
When it comes to Arrow functions, I often find myself having to carefully read the function body to figure out what’s going on.
IMHO, named functions are the best because they tell us in their name what they do.
Immediately Invoked Function Expressions (IIFE)#
const school = 'MIT'
(function anotherSchool(){
const school = 'CMU'
console.log(school)
})()
CMU
console.log(school)
MIT
Takeaways:#
IIFEs are typically used in places in our code where we need to collect a set of variables and protect them from intruding an outer scope.