Knowing the data type of a variable

Josué Pérez

Identifying a Variable’s Data Type in JavaScript

In production-grade JavaScript, type awareness is not a “nice to have”—it’s a reliability decision. JavaScript is dynamically typed, which gives speed and flexibility, but it also increases the risk of subtle runtime issues if we don’t validate assumptions at the boundaries (inputs, APIs, integrations).

The fastest way to inspect a variable’s type is using the typeof operator:

typeof varName

Example

Imagine your frontend consuming /api/me, where the backend is expected to return name as a string… but due to a bug or corrupted data, it sometimes arrives as null, a number, or even an object. Before rendering or persisting the data, you validate it:

                            async function loadProfile() {
  const res = await fetch('/api/me');
  const data = await res.json();

  // Real-world guard: never trust external data blindly
  const name = typeof data?.name === 'string' ? data.name.trim() : '';

  if (!name) {
    console.warn('Invalid user name received from API:', data?.name);
    // Fallback: show a safe default or trigger a recovery flow
    return { name: 'Unknown User' };
  }

  return { name };
}
                        
Note: Use typeof to protect critical paths—especially when handling user input, environment variables, or data coming from external services. Small checks like this prevent large incidents.

Reference

How to check if a variable is String in JavaScript