7. Operator - Coding Challenge Flashcards
1
Q
- Declare a variable ‘numNeighbours’ based on a prompt input like this: prompt(‘How many neighbour countries does your country have?’);
- If there is only 1 neighbour, log to the console ‘Only 1 border!’ (use loose equality == for now)
- Use an else-if block to log ‘More than 1 border’ in case ‘numNeighbours’ is greater than 1
- Use an else block to log ‘No borders’ (this block will be executed when ‘numNeighbours’ is 0 or any other value).
- Test the code with different values of’numNeighbours’, including 1 and 0.
- Change == to ===, and test the code again, with the same values of ‘numNeighbours’. Notice what happens when there is exactly 1 border! Why is this happening?
- Finally, convert ‘numNeighbours’ to a number, and watch what happens now when you input 1.
- Reflect on why we should use the === operator and type conversion in this situation
A
const numNeighbours = prompt( 1. 'How many neighbour countries does your country have?', ); // LATER : This helps us prevent bugs
const numNeighbours = Number(prompt('How many neighbour countries does your country have?'), );
if (numNeighbours === 1) { console.log('Only 1 border!'); } else if (numNeighbours > 1) { console.log('More than 1 border'); } else { console.log('No borders'); }
2
Q
- Comment out the previous code so the prompt doesn’t get in the way
- Let’s say Sarah is looking for a new country to live in. She wants to live in a country that speaks english, has less than 50 million people and is not an island.
- Write an if statement to help Sarah figure out if your country is right for her. You will need to write a condition that accounts for all of Sarah’s criteria. Take
your time with this, and check part of the solution if necessary. - If yours is the right country, log a string like this: ‘You should live in Portugal :)’. If not, log ‘Portugal does not meet your criteria :(‘
- Probably your country does not meet all the criteria. So go back and temporarily change some variables in order to make the condition true (unless you live in
Canada :D)
A
if (language === ‘english’ && population < 50 && !isIsland)
{
console.log(You should live in ${country} :)
);
} else {
console.log(${country} does not meet your criteria :(
);
}