Type Conversion and Casting: Handle Input Safely
A typed mark may arrive as text
A teacher enters 35 into a text field. A program reading that field receives the string '35', even though the teacher intended a number. Adding five without dealing with the type can produce the text 355.
Type conversion creates a value of another type. An explicit conversion is requested in the code, such as JavaScript’s Number. Implicit conversion, also called coercion, is performed automatically by a language operation. Neither kind proves the resulting value is valid for the task.
Predict the difference
Explain why text-plus-number joins text while converted numeric input supports addition.
Validate safely
Reject a blank, a non-finite number and a mark outside the school’s range without treating them as a valid zero.
Recognize information loss
Identify when parsing or conversion discards formatting or fractional information, and why a type assertion is not a runtime conversion.
Convert first, then check the school rule
Text input
A text field supplies characters, not a guaranteed numeric mark.
"35"Numeric conversion
Number creates a candidate numeric value.
35Validation
Check that input was supplied and the numeric value meets the school rule.
Finite and within 0–50
Conversion does not edit the original input
In JavaScript, Number(enteredScience) returns a numeric value when the text can be converted. You can store that result under another name while keeping the original string for a validation message or report.
This is different from reassigning a variable. Conversion produces a value; assignment decides where that value will be stored. It is also different from a type annotation, which gives a checker information rather than changing a runtime value.
The prerequisites are numbers, strings and booleans and type rules. Every operation below is labeled with its language because conversion behavior differs between languages.
Compare text joining with numeric addition
This complete program uses JavaScript. Predict all three output lines before revealing the trace. Number requests conversion, + performs the operation allowed by its operands, and typeof reports the original input’s type.
The first sample starts with text 35 and the second with text 20. The player explains prepared states for the displayed programs. It models a supplied text value; it does not read a form or run your own code.
Choose a sample and follow its execution. Guided simulation.
const enteredScience = '35';
console.log(enteredScience + 5);
const science = Number(enteredScience);
console.log(science + 5);
console.log(typeof enteredScience);Top-level scope
typeof confirms that the original enteredScience value is still a string. Conversion did not rewrite the original text.
355 40 string
What do you expect this program to print?
Automatic conversion follows rules, not the teacher’s intention
JavaScript · the same input, two different operations
const enteredScience = '35';
console.log(enteredScience + 5);
const science = Number(enteredScience);
console.log(science + 5);
console.log(typeof enteredScience);Expected output
355
40
stringIn the first output instruction, the string '35' leads JavaScript’s + to join text. The number 5 is converted to text, and the two strings become '355'. The operation does not guess that the teacher intended a corrected mark.
The next instruction explicitly creates numeric 35. Adding numeric 5 then gives 40. An explicit conversion makes this intention visible, but you must still inspect whether conversion succeeded and whether the mark is allowed.
Do not rely on changing the arithmetic operator to make input “work.” Different operators have different conversion rules. Use a clear conversion and validation policy before performing arithmetic.
Blank text and invalid text need different attention
This JavaScript example shows why conversion alone is insufficient. An empty string and a whitespace-only string convert to zero. Unsuitable text such as 'forty' or '35 marks' converts to NaN, short for “Not a Number.”
NaN is a special value within JavaScript’s number type, not a separate primitive type. The text 'Infinity' converts to Infinity, which is numeric but not a finite school mark. These are language-specific rules described in the Number documentation.
A genuine zero mark must remain acceptable, while a missing entry should get a useful message. Check the original input’s presence as well as the converted result.
JavaScript · local teaching example
console.log(Number(''));
console.log(Number(' '));
console.log(Number('forty'));
console.log(Number('35 marks'));
console.log(Number('Infinity'));Expected output
0
0
NaN
NaN
InfinityCheck presence, conversion and range separately
This JavaScript teaching example validates one supplied text value. trim() removes whitespace from its ends. The first condition checks whether anything remains; === tests equality. Number.isFinite accepts a finite number and rejects NaN and Infinity.
The ! symbol means “not,” and || means “or.” The range condition rejects a mark below 0 or above 50. if and else if choose the first matching branch; the final else displays an accepted mark. Only one branch prints a result.
The school in this example permits fractional marks. If a different school requires whole marks, add a separate Number.isInteger rule. See the finite-number check and later conditional statements for these operations.
JavaScript · local teaching example
const enteredScience = '35';
const text = enteredScience.trim();
const science = Number(text);
if (text === '') {
console.log('Enter a mark.');
} else if (!Number.isFinite(science)) {
console.log('Enter a finite number.');
} else if (science < 0 || science > 50) {
console.log('Enter a mark from 0 to 50.');
} else {
console.log(science);
}Expected output
35Trace why each input is accepted or rejected
JavaScript · use this complete validator for each input
const enteredScience = '35';
const text = enteredScience.trim();
const science = Number(text);
if (text === '') {
console.log('Enter a mark.');
} else if (!Number.isFinite(science)) {
console.log('Enter a finite number.');
} else if (science < 0 || science > 50) {
console.log('Enter a mark from 0 to 50.');
} else {
console.log(science);
}The complete validation program is reproduced above. Change only enteredScience to compare the following cases; each follows the same rule.
'0': not blank, converts to finite zero, and is in range. It prints 0.' ': trimming produces an empty string. The first branch prints “Enter a mark.” instead of accepting the converted zero.'forty': conversion produces NaN. The second branch prints “Enter a finite number.”'55': conversion succeeds, but the range branch prints “Enter a mark from 0 to 50.”'35.5': this fictional school permits fractions, so it prints 35.5.
These messages represent different problems. Do not replace every rejected entry with zero; that would turn missing or invalid information into an apparently real result.
Parsing a numeric prefix is not the same as validating a mark
Parsing reads text according to a format. In this JavaScript example, parseInt reads an integer prefix. The argument 10 selects decimal notation. It stops before the decimal point or the word “marks,” so both inputs can produce 35.
Number converts the whole numeric text instead. It preserves the fractional numeric value in '35.5' and produces NaN for '35 marks'. Integer-prefix parsing would silently discard information the school may need.
Use a parser when its format matches your task. It is not a universal validator. In particular, parseInt should not be chosen merely to make an unsuitable input stop producing an error.
JavaScript · local teaching example
console.log(Number('35.5'));
console.log(parseInt('35.5', 10));
console.log(parseInt('35 marks', 10));
console.log(Number('35 marks'));Expected output
35.5
35
35
NaNConverting the word false does not produce boolean false
In JavaScript, Boolean uses truthiness rules. A nonempty string such as 'false' converts to true. An empty string or numeric zero converts to false. The letters inside a nonempty string are not interpreted as a boolean instruction.
If a school form supplies a fixed yes/no choice, interpret those allowed options explicitly. Do not use Boolean(text) to decide whether a teacher typed “yes” or “no.” Unsupported choices still need validation. See JavaScript’s Boolean rules and truthy and falsy values.
JavaScript · local teaching example
console.log(Boolean('false'));
console.log(Boolean(''));
console.log(Boolean(0));
const permissionChoice = 'no';
console.log(permissionChoice === 'yes');Expected output
true
false
false
falseConversion may lose formatting that cannot be recovered
This complete JavaScript example converts the identifier '007' into a number and then back into text using String. The final text is '7', not the original identifier.
Once the numeric value has been created, it does not remember how many leading zeros were present. Keep identifiers as strings when their formatting matters. Likewise, discarding a fraction does not record the removed part for a future conversion.
JavaScript · local teaching example
const studentId = '007';
const numericId = Number(studentId);
const convertedBack = String(numericId);
console.log(studentId);
console.log(numericId);
console.log(convertedBack);Expected output
007
7
7A type assertion is not a numeric conversion
The word cast is used differently across languages. Some numeric casts create a converted value. A TypeScript type assertion instead tells the checker to treat a value as a stated type; it does not convert the runtime data.
This complete example uses TypeScript. The unknown annotation says the checker does not yet know what kind of value should be assumed. The as number assertion then asks it to trust a numeric interpretation without checking the text.
const enteredScience: unknown = '35';
const science = enteredScience as number;
console.log(science + 5);Expected output when the emitted JavaScript runs: 355. The original runtime value is still a string, so JavaScript joins text. A successfully checked assertion has not performed the conversion. Use a real conversion and validation when input is text, and do not use an assertion to hide a mismatch. See TypeScript’s assertion documentation.
Accept a genuine zero without accepting an empty entry
JavaScript · zero, empty and non-finite input
const enteredScience = '35';
const text = enteredScience.trim();
const science = Number(text);
if (text === '') {
console.log('Enter a mark.');
} else if (!Number.isFinite(science)) {
console.log('Enter a finite number.');
} else if (science < 0 || science > 50) {
console.log('Enter a mark from 0 to 50.');
} else {
console.log(science);
}Use the complete validator shown above. A teacher reports that zero marks should be accepted, but empty text should not. Explain whether the order of checks accomplishes this, then predict the output for '0', '' and 'Infinity'.
Worked answer
Text '0' is not empty; it converts to finite 0 and passes the range check, so it prints 0. Empty text fails the first branch and prints “Enter a mark.” Infinity fails the finite-number branch and prints “Enter a finite number.”
The program checks presence using text, not whether the numeric value is truthy. Testing only if (!science) would mix valid zero with missing input and would not implement the rule correctly.
Validate the result of later changes too
Conversion success is not task success. Numeric 55 is a successful conversion but an invalid mark out of 50. An initially valid mark of 49 would also exceed the maximum after a correction of five. Check results at the point where the school rule must hold.
A finite number can still be unsuitable. The school may require whole marks or a narrower range. Very large integers can exceed JavaScript Number’s safe precision, and fractional arithmetic has representation limits discussed in the basic types lesson.
These are teaching examples of supplied strings. They do not implement a real browser form, trusted server validation or saving records. A production application also enforces its input rules where data is accepted and stored. The lesson’s aim is to make the conversion and validation decisions explicit.
Check: what produced the surprising output?
JavaScript · conversion trace for this question
const enteredScience = '35';
console.log(enteredScience + 5);
const science = Number(enteredScience);
console.log(science + 5);
console.log(typeof enteredScience);Check: distinguish zero from missing input
JavaScript · presence and numeric validation
const enteredScience = '35';
const text = enteredScience.trim();
const science = Number(text);
if (text === '') {
console.log('Enter a mark.');
} else if (!Number.isFinite(science)) {
console.log('Enter a finite number.');
} else if (science < 0 || science > 50) {
console.log('Enter a mark from 0 to 50.');
} else {
console.log(science);
}Check: which operation actually changes the value’s type?
Convert deliberately and preserve the meaning of the input
Explicit conversion creates a value of another type. Automatic conversion follows the language’s operation rules. In JavaScript, quoted marks can join text with + until converted.
Check presence, finiteness and the task’s range separately. Preserve genuine zero, reject invalid input with a useful message, and remember that parsing or conversion can discard formatting or fractions. A TypeScript assertion is not a runtime conversion.
Explain how the validator handles blank text, zero and 55. Then continue to arithmetic operations. Review type checking when deciding which mistakes a tool can catch before execution.
Reaching the recap and completing the quizzes are separate milestones.