DEV Community

Ayako yk
Ayako yk

Posted on • Updated on

Object Basics We Should Know Before Solving Coding Problems

While solving LeetCode questions, I noticed I'd not fully understood Object and Array. So, I learned the fundamentals of Object again, and this blog is more like a study note for myself. But I hope it helps those of you who've got stuck with the same problems.

This article includes:

  1. basics
  2. for ... in
  3. hasOwnProperty()
  4. Object.keys(), Object.values(), Object.entries()
  5. forEach

Basics
Object is a collection of related data and/or functionality (MDN).

Property means key: value, where key is a string and also called 'property name.'

Image description

We can check if a certain key exists in an object.

Image description

for ... in
So, by using key in object along with a for loop, we can get all the keys or values of an object.

Image description

hasOwnProperty()
Another way to check the existence of a key in an object is hasOwnProperty().
property means key. It returns true or false

Image description

*It returns true even when the value is 'undefined' or 'null'.

It is useful for "hash table" questions.

Object.keys()
This returns an array of a given object's own enumerable string-keyed property names (MDN).

It returns in the key's numeric order (ascending).
The returned keys are strings.

Image description

Object.values()
This returns an array of a given object's own enumerable string-keyed property values (MDN).

It returns an array in the key's numeric order if the keys are numeric.

Image description

Object.entries()
This returns an array of a given object's own enumerable string-keyed property key-value pairs (MDN).

It returns in the key's numeric order (ascending).

Image description

forEach
array.forEach(callback)

forEach() iterates over the array items, but if we use Object.keys(), Object.values(), or Object.entries, we can still get values because those return an array.

Image description

There're more Object methods, but the above would make it easier to solve coding problems and work with JSON.

Top comments (0)