Assigning A Default Value Through The Logical Operator OR
Solution 1:
The scheme with || is the most convenient to write, but it can ONLY be used when a falsey value (undefined, null, 0, "", false, NaN) is not a legitimate value. (When you just want to deal with null and undefined, you can use the new nullish coalescing operator (??) described in this proposal and included in ES2020.)
If you want to allow specific falsey values and not allow others, then you have to write more specific code to handle your specific cases. For example, if you wanted to allow an empty string, but not allow null or undefined or other falsey values, then you'd have to write more specific code like this:
function test(value) {
if (value || value === "") {
this.value = value;
} else {
this.value = "(value not given)";
}
}
Or if you only want to exclude only undefined, you can test for it specifically:
function test(value) {
if (value === undefined) {
value = "(value not given)";
}
this.value = value;
}
Solution 2:
It depends on what values you want to exclude. If the "general false values" are too broad of a category, you can be more explicit:
function test(value) {
this.value = value !== undefined ? value : "(value not given)";
}
Solution 3:
If you want to be able to assign falsey values do this.
this.value = (typeof value !== 'undefined') ? value : 'value not given';
This will retain values like false, '', and 0, but will use the default when the value is actually not passed as a parameter.
Solution 4:
<script language="javascript">
function test (value){
this.value = arguments.length > 0 ? value : "(value not given)";
}
</script>
You can check to see if that argument was passed in by checking that functions arguments array's length.
Solution 5:
The correct way is:
this.value = (typeof value == 'undefined') ? 'my argument' : value;
Probably duplicate question. Google it.
Post a Comment for "Assigning A Default Value Through The Logical Operator OR"