06. Type conversions

Because JavaScript is a loosely typed language, meaning that it's not necessary to predeclare a given variable's type.

This feature, although convenient, can be the source of many bugs. Particularly, you should watch for type conversions, which is when a value of one type turns into another.

In the example below, the string '1' is converted into a number before the expression is evaluated.

'1' > 0  // true

Implicit conversions

An implicit conversion occurs without your explicit consent. For example, when a string and a number are added together with a + operand, the result is a string.

var ageGreeting = "I am " + 9 + " years old." // "I am 9 years old." 

Explicit conversions

In the case you want to change from a number to a string or vice versa, you can do so explicitly.

Number conversions

var numString = "100";
var num = Number(numString); // 100

String conversions

var numString = String(100);  // '100'
Next section: Control Flow

Build modern and responsive webpages

HTML & CSS

Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Ad