DEV Community

Cover image for JavaScript Interview Question #48: Dog-sized Cat
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on Originally published at learn.coderslang.com

JavaScript Interview Question #48: Dog-sized Cat

javascript interview question #48

How many errors are in this code snippet? What’s the output?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

In JavaScript there are two ways to get access to the object properties.

  • using the dot
  const dog = { name: 'Rex', age: 2, size: 'big' };

  console.log(dog.name); // Rex
  console.log(dog.age);  // 2
  console.log(dog.size); // big
⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด ⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด
  • using square brackets
  const cat = { name: 'Tom', age: 5, big: false };

  console.log(cat['name']); // Tom
  console.log(cat['age']);  // 5
  console.log(cat['big']);  // false
⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด ⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด

Notice, that we’ve used field names as plain strings inside of the square brackets.

If we go to the original question, then the statement

console.log(cat[dog.size]);
⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด ⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด

Is the same as

console.log(cat['big']);
⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด ⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด

Which is equivalent to

console.log(cat.big);
⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด ⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด

In all three cases, we get access to the field big of the object cat.


ANSWER: There are no errors in the code snippet. The value false appears in the console when the code is executed.

Learn Full-Stack JavaScript

Top comments (2)

⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด
 
ash_bergs profile image
Ash •

This is one of those questions that seems so simple once you really think about it. Thanks for the reminder to slow down and think a little longer when I look at these questions 🦄

⭐ Must Read: coderslang/javascript interview question dog sized cat hd - สรุปดราม่าล่าสุด
 
coderslang profile image
Coderslang: Become a Software Engineer •

My pleasure, Ash. Stay tuned for new articles :)