Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created June 30, 2015 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuck0523/944d5511dbbf8173a07a to your computer and use it in GitHub Desktop.
Save chuck0523/944d5511dbbf8173a07a to your computer and use it in GitHub Desktop.
//Default Parameters
//ES5
function twice(x) {
x = x || 10; //xがfalseであれば10を代入
return x * 2;
}
console.log(twice(4), twice(), twice(0));
// 8, 20, 20(0がfalseに変換されるから??)
//ES6
function twice(x = 10){
return x * 2;
}
console.log(twice(4), twice(), twice(0));
//8 20 0
//デフォルト値のない引数より後にしか置けない
function(x=1, y) {}; //NG
function(y, x=1) {}; //OK
//undefinedを渡した場合はデフォルト値が使用される
function test(value = 'default') {
console.log(value);
}
test(false); //false
test(null); //null
test(undefined); //'default'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment