Let's assume that you have the following function:
javascriptconst sum = (a, b, optional) => { optional() return a + b }
If you call the function passing 3 arguments:
javascriptsum(2, 3, () => console.log('Start the sum!')) // Start the sum! // 5
Now, let's call the function passing 2 arguments:
javascriptsum(2, 3) // Uncaught TypeError: optional is not a function
To solve the previous error, you could modify the function as follows:
javascriptconst sum = (a, b, optional) => { if(optional) optional() return a + b } sum(2, 3) // 5
Or you could create a dummy JavaScript function and assign it as initial parameter:
javascript// You could also: // optional = Boolean // optional = () => {} const sum = (a, b, optional = console.log) => { optional() return a + b } sum(2, 3) // 5
Using console.log()
without arguments is similar to use an empty function like const noop = () => {}
. You could use the Boolean()
method as well.
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.