Ir para conteúdo

ES6: function parameters with default values


A part of bed with some pillows and next to a small closet with an alarm clock on top.

We could pass some parameters in functions, right? Okay. With ES6 it is possible 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; something like that.

function oldHello(name) {
  var name = (!name) ? 'James Bond' : name;
  var nickname = (!nickname) ? 'Bond' : nickname;
  console.log('My name is ' + nickname + ', ' + name);

// My name is Bond, James Bond

Now, we could do something like that:

function hello(name = 'James Bond', nickname = 'Bond') {
  console.log('My name is ' + nickname + ', ' + name);

// My name is Bond, James Bond

Here you can find an JS Bin with the examples.

Do you like it? Did I write something stupid? Do you want to improve? Open an issue mentioning the post and let’s talk about it.

See all the posts