This is a section from a series of draft JavaScript fundamentals I started; (largely for my own revision!) to cover some aspects of JavaScript which make it unique; and perhaps contribute to its reputation as being seemingly not a ‘serious’ language if coming from a different language where the rules are different.

Let us consider that JavaScript is not a typed language. This means JavaScript is, let’s say, unique in how it interprets variables and evaluates conditions compared to many other languages, such as in JavaScripts’ implementation of type coercion.

The expressive, flexible nature of JavaScript without the need to specify types of variables, comes with the caveat that we have to be more cautious when evaluating variables to avoid unexpected results as we’ll see. Let’s look at Coercion.

I hope it’s a useful primer on this aspect of this most ubiquitous language!

Coercion is when the compiler will try to be ‘smart’ about interpreting variables, the logic behind which we should at least be familiar with to ensure we understand how our logic is evaluated to give the results we expect.

Coercion has a bad reputation, but it pays off to really learn and understand it so we can be confident we’re doing the right checks when implementing control flows, not to mention understanding what’s going on under the hood contributing to the opinions we have about JavaScript!…

Anything we don’t learn is indistinguishable from magic
— Arthur C Clarke

'The year is' + 2019;

Results in:

TypeError: can only concatenate str (not “int”) to str

Of course it would error 🙄 , as we cannot add a string to a number.

Now in JavaScript, that Number is coerced to a String.

Try typing some of these directly into your browsers’ console or a new terminal in VS Code…

'The year is ' + 2019

…which results in String concatenation as ‘The year is 2019'

Similarly:

5 + '5'

returns '55'

as the compiler has coerced the Numbers to a strings in order to concatenate them as a String output.

But what about this…

❓ Without using the console yet, what would we expect here?

5 + 5 + ‘5’

💡 Spoiler: Solution below

Yep, ’105'

The compiler will carry out the first operation, which is (5 + 5), then coerces that to String ’10', and concatenates it to the ’5', resulting in ’105'.

We’re having fun 🚀

But with a minus operator, it’s different...

What might you expect from typing this into the console?

'5' - 5

Yep, Number 0.

That’s because the String ‘5' is coerced to a Number in order for the - operator to be applied.

This is Type Coercion in JavaScript and it is intentional and follows expected rules.

Typed

Part of what makes JavaScript so expressive (and so accessible!) is its dynamically-typed nature, as opposed to typed like Python, C# or Java.

This means developers are free to mix and match types, reassigning them to variables, and using them to determine control flow without at any point needing to specify what the type of a variable should be (either when creating it or checking it).

The key point here is that this can generate errors unless we build-in defensiveness to enforce types; and not the easy-to-spot syntax ones but as logical/control flow ‘bugs’ if we don’t account for type coercion when evaluating variables.

Type checking with `typeof`

So how to add in such a check on the actual type of a variable? Fortunately, we can guard against anything unexpected by coding defensively. This could be by using keyword,const, implementing TypeScript transpiling in the codebase, in addition to thinking about exactly what we are accounting for coercion in control flow/logic.

Fortunately, when checking Strings and Numbers we can use JavaScripts’ built-in method typeof to check the type of a given variable. This method will always return a string of the type of that variable.

You may notice we’re using single quotes for strings. In JavaScript, either single or double quotes or backticks (Es6) are valid for strings, although single tends to be more popular. In projects, it’s more important to pick one and keep it consistant.

Single quotes (or backticks` ) allow you to store double quotes in HTML template strings for example, without escaping them

const htmlString = '<div class=”content”>…</div>'

Let’s create some variables.

Type these into your console of choice:

const id = 30

const name = ‘Alex’

And then check their type:

typeof id

…which returns ‘number’, and

typeof name

…which returns ‘string’

So one way to add some strictness to our practice is to enforce type equality using the triple-equals === operator:

if (id === 30) {   console.log(‘We know id is definitely a number!’);}

Notice the === . This ensures we’re strictly-checking for a number. A string of '30' would return false.

In most cases, using loose equality (==) is discouraged. The result of a comparison using strict equality (===) is easier to predict as there’s no room for type coercion to change the outcome.

Truthy and Falsy

Let’s look at what makes Truthy and Falsy values in JavaScript

a truthy value is a value that translates to true when evaluated in a Boolean context
MDN

It’s often joked that JavaScript has some quirks, particularly when considering what it considers a truthy value! But understanding which values constitute each in JavaScript is helpful when evaluating them and knowing what to expect given. Here are some common examples of each.

falsy values meaning they will evaluatefalse:

  • false
  • 0
  • ‘0’
  • ‘’ (empty string)
  • null
  • undefined

truthy values, meaning they will evaluate true:

  • true
  • ‘0'
  • ‘ ’ (any token in a string)
  • 1 (or any non-zero number, including minus!)
  • {} (empty object)
  • [] (empty array)

Coercion and Booleans

With our knowledge of what constitutes truthiness, we can create a boolean context for controlling flow by placing the value in brackets:

const pass = 1;if (pass) {   console.log(‘Passed!’);}

Summary

We’ve seen the various types of data in JavaScript. We can manipulate these types with arithmetic and comparison operators. But we need to pay particular attention to both the addition operator + and the comparison operator == which each perform conversion between types according to expected compiler rules.

This implicit conversion in JavaScript is called type coercion and is defined in the ECMAScript spec. Whenever possible in your code use always the strict comparison operator === instead of ==.

Resources on Types and Coercion

Equality comparisons and sameness — MDN

Truthy values — MDN

Falsy values — MDN

Front-end and Js Developer. Runner, MTB, always a learner.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store