Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the objects passed through rest parameter are null or undefined?

Tags:

javascript

function extend(...args), if I run the function and pass a null object in this

function extend({}), how to check if this is null or undefined.

Input: const first = { x: 2, y: 3}; const second = { a: 70, x: 4, z: 5 }; const third = { x: 0, y: 9, q: 10 }; const firstSecondThird = extend(first, second, third);

Expected Output: { x: 2, y: 3, a: 70, z: 5, q: 10 } I must also check that for each entry in ...args, that it is an object and not undefined; if any are undefined, it must throw an error. I must also check that there are at least 2 arguments.

like image 318
Vedant Soni Avatar asked Nov 03 '25 08:11

Vedant Soni


1 Answers

  • You can check length of Object.keys to check {}. As Boolean({}) is true.
  • Use includes() to check whether args contain null or undefined
  • Use some() and typeof to check if all the elements of array are object.
  • You what you don't want you properties to be overwritten if its occurs twice. Then you can you reverse()

function extend(...args){
  if(args.length < 2) throw ("Length is less than 2");
  if(!args.some(arg => typeof arg !== "object" || Object.keys(arg).length >=2 )) throw ("Arguments contain something other than object")
  if(args.includes(undefined) || args.includes(null)) throw ("Arguments contain null or undefined");
  else return Object.assign(...args.reverse()) 
   
}
const first = { x: 2, y: 3}; 
const second = { a: 70, x: 4, z: 5 };  
const third = { x: 0, y: 9, q: 10 };  
const firstSecondThird = extend(first, second, third);
console.log(firstSecondThird)


console.log(extend({}));
console.log(extend(1,2,3, undefined));
console.log(extend(1,2,3, null));
console.log(extend([]));

The above all if statements can be combined as one statement.

like image 192
Maheer Ali Avatar answered Nov 05 '25 23:11

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!