Click here to Skip to main content
15,902,777 members
Articles / Mobile Apps
Tip/Trick

JavaScript Type Coercion

Rate me:
Please Sign up or sign in to vote.
4.40/5 (3 votes)
19 Jul 2015CPOL4 min read 10.8K   3  
Type coercion in JavaScript and its Applications

Introduction

In this article we discuss about type coercion and weak typing aspects of JavaScript, then we’ll see some applications.

Background

If you use a data type JavaScript did not expect, it tries to make sense of the operation rather than report an error.

JavaScript can convert data types behind the scenes to complete an operation. This is known as type coercion. For example, a string '0' could be converted to a number 1 in the following expression: ('0' > -1). As a result, the above expression would evaluate to true.

JavaScript is said to use weak typing because the data type for a value can change. Some other languages require that you specify what data type each variable will be. They are said to use strong typing.

Type coercion can lead to unexpected values in your code (and also cause errors). So it’s necessary to know the basics to get better results working with it.

 

Prerequisites

Primitive Data Types

As we know there are five primitive data types in JavaScript:

JavaScript Primitive Data Types

Data Type

Purpose

number Numbers
string Strings
boolean True/False
null Empty Values
undefined Variable has been declared but not yet assigned a value
   
   
   
   

TRUTHY & FALSY VALUES

Due to type coercion, every value in JavaScript can be treated as if it were true or false; and this has some interesting side effects.

Falsy values are treated as if they are false. The table below shows a sample variable with a series of values, all of which are falsy.

JavaScript
var sample = false; // ----------------- Just boolean false

var sample = 0; // --------------------- the number zero

var sample = ''; // -------------------- Empty value

var sample = 10/'some string'; // ------ NaN ( not a number )

var sample; // -------------------------- a variable with no assigned value
 
   

Truthy values are treated as if they are true. Almost everything that is not in the falsy table can be treated as if it were true.

In addition, the presence of an object or an array is usually considered truthy, too. This is commonly used when checking for the presence of an element in a page, which is called feature detection.

JavaScript
var sample = true; // ------------------ Just boolean true

var sample = 1; // --------------------- numbers other than zero

var sample = 'string'; // -------------- strings with content

var sample = 10/5; // ------------------ number calculations

var sample = 'true'; // ---------------- true as a string
JavaScript
var sample = '0'; // ------------------- zero as a string
JavaScript
var sample = 'false'; // --------------- false as a string

 

Applications

CHECKING EQUALITY & EXISTENCE

Because the presence of an object or array can be considered truthy, it is often used to check for the existence of an element within a page.

JavaScript
if(document.getElementByid('footer')){

// Found: do something
}
else {

// Not found: do somethinng else
}

Because of type coercion, the strict equality operators === and !== result in fewer unexpected values than == and != do.

JavaScript
(false == 0) // ----------------------------------------    true 
(false === 0) //----------------------------------------    false
(false== ' ') //----------------------------------------    true
(false === ' ') //--------------------------------------    false
(0 == ' ') //-------------------------------------------    true
(O === ' ') //------------------------------------------    false
JavaScript
(undefined == null) // ---------------------------------    true 
(null == false) //--------------------------------------    false
(undefined == false) //---------------------------------    false
(null == 0) //------------------------------------------    false
(undefined == 0) //-------------------------------------    false
(undefined === null) //---------------------------------    false

 

SHORT CIRCUIT VALUES

Logical operators are processed left to right. They short-circuit (stop) as soon as they have a result - but they return the value that stopped the processing (not necessarily true or false).

Logical operators will not always return true or false, because:

  •  They return the value that stopped processing.
  •  That va lue might have been treated as truthy or falsy although it was not a Boolean.

Programmers use this creatively (for example, to set values for variables or even create objects).

As soon as a truthy value is found, the remaining options are not checked. Therefore, experienced programmers often:

  •  Put the code most likely to return true first in OR operations, and false answers first in AND operations.
  •  Place the options requiring the most processing powe.r last, just in case another value returns true and they do not need to be run.

Examples:

On line 1, the variable artist is given a value of artman.

On line 2, if the variable artist has a value, then artistA will be given the same value as artist (because a non-empty string is truthy).

JavaScript
var artist = 'artman' ;
var artistA = (artist || 'Unknown') ;

If the string is empty (see below), artistA becomes a string 'Unknown' .

JavaScript
var artist = ' ' ;
var artistA = (artist || 'Unknown');

You could even create an empty object if artist does not have a value:

JavaScript
var artist= '';
var artistA = (artist || {}) ;

Here are three values. If any one of them is considered truthy, the code inside the if statement will execute. When the script encounters valueB in the logical operator, it will short circuit because the number 1 is considered truthy and the subsequent code block is executed.

JavaScript
valueA = 0;
valueB = 1;
valueC = 2;
if ( valueA || valueB || valueC ) {
// Do something here
}

This technique could also be used to check for the existence of elements within a page.

Notes

  • Falsy values can also be treated as the number 0 .
  • Truthy va lues can also be treated as the number 1.
  • A unary operator returns a result with just one operand.
  • Those new to JavaScript often think the following would do the same:

     if(document.getElementByld('footer') == true) and if(document.getElementByid('footer')) 

          but document.getElementByld('header') would return an object which is a truthy value but it is not equal to a Boolean value of true.

Further Reading

It is highly recommended to search for the following concepts :

  • JavaScript feature detection
  • JavaScript object detection
  • JavaScript feature detection libraries

 

Feel Free to Thevelop :)

The End

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) thevelop.ir
Iran (Islamic Republic of) Iran (Islamic Republic of)
I am a software professional with over 10 years of commercial business applications design and development experience.

My programming experience includes Java, Spring, Struts, JSF, Hibernate, EJB, Oracle, PHP, C, C++, HTML, CSS, JavaScript frameworks and libraries and Assembly.

In the last 6 years I am working with Java Technology and currently available to take up new assignments.

Comments and Discussions

 
-- There are no messages in this forum --