HTML Academy
Strict string comparison
Conditions7/17
Back to the list of tasks
  • 1. Simple fork
  • 2. Let’s use an alternative
  • 3. Simple comparisons
  • 4. Comparisons permitting equality
  • 5. Equality, inequality
  • 6. Strict string comparison
  • 7. Strict number comparison
  • 8. Condition-based actions
  • 9. If the condition is not fulfilled
  • 10. Values ​​as a condition
  • 11. Nested conditions
  • 12. Logical operators: &&, ||
  • 13. Logic traps
  • 14. Logical negation
  • 15. Let’s combine logical operators
  • 16. Summary of “Conditions”
  • 17. Second program: “How long to take a walk for?”
Condition-based actions
  • Sign up
  • Log in

Loading…
Everything will be ready in few seconds

  • Theory
  • Theory
  • Comments

Strict number comparison

You can cast number to string using the .toString() command. But sometimes, on the contrary, you would need to turn a string into a number to compare them.

To do this, you can use the parseInt() command. Example:

var string = '1';

console.log(string);
// Logs string: "1" (string)

console.log(parseInt(string, 10));
// Logs number: 1 (number)

Note that the command has two arguments:

  1. the string we are trying to turn into a number;
  2. the base of the number system into which we cast the number.

We are used to working in decimal number system, but in programming we often have to deal with other systems: binary, octal, hexadecimal. This is why parseInt() has a second argument. And although now we are not going into the intricacies of number systems, please do not forget about this feature of the parseInt() command and always explicitly specify the second argument to avoid errors.

We will talk more about this command and its features as part of one of the following courses.

Comments

  • script.js
JavaScript
var string = '123'; var number = 123; if (string === number.toString()) { console.log('The comparison is working!'); } else { console.log('I cannot compare'); }

What didn’t you like in this task?

Thanks! We’ll fix everything at once!

Console

The code has changed, click “Run” or turn autorun on.

Result

Goalscompleted

Now let’s compare the numerical values ​​of both variables.

  1. Remove the .toString() command, leaving only number in the comparison.
  2. In the comparison, replace the variable string with the parseInt(string, 10) command.

Cookies ∙ Privacy ∙ License Agreement ∙ About ∙ Contacts ∙ © HTML Academy OÜ, 2019−2025

VISAMastercard

Log in

or

Forgot your password?

Sign up

Sign up

or
Log in

Restore access

Have you forgotten your password or lost access to your profile? Enter your email connected to your profile and we will send you a link to restore access.

Forgot to connect your email to the profile? Email us and we’ll help.