Ad space (banner)
🟨JavaScript Lessons
Lesson 52 / 69

Writing Type-Agnostic, General-Purpose Functions

In this lesson you'll learn how to write general-purpose functions that take advantage of the fact that JavaScript is a dynamically typed language. This is for people searching "JavaScript what is dynamic typing" or "JavaScript general-purpose functions."

JavaScript is a dynamically typed language, so a function can generally accept a value of any type. By writing "a general-purpose function that doesn't commit to a single type," you can reuse the same logic for both numbers and strings. This flexibility, often compared against a statically typed language like TypeScript, is a signature trait unique to JavaScript.

The sample code has a function called larger(a, b) handle both numeric comparisons and string comparisons using the exact same logic. The > operator compares magnitude for two numbers, and compares dictionary order (alphabetical order) for two strings, which lets the exact same function be reused for data of different types.

As flexible as this is, an unexpected type can be passed in without throwing an error, which can lead to bugs — so it's a good idea to build the habit of checking types inside a function alongside this flexibility, for safer code. Be careful of cases like trying to compare a number and a string, where an unexpected combination of types can lead to an unintended result.

You'll become more strongly aware of this distinction when you learn a typed language like TypeScript. Many large-scale, real-world projects adopt TypeScript specifically to perform rigorous type checking, so understanding this trade-off with JavaScript's flexibility will help your future learning too.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)