You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Sometimes it makes sense to set default values for parameters not in the function declaration, but at a later stage, during its execution.
221
220
222
-
```js
223
-
functionshowMessage(from, text) {
221
+
To check for an omitted parameter, we can compare it with `undefined`:
222
+
223
+
```jsrun
224
+
functionshowMessage(text) {
224
225
*!*
225
226
if (text ===undefined) {
226
-
text ='no text given';
227
+
text ='empty message';
227
228
}
228
229
*/!*
229
230
230
-
alert( from +": "+text);
231
+
alert(text);
231
232
}
233
+
234
+
showMessage(); // empty message
232
235
```
233
236
234
-
……或使用 `||`运算符:
237
+
...Or we could use the `||`operator:
235
238
236
239
```js
237
-
functionshowMessage(from,text) {
238
-
// 如果 text 能转为 false,那么 text 会得到“默认”值
239
-
text = text ||'no text given';
240
+
// if text parameter is omitted or "" is passed, set it to 'empty'
241
+
functionshowMessage(text) {
242
+
text = text ||'empty';
240
243
...
241
244
}
242
245
```
243
246
247
+
Modern JavaScript engines support the [nullish coalescing operator](info:nullish-coalescing-operator) `??`, it's better when falsy values, such as `0`, are considered regular:
244
248
245
-
````
249
+
```js run
250
+
// if there's no "count" parameter, show "unknown"
: The `??` operator provides a way to choose a defined value from a list of variables. The result of `a ?? b` is `a` unless it's `null/undefined`, then `b`.
0 commit comments