78,659 views
1 vote
1 vote
Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers are different. Then, display 'Variables are not identical' if the variables are not identical (not strictly equal).

User Sten Kin
by
3.6k points

2 Answers

1 vote
1 vote

To compare the values of compareNumber and userNumber and display the appropriate message, one need to use the strict equality operator (==).

So, The current code is using the loose equality operator (===), which compares both the values and the types of the operands.

In the case of 3 and "3", they are considered equal using the strict equality operator, but not using the loose equality operator.

Below is the code to compare the values using the strict equality operator is:

JavaScript

let compareNumber = 3; // Code will be tested with: 3, 8, 42

let userNumber = '3'; // Code will be tested with: '3', 8, 'Hi'

if (compareNumber === userNumber) {

console.log('Variables are identical');

} else if (compareNumber == userNumber) {

console.log('Numbers are equal');

} else {

console.log('Numbers are not equal');

}

See text below

Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers are different. Then, display 'Variables are identical' if the variables are identical (strictly equal).

Code provided to complete the assignment:

let compareNumber = 3; // Code will be tested with: 3, 8, 42

let userNumber = '3'; // Code will be tested with: '3', 8, 'Hi'

Code I have so far:

if (compareNumber === userNumber){

console.log("Variables are identical");

}

else{

if (compareNumber == userNumber){

}

console.log("Numbers are not equal");

}

Results:

Testing log when compareNumber = 3 and userNumber = "3"

Yours and expected differ. See highlights below.

Yours

Numbers are not equal

Expected

Expected no output

Testing log when compareNumber = 8 and userNumber = 8

Yours

Variables are identical



Testing log when compareNumber = 42 and userNumber = "Hi"

Yours

Numbers are not equal

User AnotherHowie
by
3.5k points
5 votes
5 votes

Answer:

Following are attached images that will help you understand the complete code. The code is tested with different variables and different outputs are obtained. All the necessary description is given in the form o comments inside the code.

Step-by-step explanation:

Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers-example-1
Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers-example-2
Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers-example-3
Compare userNumber with compareNumber and display 'Numbers are not equal' if the numbers-example-4
User Demure
by
3.3k points