Page 350 - Webapplication11_C11_Flipbook
P. 350
Method/ Description Example
Property
search It returns the position of the first match, -1 otherwise. text = "I am studying JavaScript";
document.write(text.search("studying"))
Output:5
document.write(text.search("Math"))
Output: -1
4.19 TYPE CONVERSIONS IN JAVASCRIPT
When two distinct types of data are used in an expression, JavaScript automatically converts the data and evaluates
the expression. This action is called type conversion. In JavaScript, there are two ways to convert the type:
Type Conversion
Implicit Type Conversion Explicit Type Conversion
Implicit Type Conversion
When an expression is evaluated and two different types are given that are incompatible to perform the operation,
JavaScript automatically converts them. The following are some examples of implicit conversions:
Ð ÐIf one value is a number and the other is a string, the expression turns the string to a number and performs the
arithmetic operation. For example, 12 * “5” returns the number 60, and 2 – “5” returns -3.
Ð ÐIn arithmetic operations, if a value is null, it is converted to the integer value 0. The outcome of null + 8 is 8, for
example.
Ð ÐIn an arithmetic operation, if one value is Boolean, it is converted to 0 or 1 depending on the provided value. True
+ 6 yields a result of 7, while false+8 yields a value of 8.
Ð ÐIf the value cannot be translated to another type, it is returned as NaN (Not a Number).
Explicit Type Conversion
The developer does this type of conversion by utilizing the built-in type conversion methods. The various methods to
explicitly convert data are as follows:
Method Description Example
Number( ) Converts any value to number. NaN is returned if the value cannot be Number(false)
converted. Output:0
Number(“77”)
Output:77
Number(“69 58”)
Output:NaN
parseInt( ) This method accepts two arguments and returns an integer value. parseInt(“30 years”)
Syntax: parseInt(string, radix) Output: 30
string—The value that has to be parsed (required) parseInt(“20.43”)
radix—The default value is 10. The number system is specified by Output: 20
numbers 2–36. (Optional) parseInt(“He is 30 years”)
Output: NaN
parseInt(“20”, 8)
Output: 16
348 Touchpad Web Applications-XI

