JavaScript question #Day 4

Which one is true ?

const bird = {
size: ‘small’,
};

const mouse = {
name: ‘Mickey’,
small: true,
};

A: mouse.bird.size is not valid
B: mouse[bird.size] is not valid
C: mouse[bird[“size”]] is not valid
D: All of them are valid

Answer…


This content originally appeared on DEV Community and was authored by Sooraj S

Which one is true ?

const bird = {
  size: 'small',
};

const mouse = {
  name: 'Mickey',
  small: true,
};
  • A: mouse.bird.size is not valid
  • B: mouse[bird.size] is not valid
  • C: mouse[bird["size"]] is not valid
  • D: All of them are valid

Answer: A

In JavaScript, all object keys are strings (unless it's a Symbol). Even though we might not type them as strings, they are always converted into strings under the hood.

JavaScript interprets (or unboxes) statements. When we use bracket notation, it sees the first opening bracket [ and keeps going until it finds the closing bracket ]. Only then, it will evaluate the statement.

mouse[bird.size]: First it evaluates bird.size, which is "small". mouse["small"] returns true

However, with dot notation, this doesn't happen. mouse does not have a key called bird, which means that mouse.bird is undefined. Then, we ask for the size using dot notation: mouse.bird.size. Since mouse.bird is undefined, we're actually asking undefined.size. This isn't valid, and will throw an error similar to Cannot read property "size" of undefined.


This content originally appeared on DEV Community and was authored by Sooraj S


Print Share Comment Cite Upload Translate Updates
APA

Sooraj S | Sciencx (2021-07-14T11:48:02+00:00) JavaScript question #Day 4. Retrieved from https://www.scien.cx/2021/07/14/javascript-question-day-4/

MLA
" » JavaScript question #Day 4." Sooraj S | Sciencx - Wednesday July 14, 2021, https://www.scien.cx/2021/07/14/javascript-question-day-4/
HARVARD
Sooraj S | Sciencx Wednesday July 14, 2021 » JavaScript question #Day 4., viewed ,<https://www.scien.cx/2021/07/14/javascript-question-day-4/>
VANCOUVER
Sooraj S | Sciencx - » JavaScript question #Day 4. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/14/javascript-question-day-4/
CHICAGO
" » JavaScript question #Day 4." Sooraj S | Sciencx - Accessed . https://www.scien.cx/2021/07/14/javascript-question-day-4/
IEEE
" » JavaScript question #Day 4." Sooraj S | Sciencx [Online]. Available: https://www.scien.cx/2021/07/14/javascript-question-day-4/. [Accessed: ]
rf:citation
» JavaScript question #Day 4 | Sooraj S | Sciencx | https://www.scien.cx/2021/07/14/javascript-question-day-4/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.