I'm getting started with JavaScript after a lot of experience with Python and some with C. I've noticed in a few tutorials that there seems to be a strong preference among JavaScript programmers to use lambda (arrow) functions when they could use a named function instead. For example, I found this code at https://www.electronjs.org/docs/latest/tutorial/quick-start:
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
createWindow()
})
The definition for createWindow
could have used function createWindow() {...}
instead, and the call to app.whenReady
could have just passed the createWindow
identifier instead of creating a new anonymous function to pass. So this code could have been rewritten as follows:
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
That to me seems more readable, but maybe I'm biased coming from a Python background? Python, like JavaScript, has lambdas and functions as objects. So Python programmers could write code like the first example above, but they never do -- the convention is just to define a function and then pass its identifier when needed for callbacks. On the other hand, the examples above seem extremely common in the JavaScript code I've seen.
Can anyone comment on the philosophy that drives this in JavaScript? Is it just that JavaScript is almost always used asynchronously, so code is almost always called via a callback, and coders just get used to writing everything as a lambda to be called later? Or is it that this improves maintainability, e.g., if you end up wanting to add more behavior to the whenReady
callback? I could understand that, but I really don't understand why people prefer the const createWindow = () => {...}
approach when the language already has the equivalent(?) and more fundamental function createWindow() {...}
syntax.