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
Copy file name to clipboardExpand all lines: manuscript/02-Functions.md
+26-7Lines changed: 26 additions & 7 deletions
Original file line number
Diff line number
Diff line change
@@ -202,7 +202,7 @@ setCookie("type", "js", {
202
202
});
203
203
```
204
204
205
-
The behavior of this function is exactly the same as in the previous example, the only difference is the third argument uses destructuring to pull out the necessary data. Doing so makes it clear which parameters are really expected, and the destructured parameters also act like regular parameters in that they are set to `undefined` if they are not passed.
205
+
The behavior of this function is similar to the previous example, the biggest difference is the third argument uses destructuring to pull out the necessary data. Doing so makes it clear which parameters are really expected, and the destructured parameters also act like regular parameters in that they are set to `undefined` if they are not passed.
206
206
207
207
One quirk of this pattern is that the destructured parameters don't exist when the argument isn't provided. If `setCookie()` is called with just two arguments, any attempt to access `secure`, `path`, `domain`, or `expires` will throw an error. You can safely check to see if the argument was passed by using `typeof`:
Without the `typeof` check, attempting to access `secure`, `path`, `domain`, or `expires` inside of the function will result in an error. That's because the code is effectively the same as this:
235
+
236
+
```js
237
+
functionsetCookie(name, value, options) {
238
+
239
+
var { secure, path, domain, expires } = options;
240
+
241
+
// ...
242
+
}
243
+
```
244
+
245
+
Since destructuring assignment throws an error when the right side expression evaluates to `null` or `undefined`, the same is true with the third argument isn't passed.
246
+
247
+
You can work around this behavior by providing a default value for the destructured parameter:
Unless the destructured parameter is required, you should always check to ensure that the variables are present before using them.
256
+
This example now works exactly the same as the first example in this section. Providing the default value for the destructured parameter means that `secure`, `path`, `domain`, and `expires` will all be `undefined` if the third argument to `setCookie()` isn't provided.
238
257
239
-
I> Unfortunately, there's no way to specify a default value for destructured parameters.
258
+
I> It's recommended to always provide the default value for destructured parameters to avoid all errors that are unique to their usage.
0 commit comments