How to use the parseInt() function in JavaScript

The parseInt() function is one of the most commonly used functions in JavaScript. It is used to convert a string into a number. The function can take a number of different parameters, but the most common is the string to be converted and the base of the number.

The basic usage of the parseInt() function is:

parseInt(string, base)

The first parameter is the string to be converted into a number. The second parameter is the base of the number. The base can be any number between 2 and 36. The base 10 is the most common, so that is the default if the base is not specified.

The parseInt() function will return the number that is represented by the string in the given base. If the string cannot be converted into a number in the given base, then the function will return NaN (Not a Number).

Here is an example of the parseInt() function being used:

var string = "24";
var base = 10;
var number = parseInt(string, base);
console.log(number);

This code will print the number 24. The string "24" is converted into the number 24 in base 10.

The parseInt() function can also be used to convert hexadecimal numbers into integers. The hexadecimal number system uses the letters A through F to represent the numbers 10 through 15. Here is an example of the function being used to convert a hexadecimal number into an integer:

var string = "AF";
var base = 16;
var number = parseInt(string, base);
console.log(number);

This code will print the number 255. The string "AF" is converted into the number 255 in base 16.

The parseInt() function can also be used to convert binary numbers into integers. The binary number system uses the numbers 0 and 1 to represent the numbers 2 and 10. Here is an example of the function being used to convert a binary number into an integer:

var string = "1101";
var base = 2;
var number = parseInt(string, base);
console.log(number);

This code will print the number 25. The string "1101" is converted into the number 25 in base 2.