JavaScript Type Conversion Practice Programs with Solutions (31 Programs)

Practise JavaScript type conversion 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.

Advertisement

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 Type Conversion lesson first.

JavaScript Beginner Programs

1. String to number with Number()Beginner

Convert the strings '42', '3.14' and '' to numbers and print the results.

Show solution
console.log(Number('42'));
console.log(Number('3.14'));
console.log(Number(''));

Output

42
3.14
0

Explanation: Number() converts a whole string to a number. An empty string becomes 0.

2. Invalid number stringsBeginner

Convert '42px' and 'abc' with Number() and print the results.

Show solution
console.log(Number('42px'));
console.log(Number('abc'));

Output

NaN
NaN

Explanation: Number() returns NaN if any part of the string is not numeric.

3. parseInt and parseFloatBeginner

Read the leading number from '42px' with parseInt and from '3.75 kg' with parseFloat.

Show solution
console.log(parseInt('42px', 10));
console.log(parseFloat('3.75 kg'));
console.log(parseInt('px42', 10));

Output

42
3.75
NaN

Explanation: the parse functions read digits from the start and stop at the first invalid character. If the string does not start with a number, they return NaN.

4. Number to stringBeginner

Convert the number 404 to a string in three different ways and print the types.

Show solution
const code = 404;
const a = String(code);
const b = code.toString();
const c = `${code}`;
console.log(a, b, c);
console.log(typeof a, typeof b, typeof c);

Output

404 404 404
string string string

Explanation: String(), .toString() and template literals all produce a string.

5. Convert to booleanBeginner

Use Boolean() on 0, 1, '', '0' and 'false'.

Show solution
console.log(Boolean(0));
console.log(Boolean(1));
console.log(Boolean(''));
console.log(Boolean('0'));
console.log(Boolean('false'));

Output

false
true
false
true
true

Explanation: any non-empty string is truthy, even '0' and 'false'.

6. Unary plusBeginner

Convert '25' to a number with the unary + operator and add 5.

Show solution
const quantity = '25';
console.log(quantity + 5);
console.log(+quantity + 5);

Output

255
30

Explanation: without conversion + joins strings, giving '255'. Unary + converts the string first.

7. String concatenation coercionBeginner

Print the results of '5' + 3, '5' - 3, '5' * '2' and '10' / '2'.

Show solution
console.log('5' + 3);
console.log('5' - 3);
console.log('5' * '2');
console.log('10' / '2');

Output

53
2
10
5

Explanation: + prefers string concatenation, while -, * and / convert both sides to numbers.

8. Round and format numbersBeginner

Round 19.987 to two decimals as a string and as a number.

Show solution
const amount = 19.987;
const asString = amount.toFixed(2);
const asNumber = Number(asString);
console.log(asString, typeof asString);
console.log(asNumber, typeof asNumber);

Output

19.99 string
19.99 number

Explanation: toFixed returns a string. Wrap it with Number() when you need a number again.

9. Array to stringBeginner

Convert ['smoke', 'regression'] to a string using String() and join(' | ').

Show solution
const tags = ['smoke', 'regression'];
console.log(String(tags));
console.log(tags.join(' | '));

Output

smoke,regression
smoke | regression

Explanation: arrays convert to comma-separated strings. join lets you choose the separator.

10. String to arrayBeginner

Split 'chromium,firefox,webkit' into an array and print its length.

Show solution
const csv = 'chromium,firefox,webkit';
const browsers = csv.split(',');
console.log(browsers);
console.log(browsers.length);

Output

[ 'chromium', 'firefox', 'webkit' ]
3

Explanation: split converts a delimited string into an array of strings.

JavaScript Intermediate Programs

11. Loose vs strict equalityIntermediate

Compare 0 == '', 0 === '', '1' == 1 and null == 0.

Show solution
console.log(0 == '');
console.log(0 === '');
console.log('1' == 1);
console.log(null == 0);

Output

true
false
true
false

Explanation: == converts types before comparing, with some surprising rules. Prefer === in tests.

12. parseInt with a radixIntermediate

Parse '1010' as binary and 'ff' as hexadecimal, then convert 255 back to hex.

