Skip to content

Instantly share code, notes, and snippets.

@chuck0523
Created Jun 30, 2015
Embed
What would you like to do?
//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