JavaScript Numbers & Dates Interview Questions and Answers

Review numeric conversion, floating-point behavior, NaN, and JavaScript date and time operations.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

This is a classic JavaScript trick question. typeof NaN returns "number". Yes, "Not a Number" is technically a number. It exists because NaN is the result of failed numeric operations (like 0/0 or parseInt("hello")), and the IEEE 754 floating-point spec defines it as part of the number type. Another gotcha: NaN !== NaN, so use Number.isNaN() to check for it.

javascript

console.log(typeof NaN); //number

Infinity is a special numeric value in JavaScript that represents a number beyond the largest representable value. You'll see it when you divide by zero (10/0 gives Infinity) or when a calculation overflows. There's also -Infinity for the opposite direction. A practical tip: you can use Infinity as an initial value when searching for a minimum in an array, since any real number will be smaller.

javascript

console.log(10/0); //Infinity

This trips up everyone - JavaScript uses 64-bit IEEE 754 floating-point, and 0.1 in binary is a repeating fraction, just like 1/3 in decimal. So when you add them, you get 0.30000000000000004. Never use == to compare floats directly - round with toFixed() for display, or check if the difference is smaller than Number.EPSILON for logic comparisons.

console.log(0.1 + 0.2); // 0.30000000000000004

// Fix: use toFixed() to round
console.log((0.1 + 0.2).toFixed(1)); // "0.3"

parseInt() stops at the decimal point and gives you a whole number, while parseFloat() keeps it. Both are lenient - they'll parse '3.99px' without throwing an error, which is handy when dealing with CSS values. Just remember to always pass a radix (like 10) to parseInt() to avoid surprises with octal or hex interpretation.

console.log(parseInt("3.99px"));   // 3   (integer only)
console.log(parseFloat("3.99px")); // 3.99 (keeps decimals)

console.log(parseInt("abc"));      // NaN
console.log(parseFloat("abc"));    // NaN

Without a radix, older JavaScript engines could interpret strings starting with '0' as octal, which is rarely what you want. Always pass 10 as the second argument when parsing user input or decimal strings - it makes the intent obvious and avoids cross-browser inconsistencies. When you actually need hex or binary parsing, pass 16 or 2 explicitly.

console.log(parseInt("10", 10)); // 10
console.log(parseInt("10", 2));  // 2
console.log(parseInt("0x10", 16)); // 16

Infinity is what you get when a number overflows or you divide a positive number by zero. Unlike most languages, JavaScript doesn't throw on divide-by-zero - it silently returns Infinity, which can cause bugs that are hard to trace. Always use Number.isFinite() to validate numeric results if you're doing divisions or working with user-supplied math.

console.log(1 / 0);   // Infinity
console.log(-1 / 0);  // -Infinity
console.log(Infinity + 1); // Infinity

console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite(100));      // true

Use the Intl.NumberFormat API - it handles all the locale differences like decimal separators, grouping, and currency symbols automatically. Don't roll your own formatting logic. For one-off cases number.toLocaleString('en-US', { style: 'currency', currency: 'USD' }) works fine, but if you're formatting many numbers in a hot path, create an Intl.NumberFormat instance once and reuse it - constructing it is the expensive part.

const num = 1234567.89;

// US format
console.log(new Intl.NumberFormat("en-US").format(num));
// 1,234,567.89

// Currency
console.log(new Intl.NumberFormat("en-US", {
  style: "currency", currency: "USD"
}).format(num));
// $1,234,567.89

JavaScript has only one number type - all numbers, whether integers or decimals, are stored as 64-bit IEEE 754 floating-point values. This means integers up to 2^53 are represented exactly, but beyond that you lose precision. Special numeric values include NaN (invalid operation), Infinity (overflow or divide by zero), and -Infinity. For integers larger than 2^53, use BigInt.

Internally all JavaScript numbers are 64-bit IEEE 754 floats, but you can write numeric literals in different bases: hex with 0x prefix, octal with 0o, and binary with 0b. These are just different ways to write the same underlying number. Hex is common for colors and bit masks, binary for flags, and octal occasionally for file permissions. They're all just number type at runtime.