Show solution
console.log(parseInt('1010', 2));
console.log(parseInt('ff', 16));
console.log((255).toString(16));

Output

10
255
ff

Explanation: the second argument of parseInt is the base. toString(base) converts the other way.

13. Number() vs parseInt on decimalsIntermediate

Compare Number('12.9'), parseInt('12.9', 10) and Math.trunc(Number('12.9')).

Show solution
console.log(Number('12.9'));
console.log(parseInt('12.9', 10));
console.log(Math.trunc(Number('12.9')));

Output

12.9
12
12

Explanation: parseInt drops the decimal part. Use Number to keep it, or Math.trunc for an explicit integer.

14. Object to JSON and backIntermediate

Convert a test-config object to JSON text and parse it back.

Show solution
const config = { browser: 'chromium', retries: 2, headless: true };
const json = JSON.stringify(config);
console.log(json, typeof json);
const parsed = JSON.parse(json);
console.log(parsed.retries + 1);

Output

{"browser":"chromium","retries":2,"headless":true} string
3

Explanation: JSON.stringify turns data into text, for files or APIs. JSON.parse turns it back into objects with real numbers and booleans.

15. Pretty-print JSONIntermediate

Print an object as indented JSON with two spaces.

Show solution
const result = { test: 'login', status: 'passed' };
console.log(JSON.stringify(result, null, 2));

Output

{
  "test": "login",
  "status": "passed"
}

Explanation: the third argument of JSON.stringify adds indentation, which makes logs easier to read.

16. Values JSON cannot keepIntermediate

Stringify an object containing undefined, a function and NaN, and print the result.

Show solution
const data = { a: undefined, b: () => 1, c: NaN, d: 'ok' };
console.log(JSON.stringify(data));

Output

{"c":null,"d":"ok"}

Explanation: JSON drops undefined and functions, and turns NaN into null.

17. Date to timestamp and ISO stringIntermediate

Create a date from a fixed ISO string and print its timestamp and ISO form.

Show solution
const date = new Date('2026-01-15T10:30:00Z');
console.log(date.getTime());
console.log(date.toISOString());
console.log(new Date(0).toISOString());

Output

1768473000000
2026-01-15T10:30:00.000Z
1970-01-01T00:00:00.000Z

Explanation: getTime() gives milliseconds since 1 January 1970 UTC, and toISOString() gives a standard text format.

18. Object conversion with valueOfIntermediate

Create an object with valueOf and toString, then use it in maths and in a template literal.

Show solution
const price = {
  amount: 499,
  valueOf() { return this.amount; },
  toString() { return `₹${this.amount}`; }
};
console.log(price + 1);
console.log(`${price}`);

Output

500
₹499

Explanation: maths calls valueOf, while template literals call toString.

19. Number checks: isNaN vs Number.isNaNIntermediate

Compare isNaN('abc') with Number.isNaN('abc').

Show solution
console.log(isNaN('abc'));
console.log(Number.isNaN('abc'));
console.log(Number.isNaN(Number('abc')));

Output

true
false
true

Explanation: global isNaN converts its argument first. Number.isNaN only returns true for the actual NaN value.

20. Map and object conversionsIntermediate

Convert an object into a Map and back again.

Show solution
const scores = { login: 95, checkout: 80 };
const map = new Map(Object.entries(scores));
console.log(map.get('checkout'));
const back = Object.fromEntries(map);
console.log(back);

Output

80
{ login: 95, checkout: 80 }

Explanation: Object.entries and Object.fromEntries convert between plain objects and key/value pairs.

JavaScript Real-World QA Scenario Programs

21. Parse a price from page textReal-world

Extract the number from the UI text '₹1,299.50'.

Show solution
const priceText = '₹1,299.50';
const price = Number(priceText.replace(/[^0-9.]/g, ''));
console.log(price);
console.log(price + 100);

Output

1299.5
1399.5

Explanation: remove currency symbols and thousands separators, then convert. UI text is always a string.

22. Sum prices read from the pageReal-world

A test reads cart prices as strings. Convert and sum them.

Show solution
const priceTexts = ['$12.50', '$7.25', '$30.00'];
const total = priceTexts
  .map(text => Number(text.replace('$', '')))
  .reduce((sum, value) => sum + value, 0);
