2

I'm trying to check an objects every entry's key and value in a if condition, but i cannot understand my result. What is the problem? Why is an undefined not false with "??" ?

const object = {undefined: "foo", B: "Bazz"}
console.log(Object.entries(object).every(([key, value]) => !!key && !!value))

//true

const object2 = {undefined: null, B: "Bazz"}
console.log(Object.entries(object2).every(([key, value]) => !!key && !!value)) 

//false
2
  • 2
    keys are string or symbols of objects. 'undefined' is a string. btw, why do you expect a different result? Commented Jan 13, 2022 at 18:22
  • I wanted to test what would happen if i get undefined as a key. i didn't know its managed like a string. Commented Jan 13, 2022 at 18:32

2 Answers 2

2

You cannot actually set the key to undefined. When you do { undefined: "foo" }, you are actually setting the key to the string "undefined". It is essentially the same as { "undefined": "foo" }

!!"undefined" && !!"foo" => true && true => true because non-empty strings are truthy

!!"undefined" && !!null => true && false => false because null is falsy

Sign up to request clarification or add additional context in comments.

Comments

1

The propertie names of objects are strings or Symbol. To check the value, you could take an array of unwanted strings and check with includes.

const
    check = object => Object
        .entries(object)
        .every(([key, value]) => !['', 'null', 'undefined'].includes(key) && value);

console.log(check({ a: "foo", B: "Bazz" }));
console.log(check({ undefined: "foo", B: "Bazz" }));
console.log(check({ undefined: null, B: "Bazz" }));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.