Now we will look at how the special
values true
and false
behave when converted to strings or numbers.
You will need this knowledge in the following lessons.
So, let's try to convert to a string using the function String
:
alert(String(true)); // shows 'true'
alert(String(false)); // shows 'false'
As you can see, the value true
is converted
to the string 'true'
, and the value
false
is converted to the string 'false'
.
That is, when you try to add a string and a
boolean value, this boolean value will be converted
to a string and the strings will be concatenated:
alert('a' + true); // shows 'atrue'
When cast to a number, the value true
is converted to the number 1
,
and the value false
is converted
to the number 0
:
alert(Number(true)); // shows 1
alert(Number(false)); // shows 0
Boolean values are first converted to a number in all mathematical operations. An example:
alert(true + 1); // shows 2
alert(true + true); // shows 2
Without running the code, determine what will be displayed on the screen:
alert(true + 3);
Without running the code, determine what will be displayed on the screen:
alert(true + true);
Without running the code, determine what will be displayed on the screen:
alert(true - true);
Without running the code, determine what will be displayed on the screen:
alert(true + false);
Without running the code, determine what will be displayed on the screen:
alert('1' + true);
Without running the code, determine what will be displayed on the screen:
alert( String(true) + 1 );
Without running the code, determine what will be displayed on the screen:
alert( String(true) + Number(true) );