Chapter 51. Built-in JavaScript Objects

Every developer knows how annoying the sudden “magic” in JavaScript is: numbers turn into Infinity, the string “123px” suddenly becomes 123, and NaN behaves as if it has its own laws. And it’s especially painful when all this needs to be carefully integrated into a C++/Qt application without losing control over logic.

This chapter reveals how built-in JavaScript objects work and why professional developers rely on them to write predictable scripts. You’ll discover non-obvious places where “typing by mood” breaks calculations, and learn the secret of how to quickly verify data correctness before it gets into your Qt code—saving hours of debugging and increasing reliability.

Inside—6 key object families: Global (and its extension from Qt), Number (limits, isFinite/isNaN), String (replace/substring/slice + includes/startsWith), RegExp (test/search/match/split and replacement via function), Array (push/splice/sort/spread), Date and Math (precision, rounding, sqrt, random).

Not finishing this chapter, it’s easy to miss a couple of “small” nuances that later turn into big bugs.

This chapter includes ready-to-use code examples.

Chapter Self-Check

Why is creating a Boolean object not recommended in JavaScript, even though such an object exists?Answer
Correct answer: A Boolean object always converts to true (even new Boolean(false)), which creates confusion. It’s better to use primitive true/false values, which behave predictably.
Which six values in JavaScript convert to false when logically converted?Answer
Correct answer: These are 0, null, false, NaN, undefined, and empty string (“”). All other values, including empty arrays and objects, convert to true.
Why does the method Number.isNaN(“hello”) return false, even though the string is clearly not a number?Answer
Correct answer: Number.isNaN() checks whether the value is exactly NaN, not “not a number in general”. The string “hello” is a string, not a NaN value. To check for “not a number”, use isNaN() without Number.
What happens if the second parameter in the splice() method is set to 0?Answer
Correct answer: Elements will be inserted at the specified position without deleting existing elements, since the second parameter defines the number of elements to be deleted.
Why are months in the Date object numbered from 0, while days of the month start from 1 in JavaScript?Answer
Correct answer: This is a historical legacy from the Java language, where months are represented as array indices (0-11), and days of the month as calendar numbers (1-31). This creates confusion but is preserved for backward compatibility.
What fundamental limitation does storing dates in milliseconds since January 1, 1970 impose?Answer
Correct answer: Using dates before 1970 becomes problematic, although modern implementations support negative values for dates before this reference point (Unix epoch).
What’s the difference between Math.ceil() and Math.floor() methods when working with negative numbers?Answer
Correct answer: ceil() rounds to a greater value (Math.ceil(-5.5) = -5), while floor() rounds to a lesser value (Math.floor(-5.5) = -6). For negative numbers, “greater” means closer to zero.
Why is creating functions via new Function() slower than declaring regular functions?Answer
Correct answer: Because translation (compilation) of Function code happens each time it’s used at runtime, while regular functions are compiled once when the script is loaded.
What will the expression [“10”, “5”, “40”].sort() return and why might the result be unexpected?Answer
Correct answer: It will return [“10”, “40”, “5”], because sort() by default compares elements as strings lexicographically. For numeric sorting, a comparison function is needed: sort((a,b) => a – b).
How do you get all matches of a regular expression in a string using the match() method?Answer
Correct answer: You need to use the global flag g in the regular expression: str.match(/\d+/g). Without the g flag, the method returns only the first match.
Why is the push() method often preferable to direct assignment by index for adding elements to an array?Answer
Correct answer: push() automatically adds an element to the end without requiring knowledge of the array length, and returns the new length. Direct assignment can create “holes” in the array if the index is greater than the length.
What happens if you pass a negative number to Math.sqrt()?Answer
Correct answer: The method will return NaN (Not a Number), since the square root of a negative number is not defined in real numbers.
How do you find the maximum value in a number array using the spread operator ()?Answer
Correct answer: Math.max(…arr) — the spread operator expands the array into separate arguments for the max() method, which accepts multiple parameters, not an array.
Why are the trim(), trimStart(), and trimEnd() methods useful when processing user input?Answer
Correct answer: They remove accidental spaces that the user might have added during input, which makes validation and data comparison more reliable and eliminates formatting issues.
What’s the advantage of the replace() method with a callback function instead of a simple replacement string?Answer
Correct answer: The function allows dynamically calculating the replacement for each match, giving the ability to transform found values (e.g., multiply numbers, change case) instead of simple substitution.

Practical Exercises

Easy Level

String Validator with Filtering
Create a function that takes a string array and returns a new array containing only strings that: (1) are longer than 3 characters, (2) don’t contain digits, (3) are trimmed of spaces. For example, [” hello “, “hi”, “test123”, “world”] should return [“hello”, “world”].
Hints: Use methods filter(), trim(), length and regular expression /\d/.test() to check for digits. Combine conditions in a predicate function for filter().

Medium Level

Time Series Analyzer
Create a function that takes an array of Date objects and returns statistics: number of dates in each month of the year, earliest and latest dates, and average number of days between consecutive dates. Note that the array may not be sorted.
Hints: Use getMonth() to group by months, Math.min/max with spread operator to find extreme dates, sort() to order the array. To calculate the difference in days between dates, subtract milliseconds and divide by (1000 * 60 * 60 * 24).

Hard Level

Smart Mathematical Expression Parser
Create a calculator function that takes a string with a mathematical expression (e.g., “2 * (3 + sqrt(16)) / abs(-4)”) and calculates the result. The function should support: basic operations (+, -, *, /), parentheses, Math functions (sqrt, abs, pow, sin, cos), and return an error for incorrect syntax.
Hints: Use RegExp to replace mathematical functions with their calls (replace(/sqrt\((\d+)\)/g, match => Math.sqrt(…))), clean the string of spaces with trim(), use eval() cautiously or create Function() for safe execution. Wrap in try-catch for error handling. Consider using replace() with a function to replace all Math functions.

💬 Join the Discussion!

Managed to figure out the subtleties of built-in JavaScript objects? Discovered non-obvious behavior of Math or Date?

Share your solutions to practical exercises, discuss best practices for working with arrays and regular expressions, or help other readers understand the language’s quirks!

Leave a Reply

Your email address will not be published. Required fields are marked *