denisaemailova
denisaemailova

Reputation: 33

Getting object undefined when values are assigned

My function has a parameter dtoIn and I am trying to check if it's undefined or null.

I have values assigned like this so it shouldn't be undefined, but I get that the object is undefined anyway. Can I have some advise please.

{
    count : 10,
    minAge : 10,
    maxAge : 10,
}

function main(dtoIn={count, minAge, maxAge}) { 
  if (typeof dtoIn !== "undefined" && dtoIn !== null){
    alert(`empty`);
  }
}

Upvotes: 0

Views: 1094

Answers (2)

Swiffy
Swiffy

Reputation: 4683

I think there are a couple of misunderstandings in your code as to how object destructuring and function default values work.

Consider the following example:

let obj = {
    count : 10,
    minAge : 10,
    maxAge : 10,
}

function main({ count = 15, minAge = 15, maxAge = 15 } = {}) {
    console.log(count, minAge, maxAge)
}

main(obj);
main();

We don't actually even need to perform any undefined checks here, because this syntax is for either destructuring a given object to count, minAge and maxAge OR if nothing is given, we destructure into count = 15, minAge = 15 and maxAge = 15.

If you want to keep the dtoIn named parameter and have default values for it, you can do that like so:

let obj = {
    count : 10,
    minAge : 10,
    maxAge : 10,
}

function main(dtoIn = { count: 15, minAge: 15, maxAge: 15 }) {
    console.log(dtoIn);
}

main(obj);
main();

Upvotes: 2

jhayvon brutal
jhayvon brutal

Reputation: 17

I guess you're assigning function params wrong try this way

let dtoIn = {
count : 10,
minAge : 10,
maxAge : 10,
};

function main(val) { 
  if (typeof(val) == "undefined" && val !== null){
    alert("empty");
  }
}

main(dtoIn);

Upvotes: -1

Related Questions