0

Can someone explain this code?

function _keys(obj) { if (!isObject(obj)) return []; if (Object.keys) return Object.keys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; } function isObject(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; } console.log(_keys({red: "#FF0000", green: "#00FF00", white: "#FFFFFF"})); //output ["red","green","white"] I don't understand what this '!!' operator means. Also what's the use of 'Object.keys' and '_.has(obj, key))? I am beginner in JavaScript programming and object. Thank you.

29th Oct 2020, 1:58 AM
Logos
Logos - avatar
3 odpowiedzi
+ 2
! is the logical not as Leandro Blandi said: https://www.sololearn.com/learn/JavaScript/1133/ !! Is used to convert a value to boolean type. Examples: (!!false) === false (!!true) === true (!!42) === true (!!0) === false (!!undefined) === false In your code: type === 'object' && !!obj; That line means: "obj is of type object and it's a truthy value" The only 'falsey' value of type object is null so it could have been written this way: type === 'object' && obj !== null; Object.keys is a function that return the keys of an object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys There's nothing called _.has() in Javascript. That's likely a utility function defined somewhere else. A possible implementation of that function: Edited: function has(obj,key) { return obj.hasOwnProperty(key); }
29th Oct 2020, 3:01 AM
Kevin ★
+ 1
I understand better now. Thank you.
30th Oct 2020, 1:02 PM
Logos
Logos - avatar
0
The ! sign means NOT, an example: let number = False if (!number) { // code goes if number is False } That sign is used to evaluate if a var is true or false, as I understand.
29th Oct 2020, 2:31 AM
el3be
el3be - avatar