Javascript Class4 Notes and Task
Javascript Class4 Notes and Task
<html>
<body>
<script>
let name = prompt("What is your name?", "");
alert(name);
</script>
</body>
</html>
Type Conversions
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.
String Conversion
String conversion happens when we need the string form of a value.
For example, alert(value) does it to show the value.
We can also call the String(value) function to convert a value to a string:
let value = true;
alert(typeof value); // boolean
value = String(value); // now value is a string "true"
alert(typeof value); // string
Numeric Conversion
Numeric conversion in mathematical functions and expressions happens automatically.
For example, when division / is applied to non-numbers:
alert( "6" / "2" ); // 3, strings are converted to numbers
We can use the Number(value) function to explicitly convert a value to a number:
let str = "123";
alert(typeof str); // string
let num = Number(str); // becomes a number 123
alert(typeof num); // number
Remainder % The remainder operator %, despite its appearance, is not related to percents.
The result of a % b is the remainder of the integer division of a by b.
For instance:
alert( 5 % 2 ); // 1, the remainder of 5 divided by 2
alert( 8 % 3 ); // 2, the remainder of 8 divided by 3
A code that asks the user for two numbers and shows their sum.
<html>
<head></head>
<body>
<script>
let x=prompt('Enter a number:','1');
let y=prompt('Enter another number:','2');
let z=Number(x)+Number(y);
alert(`Your value ${z}`);
</script>
</body>
</html>
The binary + is the only operator that supports strings in such a way. Other arithmetic operators work
only with numbers and always convert their operands to numbers.
Task:
What are the final values of all variables a, b, c and d after the code below?
let a = 1, b = 1;
let c = ++a; // ?
let d = b++; // ?
let a = 2;
let x = 1 + (a *= 2);
1. "" + 1 + 0
2. "" - 1 + 0
3. true + false
4. 6 / "3"
5. "2" * "3"
6. 4 + 5 + "px"
7. "$" + 4 + 5
8. "4" - 2
9. "4px" - 2
10. " -9 " + 5
11. " -9 " - 5
12. null + 1
13. undefined + 1
14. " \t \n" - 2