toFixed(n) rounds and formats to n decimal places as a string - useful for displaying currency, but remember it returns a string so don't do math on it afterward. toString(base) converts to a string in any base, so (255).toString(16) gives 'ff'. Number.parseInt() and Number.parseFloat() are the same as the global versions. Number.isNaN() is the safe NaN check, and valueOf() is rarely called directly - it's used internally by JavaScript during type coercion.

`Number.isNaN(value)` returns true only when the value is the numeric `NaN`, without coercion. Global `isNaN()` first converts its argument to a number, so values such as `"text"` also produce true.

JavaScript `Number` uses IEEE 754 binary floating-point, and many decimal fractions have no exact finite binary representation. For currency, use integer minor units or a decimal arithmetic approach rather than comparing rounded binary fractions directly.

It confirms a value is an integer whose magnitude is within the range where adjacent integers are exactly distinguishable as JavaScript `Number` values. Larger exact integer calculations require `BigInt` or another representation.

An invalid `Date` has a timestamp of `NaN`; check `Number.isNaN(date.getTime())`. Many date getters return `NaN` for invalid dates, while converting the date to ISO text can throw a `RangeError`.

Non-standard date strings can be parsed inconsistently across environments, and date-only versus date-time strings can have different time-zone semantics. Use a well-defined ISO format and make the intended time zone explicit.

Local days can be shorter or longer than 24 hours around daylight-saving transitions. For calendar-day operations use date components or a date-time API with explicit zone semantics rather than assuming a fixed millisecond duration.

JavaScript Practical and Coding Interview Questions

Problem: Write a function that distinguishes the numeric NaN value from a string containing non-numeric text.

javascript

function isNaNValue(value) {
  return Number.isNaN(value);
}

console.log(isNaNValue(NaN));
console.log(isNaNValue('not a number'));

Problem: Construct a Date for a fixed UTC instant, then log its ISO representation.

javascript

const date = new Date('2024-01-02T15:04:00Z');
console.log(date.toISOString());

Problem: Format 1234.5 as US dollars and a fixed UTC date as a readable date without depending on the machine's local time zone.

javascript

const amount = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
}).format(1234.5);
const date = new Date('2024-01-02T15:04:00Z');
const dateLabel = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'medium',
  timeZone: 'UTC',
}).format(date);
console.log(amount, dateLabel);

Problem: Write a function that returns true only for prime whole numbers. Stop checking once the divisor is larger than the square root of the input.

javascript

function isPrime(value) {
  if (!Number.isInteger(value) || value < 2) return false;
  for (let divisor = 2; divisor * divisor <= value; divisor += 1) {
    if (value % divisor === 0) return false;
  }
  return true;
}

console.log(isPrime(37));
console.log(isPrime(45));

Problem: Use a loop to calculate n factorial for an integer from 0 through 12. Remember that 0 factorial is 1, and reject values outside that range.

javascript

function factorial(value) {
  if (!Number.isInteger(value) || value < 0 || value > 12) {
    throw new RangeError('value must be an integer from 0 through 12');
  }
  let result = 1;
  for (let factor = 2; factor <= value; factor += 1) {
    result *= factor;
  }
  return result;
}

console.log(factorial(6));
console.log(factorial(0));

Problem: Return the first count values of a Fibonacci sequence that starts with 0 and 1. Return an empty array when count is zero.

javascript

function fibonacciSequence(count) {
  if (!Number.isInteger(count) || count < 0 || count > 40) {
    throw new RangeError('count must be an integer from 0 through 40');
  }
  const values = [];
  let previous = 0;
  let current = 1;
  for (let index = 0; index < count; index += 1) {
    values.push(previous);
    [previous, current] = [current, previous + current];
  }
  return values;
}

console.log(fibonacciSequence(8));

Problem: For a non-negative integer up to 999,999,999, return its digit count and the number formed by reversing those digits. Treat zero as having one digit.

javascript

function summarizeDigits(value) {
  if (!Number.isInteger(value) || value < 0 || value > 999999999) {
    throw new RangeError('value must be a non-negative integer up to 999999999');
  }
  let remaining = value;
  let count = 0;
  let reversed = 0;
  do {
    const digit = remaining % 10;
    reversed = reversed * 10 + digit;
    remaining = Math.floor(remaining / 10);
    count += 1;
  } while (remaining > 0);
  return { count, reversed };
}

console.log(summarizeDigits(90620));