JS-Dev-101 practice question 1 of 25

A developer executes: document.cookie; document.cookie = 'key=John Smith'; What is the behavior?

Full set: 148 questions
Answer options
A: Cookies are read and the key value is set, the remaining cookies are unaffected. Correct answer
B: Cookies are read, but the key value is not set because the value is not URL encoded.
C: Cookies are not read because line 01 should be document.cookies, but the key value is set and all cookies are wiped.
D: Cookies are read and the key value is set, and all cookies are wiped.
Correct Answer:
A. Cookies are read and the key value is set, the remaining cookies are unaffected.
Explanation

The document.cookie property is an accessor, not a simple data property. When you read it, you get a string of all cookies for the document. When you assign a value to it, you are not overwriting all cookies. Instead, the browser parses the string and adds the new cookie or updates an existing cookie with the same name. All other cookies remain unaffected by this operation. The value 'John Smith' is valid, as modern browsers will handle the space.

Why Incorrect

B. The assignment will typically succeed. While URL encoding is best practice, browsers are lenient with spaces in cookie values and will often handle them correctly.
C. The property is document.cookie (singular), not cookies. The assignment operation adds or updates a single cookie; it does not wipe existing ones.
D. Assigning to document.cookie does not wipe or overwrite all other existing cookies; it only adds or updates the specified cookie.

References

1. MDN Web Docs, Document.cookie, "Using document.cookie" section. States: "You can set a new cookie by assigning a string with the cookie value to document.cookie... Note that this will not remove or change other cookies that are already stored."

2. Salesforce Lightning Web Components Dev Guide, Communicate with Cookies, "Set a Cookie" section. Demonstrates the same additive behavior of assigning to document.cookie.

Scroll to Top