Dynamic Typing

In the previous chapter, we explored JavaScript's built-in values and types and covered some of the challenges involved when using them. The next natural step is for us to explore how JavaScript's dynamic system plays out in the real world. Since JavaScript is a dynamically typed language, the variables in your code are not constrained in terms of the type of values they refer to. This introduces a huge challenge for the clean coder. Without certainty regarding our types, our code can break in unexpected ways and can become incredibly fragile. This fragility can be explained quite simply by imagining a numeric value embedded within a string:

const possiblyNumeric = '203.45';

Here, we can see that the value is numeric but that it has been wrapped in a string literal and so, as far as JavaScript is concerned, is just a regular string. But because JavaScript is dynamic, we can freely pass this value around to any function—even a function that is expecting a number:

setWidth('203.45');

function setWidth(width) {
width += 20; // Add margins
applyWidth(width); // Apply the width
}

The function adds a margin value to the number via the += operator. This operator, as we will learn later in this chapter, is an alias for the operation a = a + b, and the + operator here will, in the case of either operand being a String type, simply concatenate the two strings together. What's funny is that this simple and innocent-looking implementation detail is the crux of millions of exhausting debugging sessions that have occurred around the world at various times. Thankfully, knowing about this operator and its exact behavior will save you countless hours of pain and exhaustion, and will cement in your mind the importance of writing code that avoids the very trap we've fallen into with our possiblyNumeric value.

In this chapter, we will cover the following topics:

  • Detection
  • Conversion, coercion, and casting

The first crucial step in being able to wrangle our types with more ease is to learn about detection, which is the skill of being able to discern what type or types you're dealing with in the least complex way.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.172.93