0

enter image description here

I need help this task You have to implement function that will Check that object is empty. Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)

check object for presence: {},0, “”, symbol(“key”), null, 5,[].

2
  • Can you post your code? Commented Feb 11, 2022 at 13:00
  • Yes, sure. I post code Commented Feb 11, 2022 at 13:46

2 Answers 2

2

You can use something like this. This will just loop through the object and check if any value exist and if it does it will just return false else it will return true.

function isEmpty(obj) {
  for (let key in obj) {
     if(!!obj[key]) return false;
   }
   return true;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am not sure what you are talking about but it should work for all the falsy values.
I added a check. How it is possible to optimize and accelerate this code? function isEmpty(object) { return !Object.values(object) || Object.values(object).every (v => !v) && Object.getOwnPropertySymbols(object).length === 0; }
0

You can use 'Object.Values(obj)' which returns an array of all the values from the key value pairs of the object passed as parameter.

'!Object.Values(obj)' will return false if there are no values, which means this is not an object.

'anArray.every(element => { //return a boolean } )' will loop through all the items of the array and return true only if the the arrow function returns true for all 'every' element on the array

function isEmpty (obj){
    return !Object.Values(obj) ||
    Object.Values(obj).every (v => !v));
    

3 Comments

I added a check. How it is possible to optimize and accelerate this code? function isEmpty(object) { return !Object.values(object) || Object.values(object).every (v => !v) && Object.getOwnPropertySymbols(object).length === 0; }
It doesnt need otimization. But one change although not necessary is maybe to check for !Object.Values(obj).some(v => !!v))
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.