We could pass some parameters in functions. Okay. With ES6, it is possible to assign default values for them if they are not passed.
When we create a function, we could verify that the values were passed or not, and maybe assign a value to it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function oldHello(name, nickname) { | |
var name = (!name) ? 'James Bond' : name; | |
var nickname = (!nickname) ? 'Bond' : nickname; | |
console.log('My name is ' + nickname + ', ' + name); | |
} | |
oldHello(); | |
// My name is Bond, James Bond |
Now, we could do something like that:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function hello(name = 'James Bond', nickname = 'Bond') { | |
console.log('My name is ' + nickname + ', ' + name); | |
} | |
hello(); | |
// My name is Bond, James Bond |
Here you can find a JS Bin with the examples.