JavaScript: JavaScript Utility Methods
We've covered type conversions — now let's learn a batch of utility methods you'll use every day. Think of them as a Swiss army knife — each one is simple, but you'll miss any one of them when you need it.
1. Essential Utility Methods
(1) parseInt and parseFloat
Parse numbers from the beginning of a string, stopping at the first non-numeric character:
<!-- Script tag -->
<script>
console.log(parseInt("42px")); // 42
console.log(parseInt("3.14")); // 3 (integer part only)
console.log(parseFloat("3.14")); // 3.14
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("abc42")); // NaN (doesn't start with a number)
</script>
The second argument of parseInt specifies the radix:
<!-- Script tag -->
<script>
console.log(parseInt("FF", 16)); // 255 (hexadecimal)
console.log(parseInt("10", 2)); // 2 (binary)
</script>
Pitfall: Without a radix, strings starting with 0x are parsed as hexadecimal. Always pass 10 as the second argument.
(2) isNaN vs Number.isNaN
| Method | Behavior |
|---|---|
isNaN(value) |
Converts to number first, then checks if it's NaN |
Number.isNaN(value) |
Strictly checks if the value is NaN (no conversion) |
<!-- Script tag -->
<script>
console.log(isNaN("hello")); // true (Number("hello") → NaN, then true)
console.log(Number.isNaN("hello")); // false ("hello" itself is not NaN)
console.log(isNaN(undefined)); // true
console.log(Number.isNaN(undefined));// false
</script>
Conclusion: Use Number.isNaN() — it won't silently coerce types.
(3) toFixed
Controls decimal places, returns a string:
<!-- Script tag -->
<script>
console.log((3.14159).toFixed(2)); // "3.14"
console.log((3.1).toFixed(4)); // "3.1000" (padded with zeros)
console.log((3.145).toFixed(2)); // "3.14" or "3.15" (floating-point precision issue, rounding not guaranteed)
</script>
Note that toFixed returns a string — use Number() to convert it back for calculations.
(4) toString
Converts a number to a string, with optional radix support:
<!-- Script tag -->
<script>
console.log((255).toString()); // "255"
console.log((255).toString(16)); // "ff"
console.log((8).toString(2)); // "1000"
console.log((100).toString(8)); // "144"
</script>
Booleans and arrays also have toString:
<!-- Script tag -->
<script>
console.log(true.toString()); // "true"
console.log([1,2,3].toString()); // "1,2,3"
</script>
(5) Number.isInteger
Checks whether a value is an integer:
<!-- Script tag -->
<script>
console.log(Number.isInteger(5)); // true
console.log(Number.isInteger(5.0)); // true (5.0 is just 5)
console.log(Number.isInteger(5.5)); // false
console.log(Number.isInteger("5")); // false (a string is not an integer)
console.log(Number.isInteger(NaN)); // false
</script>
(6) Math.trunc and Math.sign
Math.trunc simply chops off the decimal part (no rounding):
<!-- Script tag -->
<script>
console.log(Math.trunc(4.9)); // 4
console.log(Math.trunc(-4.9)); // -4
console.log(Math.trunc(4.1)); // 4
</script>
Math.sign returns the sign of a number:
<!-- Script tag -->
<script>
console.log(Math.sign(5)); // 1
console.log(Math.sign(-5)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
console.log(Math.sign(NaN)); // NaN
</script>
(7) Limitations of typeof
typeof usually works for type checking, but there are a few classic gotchas:
<!-- Script tag -->
<script>
console.log(typeof 42); // "number" ✅
console.log(typeof "hello"); // "string" ✅
console.log(typeof true); // "boolean" ✅
console.log(typeof undefined); // "undefined" ✅
console.log(typeof null); // "object" ❌ This is a historical bug!
console.log(typeof []); // "object" ❌ Arrays are also objects
console.log(typeof {}); // "object" ✅
console.log(typeof function(){}); // "function" ✅
</script>
typeof null === "object" is a "veteran bug" in JavaScript — it's been around since 1995 and can never be fixed. Use value === null to check for null. Use Array.isArray() to check for arrays.
▶ Example: Price Calculator
▶ Try it Yourself▶ Example: Input Validation Tool
▶ Try it Yourself▶ Example: typeof and Type Checking
▶ Try it Yourself❓ FAQ
parseFloat("42px") parses from the beginning until it hits a non-numeric character and returns 42, while Number("42px") requires the entire string to be a valid number, otherwise it returns NaN. So use parseFloat to extract a number from mixed text, and use Number() for strict type conversion or validation.parseInt("08") sometimes return 0?0 were parsed as octal, and "08" is invalid in octal, so it returns 0. To avoid this pitfall, always pass the second argument: parseInt("08", 10) will return 8.toFixed guarantee proper rounding?toFixed may not match what you'd expect. When you need reliable rounding, you can first use Math.round(num * 100) / 100 and then toFixed, or use a dedicated precision library.📖 Summary
parseInt(str, radix)parses integers; specify radix to avoid surprises.parseFloat(str)parses floatsisNaN(value)checks for NaN —NaN === NaNis false, useNumber.isNaNfor strict checking- Explicit conversion:
Number(value),String(value),Boolean(value)are safer than implicit num.toFixed(digits)returns a string with specified decimal places, great for currency display- Type checking:
typeoffor primitives,Array.isArray()for arrays,Object.prototype.toString.call()for precise detection
📝 Exercises
- Write a function
parseChineseNumber(str)that parses strings like"3.5🦄"→3.5,"100🦄"→100,"🦄200"→200(usingparseFloat). Handle the case where plain text returnsNaN. - Write a function
formatMoney(amount)that takes a number and returns a string with comma-separated thousands and two decimal places, e.g.1234567.89→"1,234,567.89"(hint: usetoFixedandtoStringwith array methods). - Write a function
getType(value)🦄typeof🦄:🦄null🦄null,🦄array,🦄typeof🦄。