JavaScript Data Types
Introduction to Data Types
JavaScript has two main categories of data types:
- Primitive — data stored directly in memory (stack)
- Non-Primitive — data stored as a reference (heap)
Primitive Types (7 Types)
1. String
A String is a data type for text/characters, written with quotes (', ", or `).
// String declaration
let name = "John Smith"; // double quotes
let studentId = '2024100123'; // single quotes
let message = `Hello, ${name}!`; // template literal (backtick)
console.log(typeof name); // "string"
console.log(name.length); // 13
2. Number
Number is a data type for numbers, both integers and floats.
// Number declaration
let semester = 3; // integer
let gpa = 3.75; // float
let negative = -85; // negative
let infinity = Infinity; // infinity
let notANumber = NaN; // result of an invalid operation
console.log(typeof semester); // "number"
console.log(typeof gpa); // "number"
// NaN
console.log(typeof NaN); // "number" (still a number!)
console.log(NaN === NaN); // false
console.log(isNaN("abc")); // true
console.log(Number.isNaN(NaN)); // true (stricter)
3. Boolean
A Boolean has only two values: true or false.
// Boolean declaration
let active = true;
let passed = false;
console.log(typeof active); // "boolean"
// Used in an academic portal
let paymentStatus = true;
let hasRegistered = false;
if (paymentStatus && hasRegistered) {
console.log("You may take the exam.");
} else if (paymentStatus && !hasRegistered) {
console.log("Please register first.");
} else {
console.log("Please pay the tuition first.");
}
4. Null
null is an intentional "nothing" (the intent of having no value).
// Null declaration
let examScore = null; // No score yet
let advisor = null; // Not determined yet
console.log(typeof examScore); // "object" (a bug in JavaScript!)
console.log(examScore === null); // true
5. Undefined
undefined is a "nothing" because it has not been given a value yet.
// Undefined declaration
let studentName;
console.log(studentName); // undefined
// Function without a return
function checkStatus() {
let status = "active";
// no return
}
console.log(checkStatus()); // undefined
console.log(typeof undefined); // "undefined"
6. Symbol
Symbol is a unique and immutable data type, introduced in ES6.
// Symbol declaration
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 === id2); // false — always unique!
console.log(typeof id1); // "symbol"
// Used as a unique property key
const STUDENT_ID = Symbol("studentId");
const student = {
[STUDENT_ID]: "2024100123",
name: "John Smith"
};
console.log(student[STUDENT_ID]); // "2024100123"
console.log(student.name); // "John Smith"
7. BigInt
BigInt was introduced in ES2020 for numbers larger than Number.MAX_SAFE_INTEGER.
// BigInt declaration
let bigNumber = 9007199254740991n; // with the 'n' suffix
let bigNumber2 = BigInt("9007199254740991"); // with the BigInt() function
console.log(typeof bigNumber); // "bigint"
// Number vs BigInt
let maxNumber = Number.MAX_SAFE_INTEGER;
console.log(maxNumber); // 9007199254740991
console.log(maxNumber + 1); // 9007199254740992 (wrong!)
console.log(bigNumber + 1n); // 9007199254740992n (correct!)
// Usage: a very long student ID
const LONG_STUDENT_ID = BigInt("2024100123456789012345");
console.log(LONG_STUDENT_ID); // 2024100123456789012345n
Non-Primitive Types
1. Object
An Object is a collection of data in the form of key-value pairs.
// Object declaration
let student = {
studentId: "2024100123",
name: "John Smith",
major: "Computer Science",
gpa: 3.75,
hobbies: ["reading", "coding", "playing chess"]
};
console.log(typeof student); // "object"
console.log(student.name); // "John Smith"
console.log(student.hobbies[0]); // "reading"
2. Array
An Array is a special object for storing ordered data.
// Array declaration
let courseList = [
"Web Programming",
"Database",
"Algorithms",
"Computer Networks"
];
console.log(typeof courseList); // "object"
console.log(Array.isArray(courseList)); // true
console.log(courseList.length); // 4
3. Function
A Function is an executable code block.
// Function declaration
function calcAverage(score1, score2, score3) {
return (score1 + score2 + score3) / 3;
}
console.log(typeof calcAverage); // "function"
console.log(calcAverage(85, 90, 78)); // 84.33...
The typeof Operator
typeof is used to check a variable's data type.
// Usage of typeof
console.log(typeof "John"); // "string"
console.log(typeof 3.75); // "number"
console.log(typeof true); // "boolean"
console.log(typeof null); // "object" (a BUG!)
console.log(typeof undefined); // "undefined"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof 100n); // "bigint"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
// Function to check a type correctly
function checkType(data) {
if (data === null) return "null";
if (Array.isArray(data)) return "array";
if (typeof data === "object") return "object";
return typeof data;
}
console.log(checkType(null)); // "null"
console.log(checkType([1, 2, 3])); // "array"
console.log(checkType({})); // "object"
console.log(checkType("hello")); // "string"
Type Coercion (Automatic Type Conversion)
JavaScript automatically converts data types in certain operations.
// Implicit coercion
console.log("5" + 3); // "53" (number → string)
console.log("5" - 3); // 2 (string → number)
console.log(true + 1); // 2 (boolean → number)
console.log(false + "5"); // "false5" (boolean → string)
// Explicit coercion
let scoreString = "85";
let scoreNumber = Number(scoreString); // 85
let asString = String(scoreNumber); // "85"
let booleanTrue = Boolean(1); // true
let booleanFalse = Boolean(0); // false
console.log(scoreString + 10); // "8510" (string concatenation)
console.log(scoreNumber + 10); // 95 (number addition)
Case Study: Data Types of Fields in a Student Registration Form
// === NEW STUDENT REGISTRATION FORM ===
const registrationForm = {
// String — Student ID must be 10 digits
studentId: "2024100123",
// String — full name
fullName: "John Smith",
// String — university email
email: "[email protected]",
// Number — year of birth
birthYear: 2002,
// Number — entrance exam score
entranceExamScore: 685,
// Boolean — recipient of student financial aid?
financialAid: false,
// Boolean — person with a disability?
disability: false,
// String — gender
gender: "Male",
// String — address
address: "123 Main Street, New York",
// Null — no photo yet (not uploaded)
profilePhoto: null,
// String — selected study program
studyProgram: "Computer Science",
// Array of strings — exams already taken
examsTaken: ["College Entrance Exam", "Independent Exam"],
// Object — parent data
parents: {
fatherName: "Smith",
fatherOccupation: "Self-employed",
motherName: "Mary",
motherOccupation: "Teacher"
},
// Undefined — no final decision yet
finalDecision: undefined
};
// === VALIDATION FUNCTIONS BASED ON DATA TYPE ===
function validateForm(form) {
const error = [];
// Check student ID — must be a string, 10 characters, all digits
if (typeof form.studentId !== "string") {
error.push("Student ID must be a string!");
} else if (form.studentId.length !== 10) {
error.push("Student ID must be 10 characters!");
} else if (!/^\d{10}$/.test(form.studentId)) {
error.push("Student ID must be digits!");
}
// Check name — must be a string, at least 3 characters
if (typeof form.fullName !== "string") {
error.push("Name must be a string!");
} else if (form.fullName.length < 3) {
error.push("Name must be at least 3 characters!");
}
// Check year of birth — must be a number, between 1980 and 2010
if (typeof form.birthYear !== "number") {
error.push("Year of birth must be a number!");
} else if (form.birthYear < 1980 || form.birthYear > 2010) {
error.push("Year of birth is not valid!");
}
// Check entrance exam score — must be a number, between 0 and 900
if (typeof form.entranceExamScore !== "number") {
error.push("Entrance exam score must be a number!");
} else if (form.entranceExamScore < 0 || form.entranceExamScore > 900) {
error.push("Entrance exam score is not valid!");
}
// Check financial aid — must be a boolean
if (typeof form.financialAid !== "boolean") {
error.push("Financial aid status must be a boolean!");
}
// Check photo — must be null (not uploaded) or a string (uploaded)
if (form.profilePhoto !== null && typeof form.profilePhoto !== "string") {
error.push("Photo format is not valid!");
}
// Check exams — must be an array
if (!Array.isArray(form.examsTaken)) {
error.push("Exam list must be an array!");
}
// Check parents — must be an object
if (typeof form.parents !== "object" || form.parents === null) {
error.push("Parent data must be an object!");
}
return {
valid: error.length === 0,
errors: error
};
}
const validationResult = validateForm(registrationForm);
console.log("Valid:", validationResult.valid); // true
console.log("Errors:", validationResult.errors); // []
// Summary of data types in the form
console.log("\n=== DATA TYPES SUMMARY ===");
Object.entries(registrationForm).forEach(([key, value]) => {
let type;
if (value === null) type = "null";
else if (Array.isArray(value)) type = "array";
else type = typeof value;
console.log(`${key}: ${type}`);
});
Summary
| Category | Type | typeof |
Example |
|---|---|---|---|
| Primitive | String | "string" |
"John" |
| Number | "number" |
3.75, -85 |
|
| Boolean | "boolean" |
true, false |
|
| Null | "object" (bug!) |
null |
|
| Undefined | "undefined" |
undefined |
|
| Symbol | "symbol" |
Symbol("id") |
|
| BigInt | "bigint" |
100n |
|
| Non-Primitive | Object | "object" |
{} |
| Array | "object" |
[] |
|
| Function | "function" |
function(){} |
Understanding data types is very important for writing correct code and avoiding bugs, especially ones related to type coercion, which can be surprising.