Practise JavaScript data types with 31 programs, each with a full solution, the exact output and a short explanation. The programs start with the basics, move to intermediate problems and finish with real-world scenarios from test automation, such as test data, prices, form inputs and test results. They are written for testers learning JavaScript for Playwright.
How to practise: read the task, write your own solution first, then open Show solution to compare. Run any program with node program.js.
New to this topic? Read the JavaScript Data Types lesson first.
- Beginner programs (1–10)
- Intermediate programs (11–20)
- Real-world QA scenario programs (21–31)
JavaScript Beginner Programs
1. Print the type of each primitiveBeginner
Use typeof to print the type of a string, number, boolean, undefined, bigint and symbol.
Show solution
console.log(typeof 'Playwright');
console.log(typeof 42);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof 10n);
console.log(typeof Symbol('id'));
Output
string
number
boolean
undefined
bigint
symbol
Explanation: typeof returns a string naming the type. These six, plus null, are JavaScript’s primitive types.
2. typeof nullBeginner
Print typeof null and explain the result in a comment.
Show solution
const value = null;
console.log(typeof value);
console.log(value === null);
Output
object
true
Explanation: typeof null returns 'object' because of an old bug kept for compatibility. Check for null with === null.
3. Arrays and functions with typeofBeginner
Print typeof for an array, an object and a function.
Show solution
console.log(typeof ['chromium', 'firefox']);
console.log(typeof { retries: 2 });
console.log(typeof function login() {});
Output
object
object
function
Explanation: arrays are objects, so typeof returns 'object'. Functions are a special case and return 'function'.
4. Check for an arrayBeginner
Use Array.isArray to tell an array apart from a plain object.
Show solution
const browsers = ['chromium', 'webkit'];
const config = { browser: 'chromium' };
console.log(Array.isArray(browsers));
console.log(Array.isArray(config));
Output
true
false
Explanation: Array.isArray is the reliable array check, because typeof returns 'object' for both.
5. Integer or decimalBeginner
Check whether 10, 10.5 and -3 are integers.
Show solution
console.log(Number.isInteger(10));
console.log(Number.isInteger(10.5));
console.log(Number.isInteger(-3));
Output
true
false
true
Explanation: JavaScript has one number type for integers and decimals. Number.isInteger checks for whole numbers.
6. NaN is a numberBeginner
Divide a string by a number, then print the result, its type and whether it is NaN.
Show solution
const result = 'abc' / 2;
console.log(result);
console.log(typeof result);
console.log(Number.isNaN(result));
Output
NaN
number
true
Explanation: invalid maths produces NaN (“Not a Number”), which is still of type number.
7. InfinityBeginner
Print the results of dividing 1 by 0 and -1 by 0, and their type.
Show solution
console.log(1 / 0);
console.log(-1 / 0);
console.log(typeof Infinity);
Output
Infinity
-Infinity
number
Explanation: dividing by zero gives Infinity or -Infinity instead of an error.
8. Boolean values from comparisonsBeginner
Store the results of three comparisons in variables and print them with their type.
Show solution
const isPassed = 85 >= 70;
const isEmpty = ''.length === 0;
const isAdmin = 'viewer' === 'admin';
console.log(isPassed, isEmpty, isAdmin);
console.log(typeof isPassed);
Output
true true false
boolean
Explanation: comparison operators always produce a boolean, true or false.
9. null vs undefinedBeginner
Compare null and undefined with == and ===.
Show solution
let notAssigned;
const emptyValue = null;
console.log(notAssigned == emptyValue);
console.log(notAssigned === emptyValue);
Output
true
false
Explanation: loose equality treats null and undefined as equal. Strict equality also compares types, so they differ.
10. String length and charactersBeginner
Print the length of 'Playwright', its first character and its last character.
Show solution
const tool = 'Playwright';
console.log(tool.length);
console.log(tool[0]);
console.log(tool[tool.length - 1]);
Output
10
P
t
Explanation: strings have a length property and characters can be read by index, starting at 0.
JavaScript Intermediate Programs
11. Floating-point precisionIntermediate
Print 0.1 + 0.2, compare it with 0.3, then compare safely using a tolerance.
Show solution
const sum = 0.1 + 0.2;
console.log(sum);
console.log(sum === 0.3);
console.log(Math.abs(sum - 0.3) < Number.EPSILON);
Output
0.30000000000000004
false
true
Explanation: decimals are stored in binary floating point, so some sums are slightly off. Compare with a tolerance instead.
12. Safe integer limitsIntermediate
Print the largest safe integer and show that adding 1 and 2 to it gives the same result.
Show solution
const max = Number.MAX_SAFE_INTEGER;
console.log(max);
console.log(max + 1 === max + 2);
console.log(Number.isSafeInteger(max + 1));
Output
9007199254740991
true
false
Explanation: beyond 2^53 − 1, numbers lose precision, so different integers can become equal.
13. BigInt for large IDsIntermediate
Store a large order ID as a BigInt, add 1 and print it.
Show solution
const orderId = 9007199254740993n;
const nextId = orderId + 1n;
console.log(nextId);
console.log(typeof nextId);
Output
9007199254740994n
bigint
Explanation: BigInt (numbers ending in n) stores arbitrarily large integers exactly. You cannot mix BigInt and number in maths.
14. Mixing BigInt and numberIntermediate
Try adding a BigInt to a number and print the error message, then do it correctly.
Show solution
try {
console.log(10n + 5);
} catch (error) {
console.log(error.name);
}
console.log(10n + BigInt(5));
Output
TypeError
15n
Explanation: mixing types throws a TypeError. Convert explicitly with BigInt() or Number().
15. Symbols are uniqueIntermediate
Create two symbols with the same description and compare them.
Show solution
const id1 = Symbol('testId');
const id2 = Symbol('testId');
console.log(id1 === id2);
console.log(id1.description);
Output
false
testId
Explanation: every Symbol() call creates a unique value, even with the same description.
16. Primitives are immutableIntermediate
Try to change the first character of a string and print it.
Show solution
let browser = 'chromium';
browser[0] = 'C';
console.log(browser);
browser = browser[0].toUpperCase() + browser.slice(1);
console.log(browser);
Output
chromium
Chromium
Explanation: you cannot change a string in place. Methods return a new string, which you assign back to the variable.
17. Truthy and falsy valuesIntermediate
Print whether each value in a list is truthy or falsy.
Show solution
const samples = [
[0, '0'], ['', "''"], ['qa', "'qa'"], [null, 'null'], [undefined, 'undefined'],
[NaN, 'NaN'], [[], '[]'], [{}, '{}'], [-1, '-1']
];
for (const [value, label] of samples) {
console.log(label, '->', value ? 'truthy' : 'falsy');
}
Output
0 -> falsy
'' -> falsy
'qa' -> truthy
null -> falsy
undefined -> falsy
NaN -> falsy
[] -> truthy
{} -> truthy
-1 -> truthy
Explanation: 0, '', null, undefined, NaN and false are falsy. Empty arrays and objects are truthy.
18. Detect the real typeIntermediate
Write a function that returns 'null', 'array' or the typeof result, and test it with several values.
Show solution
function getType(value) {
if (value === null) return 'null';
if (Array.isArray(value)) return 'array';
return typeof value;
}
console.log(getType(null));
console.log(getType([1, 2]));
console.log(getType({}));
console.log(getType('text'));
Output
null
array
object
string
Explanation: combining checks fixes the two surprises of typeof: null and arrays.
19. Object.prototype.toString type checkIntermediate
Print the internal type tag of a date, an array, null and a regular expression.
Show solution
const tag = value => Object.prototype.toString.call(value);
console.log(tag(new Date(0)));
console.log(tag([]));
console.log(tag(null));
console.log(tag(/test/));
Output
[object Date]
[object Array]
[object Null]
[object RegExp]
Explanation: Object.prototype.toString returns a precise tag such as [object Date], useful for robust type checks.
20. Compare by value vs by referenceIntermediate
Compare two identical arrays with ===, then compare their JSON strings.
Show solution
const expected = ['login', 'logout'];
const actual = ['login', 'logout'];
console.log(expected === actual);
console.log(JSON.stringify(expected) === JSON.stringify(actual));
Output
false
true
Explanation: === compares object references, not contents. For simple data, comparing JSON strings checks the values.
JavaScript Real-World QA Scenario Programs
21. Validate API field typesReal-world
Check that each field in an API user object has the expected type and print any mismatch.
Show solution
const user = { id: 101, name: 'Asha', active: 'yes', tags: ['qa'] };
const schema = { id: 'number', name: 'string', active: 'boolean', tags: 'array' };
for (const [field, expected] of Object.entries(schema)) {
const value = user[field];
const actual = Array.isArray(value) ? 'array' : typeof value;
if (actual !== expected) console.log(`${field}: expected ${expected}, got ${actual}`);
}
console.log('Type check finished');
Output
active: expected boolean, got string
Type check finished
Explanation: simple schema checks catch API contract bugs early, such as a boolean sent as the string 'yes'.
22. Count values by typeReal-world
Count how many values of each type a response array contains.
Show solution
const response = [1, 'two', 3, null, true, 'six', undefined, 8];
const counts = {};
for (const value of response) {
const type = value === null ? 'null' : typeof value;
counts[type] = (counts[type] || 0) + 1;
}
console.log(counts);
Output
{ number: 3, string: 2, null: 1, boolean: 1, undefined: 1 }
Explanation: grouping by type helps spot unexpected data, such as nulls in a numeric column.
23. Check for missing valuesReal-world
Report which form fields are empty, null or undefined.
Show solution
const form = { firstName: 'Ravi', lastName: '', email: null, phone: undefined, city: 'Pune' };
const missing = Object.keys(form).filter(key => form[key] === '' || form[key] == null);
console.log('Missing fields:', missing.join(', '));
Output
Missing fields: lastName, email, phone
Explanation: == null matches both null and undefined, and === '' catches empty strings.
24. Verify a price is a valid numberReal-world
Check a list of prices and print whether each one is a finite, non-negative number.
Show solution
const prices = [499, -10, NaN, Infinity, 0, '299'];
for (const price of prices) {
const valid = typeof price === 'number' && Number.isFinite(price) && price >= 0;
console.log(String(price), valid ? 'valid' : 'invalid');
}
Output
499 valid
-10 invalid
NaN invalid
Infinity invalid
0 valid
299 invalid
Explanation: Number.isFinite rejects NaN and Infinity, and the typeof check rejects numbers stored as strings.
25. Optional response fieldsReal-world
Read a nested optional field safely and fall back to a default.
Show solution
const responseA = { user: { address: { city: 'Mumbai' } } };
const responseB = { user: {} };
console.log(responseA.user.address?.city ?? 'Unknown');
console.log(responseB.user.address?.city ?? 'Unknown');
Output
Mumbai
Unknown
Explanation: optional chaining returns undefined instead of throwing when a property is missing, and ?? supplies a default.
26. Identify boolean-like stringsReal-world
Convert the CSV values 'true', 'false' and 'TRUE' to real booleans and print their type.
Show solution
const csvValues = ['true', 'false', 'TRUE'];
for (const text of csvValues) {
const bool = text.toLowerCase() === 'true';
console.log(text, '->', bool, typeof bool);
}
Output
true -> true boolean
false -> false boolean
TRUE -> true boolean
Explanation: Boolean('false') would be true because the string is non-empty, so compare the text instead.
27. Detect empty arrays and objectsReal-world
Write checks that report whether an API returned an empty list or an empty object.
Show solution
const isEmptyArray = value => Array.isArray(value) && value.length === 0;
const isEmptyObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === 0;
console.log(isEmptyArray([]), isEmptyArray([1]));
console.log(isEmptyObject({}), isEmptyObject({ id: 1 }));
Output
true false
true false
Explanation: empty arrays and objects are truthy, so you must check length or Object.keys explicitly.
28. Copy test data safelyReal-world
Make a deep copy of nested test data with structuredClone, change the copy and show the original is unchanged.
Show solution
const baseUser = { name: 'Asha', roles: ['viewer'] };
const adminUser = structuredClone(baseUser);
adminUser.roles.push('admin');
console.log(baseUser.roles);
console.log(adminUser.roles);
Output
[ 'viewer' ]
[ 'viewer', 'admin' ]
Explanation: structuredClone copies nested objects too, so changing the copy does not leak into shared test data.
29. Spread creates a shallow copyReal-world
Copy an object with spread, change a nested array and observe the side effect.
Show solution
const original = { name: 'cart', items: ['pen'] };
const copy = { ...original };
copy.name = 'wishlist';
copy.items.push('book');
console.log(original.name, original.items);
Output
cart [ 'pen', 'book' ]
Explanation: spread copies only the top level. Nested arrays and objects are still shared between the copies.
30. Summarise data types in test dataReal-world
Print a one-line summary of the type of each property in a test case object.
Show solution
const testCase = { id: 'TC-101', priority: 1, automated: true, tags: ['smoke'], owner: null };
const summary = Object.entries(testCase)
.map(([key, value]) => `${key}:${value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value}`)
.join(' | ');
console.log(summary);
Output
id:string | priority:number | automated:boolean | tags:array | owner:null
Explanation: a quick type summary is handy when debugging data loaded from JSON or CSV files.
31. Validate a status code typeReal-world
An API returns its status as a string. Show why === comparison with a number fails, and fix it.
Show solution
const response = { status: '200' };
console.log(response.status === 200);
console.log(Number(response.status) === 200);
console.log(typeof response.status);
Output
false
true
string
Explanation: strict equality compares types, so '200' === 200 is false. Convert explicitly before comparing.
2 thoughts on “JavaScript Data Types Practice Programs with Solutions (31 Programs)”