![]() ![]() Let’s create a function using some of JavaScript’s newer features to safely check if an object is empty. If you try this using an object that is undefined or null you will get an error: That’s pretty much it but there is potentially one issue. Now just check if the length of that array is 0:Ĭonst isEmpty = properties.length = 0 // false Objects have many useful methods you can use and in this case we use the Object.keys() method which simply returns an array containing all of the property names that the object has. ![]() Now that you have an object to work with you can check if it has any properties:Ĭonst properties = Object.keys(person) // ![]() The first step will be to create an object and add some properties to it. In other words, how can you tell if an object has any defined properties? Solution Something that is common amongst the uses of objects, though, is the need to easily check if an object is empty. There are so many creative uses for these objects beyond simply storing and retrieving keyed values. One thing that is enjoyable about writing JavaScript code is how simple it is to create and use objects. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |