Lesson goal: Check a value’s type and make simple conversions.
typeofconsole.log(typeof "Aman");
console.log(typeof 60);
console.log(typeof true);
console.log(typeof undefined);
string
number
boolean
undefined
typeof returns a string describing the type.
You can also check a named value:
const notebookPrice = 60;
console.log(typeof notebookPrice);
number
nullconsole.log(typeof null);
object
null is still a primitive value representing absence.To check specifically for null, use:
const selectedCourse = null;
console.log(selectedCourse === null);
true
=== in the next lesson.Why conversion matters
Values read from an HTML input’s .value property are strings. Even if someone types digits, your code often needs to convert them before calculating.
Consider:
const firstValue = "60";
const secondValue = "3";
console.log(firstValue + secondValue);
603
+ joins the strings.Convert text to a number
Use Number():
const priceText = "60";
const quantityText = "3";
const price = Number(priceText);
const quantity = Number(quantityText);
console.log(price * quantity);
180
When conversion fails
const price = Number("sixty");
console.log(price);
NaN
NaN means Not-a-Number. It represents an invalid numeric result.
Check it using:
console.log(Number.isNaN(price));
true
console.log(typeof NaN);
number
typeof alone does not prove that a number is usable. Number.isFinite() checks whether a value is a finite number:console.log(Number.isFinite(60));
console.log(Number.isFinite(NaN));
true
false
console.log(Number(""));
console.log(Number(" "));
0.When we build forms later, we will check for empty input before converting it.
Convert a value to text
Use String():
const studentCode = 101;
const codeText = String(studentCode);
console.log(codeText);
console.log(typeof codeText);
101
string
console.log(Boolean(1));
console.log(Boolean(0));
console.log(Boolean(""));
console.log(Boolean("hello"));
true
false
false
true
true, including the string "false":console.log(Boolean("false"));
true
Boolean() checks whether a value is truthy or falsy. It does not interpret the meaning of words.
Convert "25" and "5" into numbers and add them.
Solution:
const firstNumber = Number("25");
const secondNumber = Number("5");
console.log(firstNumber + secondNumber);
30
Use typeof to inspect types and Number(), String(), or Boolean() to convert values. Watch for failed numeric conversions and empty strings.