JS Fundamentals - Type Conversions Flashcards

1
Q

Type Conversion

A

Most of the time, operators and functions automatically convert the values given to them to the right type.

For example, alert automatically converts any value to a string to show it. Mathematical operations convert values to numbers.

There are also cases when we need to explicitly convert a value to the expected type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

String conversion

A

We can also call the String(value) function to convert a value to a string:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Example of String Conversion

A
let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string “true”
alert(typeof value); // string

String conversion is mostly obvious. A false becomes “false”, null becomes “null”, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Numeric Conversion

A
alert( "6" / "2" ); // 3, strings are converted to numbers
let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When does NaN happen in Numeric conversion

A

let age = Number(“an arbitrary string instead of a number”);

alert(age); // NaN, conversion failed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Examples of Numeric Conversion

A
Value	Becomes…
undefined	NaN
null	                0
true and false	1 and 0
string	Whitespaces from the start and end are removed. If the remaining string is empty, the result is 0. Otherwise, the number is “read” from the string. An error gives NaN.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

null and undefined

A

Please note that null and undefined behave differently here: null becomes zero while undefined becomes NaN.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Boolean Conversion

A

It happens in logical operations (later we’ll meet condition tests and other similar things) but can also be performed explicitly with a call to Boolean(value).

The conversion rule:

Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false.
Other values become true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Please Note

A

Some languages (namely PHP) treat “0” as false. But in JavaScript, a non-empty string is always true.

alert( Boolean(“0”) ); // true
alert( Boolean(“ “) ); // spaces, also true (any non-empty string is true)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly