Defining a property using a method inside an object

I already know the answer (the lower most code snippet), but I’m struggling to understand why my logic fails using checkIsland(). Here’s my code:

const myCountry = {
  country: "Mexico",
  capital: "Mexico City",
  language: "Spanish",
  population: 120,
  neighbours: ["United States", "Guatemala", "Belize"],
  describe() {
    console.log(
      `${this.country} has ${this.population} million ${this.language}-speaking people, ${this.neighbours.length} neighouting countries and a capital city called ${this.capital}`
    );
  },
  checkIsland() {
    this.neighbours.length === 0 // if myCountry's neighbour array is empty
      ? this.isIsland = true // create a new property called isIsland(), and set it to true
      : this.isIsland = false; //if not, create a new property called isIsland(), and set it to false
  };
};

The correct code is this:
checkIsland () { this.isIsland = this.neighbours.length === 0 ? true : false;

1 Like

This code isn’t doing anything with the true or false. It doesn’t return it or assign it to a variable.

My bad, change the === to =. I just changed it but still not working. Is there another issue?

The only issue I see is that you have a semicolon that you shouldn’t on the second-to-last line. Once I remove that it works fine.
see it working on repl.it here
Stylistically, it isn’t the way you want to do it, but it works.

EDITED to fix link

If you really want to have a checkIsland method, you do not need another property (isIsland), you just the method to return true or false based on whether or not the neighbours array is empty or not. Your current checkIsland method returns undefined because you have not explicitly specified a return value for it.

  checkIsland() {
    return !this.neighbours.length;
  };
2 Likes

A ternary’s job is to return a value which can be assigned to a variable. Assigning a value to a variable inside the ternary is not best practices and will often fail. So, the reassignment must be declared first, followed by the condition, then finally the value… IE let x = true === true ? “It’s true!” : “It’s false!”.

2 Likes

Definitely true, didn’t think of that. But the tutorial asked me to set a property (called isIsland) using a method.

You might also use coercion, as 0 is a falsy value.

Edit: I reversed the logic, too tired I guess and it was already shown so I guess my post is a bit pointless.

checkIsland() {
  this.isIsland = !Boolean(this.neighbours.length);

  // or using ! if you like that better
  // this.isIsland = !this.neighbours.length;
}

i tried if and else,it worked but you don’t need to use ternary operators.
just return the length of that property to see the populetion.