console.log(total.toFixed(2));

Output

49.75

Explanation: summing the raw strings would concatenate them, so convert each to a number first.

23. Read numeric environment variablesReal-world

Convert the environment values '4' and undefined to a worker count with a default of 2.

Show solution
const env = { WORKERS: '4' };
const workers = Number(env.WORKERS ?? 2);
const retries = Number(env.RETRIES ?? 0);
console.log(workers, typeof workers);
console.log(retries);

Output

4 number
0

Explanation: environment variables are always strings or missing. Convert them and provide defaults.

24. Parse a boolean flag safelyReal-world

Turn HEADLESS values such as 'true', 'false', '1' and undefined into booleans.

Show solution
const toBool = value => ['true', '1', 'yes'].includes(String(value).toLowerCase());
console.log(toBool('true'));
console.log(toBool('false'));
console.log(toBool('1'));
console.log(toBool(undefined));

Output

true
false
true
false

Explanation: Boolean('false') is true, so compare against known true values instead.

25. Parse CSV rows into typed objectsReal-world

Convert a CSV line 'qa_user,25,true' into an object with a string, number and boolean.

Show solution
const line = 'qa_user,25,true';
const [username, age, active] = line.split(',');
const user = { username, age: Number(age), active: active === 'true' };
console.log(user);

Output

{ username: 'qa_user', age: 25, active: true }

Explanation: CSV fields are text, so convert each column to the type your test expects.

26. Compare an API number with UI textReal-world

The API returns 1299 and the UI shows '1,299'. Compare them correctly.

Show solution
const apiPrice = 1299;
const uiText = '1,299';
console.log(apiPrice === uiText);
console.log(apiPrice === Number(uiText.replace(/,/g, '')));

Output

false
true

Explanation: normalise the UI text into a number before comparing it with API data.

27. Convert durationsReal-world

Convert a test duration of 125430 ms into minutes and seconds.

Show solution
const durationMs = 125430;
const totalSeconds = Math.floor(durationMs / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
console.log(`${minutes}m ${String(seconds).padStart(2, '0')}s`);

Output

2m 05s

Explanation: integer division with Math.floor and % converts a raw number into a readable duration.

28. Read numbers from a sentenceReal-world

Extract all numbers from 'Passed 45 of 50 tests in 12.5 seconds'.

Show solution
const summary = 'Passed 45 of 50 tests in 12.5 seconds';
const numbers = summary.match(/\d+(\.\d+)?/g).map(Number);
console.log(numbers);
console.log(numbers[0] / numbers[1]);

Output

[ 45, 50, 12.5 ]
0.9

Explanation: match with a global regular expression finds every number as a string, and map(Number) converts them.

29. Normalise mixed input typesReal-world

A form sends quantities as 5, '7', '' and null. Convert them to numbers, treating empty values as 0.

Show solution
const inputs = [5, '7', '', null, '3'];
const quantities = inputs.map(value => (value === '' || value == null ? 0 : Number(value)));
console.log(quantities);
console.log(quantities.reduce((a, b) => a + b, 0));

Output

[ 5, 7, 0, 0, 3 ]
15

Explanation: decide explicitly how empty values convert, rather than relying on implicit coercion.

30. Format a number as currency textReal-world

Format 1234567.891 as a US dollar amount and an Indian rupee amount.

Show solution
const amount = 1234567.891;
console.log(amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));
console.log(amount.toLocaleString('en-IN', { style: 'currency', currency: 'INR' }));

Output

$1,234,567.89
₹12,34,567.89

Explanation: toLocaleString converts numbers into locale-aware text, which is useful when asserting formatted prices.

31. Query string to objectReal-world

Convert the query string '?page=2&sort=price&inStock=true' into an object with typed values.

Show solution
const params = new URLSearchParams('?page=2&sort=price&inStock=true');
const query = {
  page: Number(params.get('page')),
  sort: params.get('sort'),
  inStock: params.get('inStock') === 'true'
};
console.log(query);

Output

{ page: 2, sort: 'price', inStock: true }

Explanation: URLSearchParams returns every value as a string, so convert numbers and booleans yourself.

Keep Practising

Leave a Comment