5 Lesser-Known Object Tricks in JavaScript
Hi, I’m Tushar, front-end developer. In this blog, I am going to share with you some object tricks in JavaScript. While many developers are familiar with the basics, there are some hidden tricks that can significantly enhance your object manipulation skills. Let’s dive into these special tips that you might not know about!
1. Object.create() for Prototypal Inheritance
Most developers are aware of the object literal syntax {}
, but there's a less known method called Object.create()
. It allows you to create a new object with specified prototype object.
2. Object.freeze() for Immutable Objects
When you want to make an object immutable, preventing any change to its properties.
3. Object.seal() for Sealed Objects
Similar to Object.freeze(), Object.seal() prevents new properties from being added to the object
4. Object.keys() for Quick Property Checks
Sometimes, you need to check if an object has any properties or retrieve the object keys from an object. Instead of using a for...in
loop, you can utilize Object.keys()
for a more concise check:
5. Object.values() for Extracting Values
If you want an array of an object’s values, use Object.values()
:
These object tricks can add finesse to your JavaScript code. Experiment with them in your projects, and you might discover new ways to leverage the full potential of JavaScript objects. Thanks for reading and happy coding!