type conversions & math Flashcards
alert( “6” / “2” ); //returns?
3, strings are converted to numbers
let str = “123”;
alert(typeof str); // Returns
String
let str = “123”;
let num = Number(str);
alert(typeof num); // returns and why
number,
It becomes a number 123
let age = Number(“an arbitrary string instead of a number”);
alert(age); // returns?
NaN, conversion failed
Numeric conversion rules:
undefined becomes?
NAN
Numeric conversion rules:
Null becomes?
0
Numeric conversion rules:
true and false
1 & 0
Numeric conversion rules:
If the remaining string is empty, the result is _____
0
Numeric conversion rules:
String with characters// returns?
the number is “read” from the string. An error gives NaN.
alert( Number(“123z”) ); // returns?
NaN (error reading a number at “z”)
Numeric conversion rules:
Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become _____.
false
False numeric conversion
0
empty string
null
undefined
NAN
alert( Boolean(“hello”) ); // return
true
alert( Boolean(“”) ); // returns
false
alert( Boolean(“0”) ); // returns
0
in JavaScript, a non-empty string is always true.
& alert( Boolean(“ “) ); // return?
spaces, also true (any non-empty string is true)
let x = 1;
x = -x;
alert( x ); // returns?
-1, unary negation was applied
alert( ‘1’ + 2 ); // returns?
“12”
contacination
alert( 2 + ‘1’ ); // returns?
“21”
alert(2 + 2 + ‘1’ ); // returns?
Here, operators work one after another. The first + sums two numbers, so it returns 4, then the next + adds the string 1 to it, so it’s like 4 + ‘1’ = ‘41’.
alert(‘1’ + 2 + 2); // “
Here, the first operand is a string, the compiler treats the other two operands as strings too. The 2 gets concatenated to ‘1’, so it’s like ‘1’ + 2 = “12” and “12” + 2 = “122”.
alert( +true ); // returns and why?
1
But if the operand is not a number, the unary plus converts it into a number.
alert( +”” ); // returns
0
if the operand is not a number, the unary plus converts it into a number.
let apples = “2”;
alert( +apples);
write the longer variant
alert( Number(apples) );