• Home
  • HTML
    • HTML Introduction
    • HTML Basic
    • HTML Elements
    • HTML Attributes
    • HTML Headings
    • HTML Paragraphs
    • HTML Text Formatting
    • HTML Styles
    • HTML Comments
    • HTML Styles - CSS
    • HTML Links
    • HTML Images
    • HTML Tables
    • HTML Lists
    • HTML Block and Inline Elements
    • HTML class Attribute
    • HTML Forms
    • HTML Media
  • CSS
    • Introduction of CSS
    • CSS Syntax
    • CSS Selectors
    • How To Add CSS
    • CSS Comments
    • CSS Colors
    • CSS Backgrounds
    • CSS Borders
    • CSS Margins
    • CSS Text
    • CSS Lists
    • CSS Tables
    • CSS Box Model
    • CSS Dimension
    • CSS Padding
    • CSS Border
    • CSS Margin
    • CSS Outline
    • CSS Cursors
    • CSS Overflow
    • CSS Units
    • CSS Visual Formatting
    • CSS Display
    • CSS Visibility
    • CSS Position
    • CSS Layers
    • CSS Float
    • CSS Alignment
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS Media Types
    • CSS Sprites
    • CSS Opacity
    • CSS Attribute Selectors
    • CSS Validation
    • CSS3 Border
    • CSS3 Gradients
    • CSS3 Text Overflow
  • JavaScript
    • JS Introduction
    • JS Getting Started
    • JS Syntax
    • JS Variables
    • JS Generating Output
    • JS Data Types
    • JS Operators
    • JS Events
    • JS Strings
    • JS Numbers
    • JS If Else
    • JS Switch Case
    • JS Arrays
    • JS Sorting Arrays
    • JS Loops
    • JS Functions
    • JS Objects
    • JS DOM Nodes
    • JS DOM Selectors
    • JS DOM Styling
    • JS DOM Get Set Attributes
    • JS DOM Manipulation
    • JS DOM Navigation
    • JS Window
    • JS Screen
    • JS Location
    • JS History
    • JS Navigator
    • JS Dialog Boxes
    • JS Timers
    • JS Date and Time
    • JS Math Operations
    • JS Type Conversions
    • JS Event Listeners
    • JS Event Propagation
    • JS Borrowing Methods
    • JS Hoisting Behavior
    • JS Closures
    • JS Strict Mode
    • JS JSON Parsing
    • JS Error Handling
    • JS Regular Expressions
    • JS Form Validation
    • JS Cookies
    • JS AJAX Requests
    • JS ES6 Features
  • jQuery
    • jQuery Introduction
    • jQuery Syntax
    • jQuery Selectors
    • jQuery Events
    • jQuery Show/Hide
    • jQuery Fade
    • jQuery Slide
    • jQuery Animation
    • jQuery Stop
    • jQuery Chaining
    • jQuery Callback
    • jQuery Get/Set
    • jQuery Insert
    • jQuery Remove
    • jQuery CSS Classes
    • jQuery Style Properties
    • jQuery Dimensions
    • jQuery Traversing
    • jQuery Ancestors
    • jQuery Descendants
    • jQuery Siblings
    • jQuery Filtering
    • jQuery Ajax
    • jQuery Load
    • jQuery Get/Post
    • jQuery No-Conflict
  • PHP
    • PHP Introduction
    • PHP Install
    • PHP Syntax
    • PHP Comments
    • PHP Variables
    • PHP Echo / Print
    • PHP Data Types
    • PHP Strings
    • PHP Constants
    • PHP Operators
    • PHP If...Else...Elseif
    • PHP Switch
    • PHP Loops
    • PHP Functions
    • PHP Arrays
    • PHP Superglobals
    • PHP Date and Time
    • PHP Include
    • PHP File Handling
    • PHP File Upload
    • PHP Cookies
    • PHP Sessions
    • PHP Filters
    • PHP Callback Functions
    • PHP JSON
    • PHP Exceptions
    • PHP What is OOP
    • PHP Classes/Objects
    • PHP Constructor
    • PHP Destructor
    • PHP Access Modifiers
    • PHP Inheritance
    • PHP Abstract Classes
    • PHP Interfaces
    • PHP Traits
    • PHP Static Methods
    • PHP Namespaces
  • SQL
    • Introduction to SQL
    • SQL Create Command
    • SQL ALTER Command
    • SQL Truncate Drop Rename
    • INSERT SQL command
    • UPDATE SQL command
    • DELETE SQL command
    • SQL COMMIT command
    • SQL ROLLBACK command
    • SQL GRANT and REVOKE Command
    • SQL WHERE clause
    • SQL LIKE clause
    • SQL ORDER BY Clause
    • SQL Group By Clause
    • SQL HAVING Clause
    • SQL DISTINCT keyword
    • SQL AND OR operator
    • SQL Constraints
    • SQL Functions
    • SQL JOIN
  • Python
    • Getting started with Python
    • Introduction to IDLE
    • Python 2.x vs. Python 3.x
    • Syntax Rules and First Program
    • Numbers and Math Functions
    • Python Operators
    • Python Variables
    • Python Modules and Functions
    • Python Input and Output
    • Data Types in Python
    • String in Python
    • String Functions in python
    • Lists in Python
    • Utilizing List Elements by Iterating
    • Deleting List Elements & other Functions
    • Dictionaries in Python
    • Functions for Dictionary
    • Tuples in Python
    • Relational and Logical Operators
    • Conditional Statements in Python
    • Looping in Python
    • Define Functions in Python
    • Python-Introduction to OOP
    • Object Oriented Programming in Python
    • Classes in Python
    • The concept of Constructor
    • Destructors - Destroying the Object in Python
    • Inheritance in Python
    • Access Modifers in Python
    • Types of Inheritance
    • Method Overriding in Python
    • Polymorphism
    • static Keyword
    • Operator Overloading Python
    • Introduction to Error Handling
    • Exception Handling: try and except
    • Exeption Handling: finally
    • Exception Handling: raise
    • File Handling
    • Reading and Writing File
    • Introduction to Multithreading
    • Threading Module in Python
    • Thread Object
    • Lock Object
    • RLock Object
    • Event Object
    • Timer Object
    • Condition Object
    • Barrier Object
    • __name__ Variable in Python
    • Iterable and Iterator
    • yield Keyword
    • Python Generators
    • Python Closures
    • Python Decorators
    • @property Decorator in Python
    • Assert Statement
    • Garbage Collection
    • Shallow and Deep Copy
    • Introduction to Logging
    • Configure Log LEVEL, Format etc
    • Python Logging in a file
    • Python Logging Variable Data
    • Python Logging Classes and Functions
    • Python MySQL Introduction
    • Create Database - Python MySQL
    • Create Table - Python MySQL
    • Insert Data in Table
    • Select Data from Table
    • Update data in Table
    • Delete data from Table
    • Drop Table from Database
    • WHERE clause - Python MySQL
    • Order By clause - Python MySQL
    • Limit clause - Python MySQL
    • Table Joins - Python MySQL
  • MongoDB
    • MongoDB Introduction
    • Overview of MongoDB
    • MongoDB vs SQL Databases
    • Advantages of MongoDB
    • When to go for MongoDB
    • Data Modelling in MongoDB
    • Is MongoDB really Schemaless?
    • Installing MongoDB on Windows and Linux
    • Datatypes in MongoDB
    • Create and Drop Database in MongoDB
    • MongoDB: Creating a Collection
    • CRUD Operations in MongoDB
    • Data Relationships in MongoDB
    • Indexing in MongoDB
    • Sorting in MongoDB
    • Aggregation in MongoDB
    • Data Backup and Restoration in MongoDB
    • Sharding in MongoDB
    • Java Integration with MongoDB
  • Elixir
    • Elixir Overview
    • Elixir Environment
    • Elixir Basic Syntax
    • Elixir Data Types
    • Elixir Variables
    • Elixir Operators
    • Elixir Pattern Matching
    • Elixir Decision Making
    • Elixir Strings
    • Elixir Char Lists
    • Elixir Lists and Tuples
    • Elixir Keyword Lists
    • Elixir Maps
    • Elixir Modules
    • Elixir Aliases
    • Elixir Functions
    • Elixir Recursion
    • Elixir Loops
    • Elixir Enumerables
    • Elixir Streams
    • Elixir Structs
    • Elixir Protocols
    • Elixir File I/O
    • Elixir Processes
    • Elixir Sigils
    • Elixir Comprehensions
    • Elixir Typespecs
    • Elixir Behaviours
    • Elixir Errors Handling
    • Elixir Macros
    • Elixir Libraries
  • TypeScript
    • TypeScript Overview
    • Install TypeScript
    • First TypeScript Program
    • Type Annotation
    • TypeScript Variable
    • TypeScript Data Type Number
    • TypeScript Data Type String
    • TypeScript Data Type Boolean
    • TypeScript Arrays
    • TypeScript Tuples
    • TypeScript Enum
    • TypeScript Union
    • TypeScript Any Data Type
    • TypeScript Void Data Type
    • TypeScript Never Data Type
  • Home
  • JS Introduction
  • JS Getting Started
  • JS Syntax
  • JS Variables
  • JS Generating Output
  • JS Data Types
  • JS Operators
  • JS Events
  • JS Strings
  • JS Numbers
  • JS If Else
  • JS Switch Case
  • JS Arrays
  • JS Sorting Arrays
  • JS Loops
  • JS Functions
  • JS Objects
  • JS DOM Nodes
  • JS DOM Selectors
  • JS DOM Styling
  • JS DOM Get Set Attributes
  • JS DOM Manipulation
  • JS DOM Navigation
  • JS Window
  • JS Screen
  • JS Location
  • JS History
  • JS Navigator
  • JS Dialog Boxes
  • JS Timers
  • JS Date and Time
  • JS Math Operations
  • JS Type Conversions
  • JS Event Listeners
  • JS Event Propagation
  • JS Borrowing Methods
  • JS Hoisting Behavior
  • JS Closures
  • JS Strict Mode
  • JS JSON Parsing
  • JS Error Handling
  • JS Regular Expressions
  • JS Form Validation
  • JS Cookies
  • JS AJAX Requests
  • JS ES6 Features
Home >> javascript >> JS Type Conversions

JS Type Conversions

JavaScript at times automatically converts values from one data type to another when used in an expression. For instance, in mathematical operations values are automatically converted to numbers. but, the final result is not always what you expected:

In some situations, you might need to manually convert a value from one data type to another. However, JavaScript provides several different methods to perform such data type conversion tasks. In subsequent sections in this tutorial, we will discuss those methods in detail.

alert("3" - 2);  // Outputs: 1 
alert("3" + 2);  // Outputs: "32" (because + is also concatenation operator)
alert(3 + "2");  // Outputs: "32"
alert("3" * "2");  // Outputs: 6
alert("10" / "2");  // Outputs: 5
alert(1 + true);  // Outputs: 2 (because true is converted to 1)
alert(1 + false);  // Outputs: 1 (because false is converted to 0)
alert(1 + undefined);  // Outputs: NaN
alert(3 + null);  // Outputs: 3 (because null is converted to 0)
alert("3" + null);  // Outputs: "3null"
alert(true + null);  // Outputs: 1
alert(true + undefined);  // Outputs: NaN

Try with example

 

Converting Values to Numbers

In JavaScript, numeric conversion is mostly required when you read the value from a string-based source like text input, but you expect a number to be entered, or want to treat it as a number.

In this case, you can use the global method Number() to convert strings to numbers.

var str = "123";
alert(typeof str); // Outputs: string

var num = Number(str); // Becomes a number 123
alert(typeof num); // Outputs: number

Try with example

 

However, if the string is not a valid number, the result will be NaN. But, empty strings convert to 0.

Number("10.5")  // returns 10.5
Number(true)  // returns 1
Number(false)  // returns 0
Number(null)  // returns 0
Number(" 123 ")  // returns 123
Number(" ")  // returns 0
Number("")  // returns 0
Number("123e-1")  // returns 12.3
Number("0xFF") // returns 255 (hexadecimal representation)
Number("undefined")  // returns NaN
Number("null")  // returns NaN
Number("Hello World!")  // returns NaN

Try with example

 

Converting Values to Strings

More so, the String() method can be used to convert a value to a string.

The example below will show you how to convert a Boolean value to a string.

var bool = true;
alert(typeof bool); // Outputs: boolean

var str = String(bool); // Becomes a string "true"
alert(typeof str); // Outputs: string

Try with example

 

Note: The String() method can also be used on any type of number, variable, or expression:

String(10.5)  // returns "10.5"
String(123)  // returns "123"
String(100 + 23)  // returns "123"
String(true)  // returns "true"
String(false)  // returns "false"
String(123e-1)  // returns "12.3"
String(0xFF) // returns "255"
String(undefined)  // returns "undefined"
String(null)  // returns "null"

The toString() method is another technique for converting numbers to strings.

var num = 123;
alert(typeof num); // Outputs: number

var str = num.toString(); // Becomes a string "123"
alert(typeof str); // Outputs: string

Try with example

 

Converting Values to Boolean

Boolean conversions is another conversion in JavaScript, and it's also straightforward. In this case, the Boolean() method is used to convert any value to a Boolean value (i.e. in the form of true or false).

However, intuitively empty values, such as 0, null, false, undefined, NaN, or an empty string ("") become false; while other values become true, as shown in the example below:

Boolean(0) // returns false
Boolean(null)  // returns false
Boolean(false)  // returns false
Boolean(undefined)  // returns false
Boolean(NaN)  // returns false
Boolean("") // returns false
Boolean("0") // returns true
Boolean(1) // returns true
Boolean(true) // returns true
Boolean("false") // returns true
Boolean("Hello World!") // returns true
Boolean(" ") // returns true

Try with example

 

From the example above, you will find out that the Boolean() method returns true for the string with zero "0", and a string "false", whereas it returns false for the values 0 and false.

Note: In most programming languages like PHP, the string "0" is treated as false. But this is not the case in JavaScript, as a non-empty string is always true.

 

Object to Primitive Conversions

So far, all these conversions we've seen are performed on primitive data types (i.e data types that can hold only a single value at a time). However, what do you think will happen with complex data types such as an object, let's find out.

Just as learned earlier, JavaScript automatically performs object-to-string conversion when you try to print out an object like alert(obj) or document.write(obj). Same as, the object-to-number conversions are automatically performed when you try to add or subtract objects or apply mathematical functions, for example, adding or subtracting date objects. This is an example:

var date1 = new Date(2022, 7, 15);
alert(date1); // Display date string like: Mon Aug 15 2022 00:00:00

var date2 = new Date(2023, 7, 15);
var time = date2 - date1;
alert(time) // Display time in milliseconds: 31536000000

Try with example

 

Also, with the toString() method, you can perform the object-to-string conversion manually, which will return a string representation of the object. More so, you can use the valueOf() method on some objects like Date to perform the object-to-number conversion. Take a look at this example:

 var arr = [1, 2, 3];
alert(arr.toString()); // returns "1,2,3"

var d = new Date(2022, 7, 15);
alert(d.toDateString()); // returns date like Mon Aug 15 2022 00:00:00
alert(d.valueOf()); // returns 1660501800000

Try with example

Note: Object-to-Boolean conversions are insignificant since all objects (such as arrays and functions) are true in a boolean context. Hence, you have an only string and numeric conversions.

 

Type Conversions Using Operators

In JavaScript, certain operators, such as ‘+’ and ‘-‘ operators, can also be used to perform type conversions, as demonstrated in the example below:

var x = "10"; // x is a string
var y = +x;
alert(typeof(y)); // Outputs: number
alert(y); // Outputs: 10

var x = 10; // x is a number
var y = x + "";
alert(typeof(y)); // Outputs: string
alert(y); // Outputs: 10

var x = "15"; // x is a string
var y = x - 0;
alert(typeof(y)); // Outputs: number
alert(y); // Outputs: 15

var x = "123";
alert(typeof(!!x)); // Outputs: boolean
alert(!!x); // Outputs: true

var x = "Hello World!";
var y = +x;
alert(typeof(y));// Outputs: number
alert(y); // Outputs: NaN

Try with example

We hope you've learned and understood the basics of data type conversions. Please, you can do yourself good by checking out the tutorial on JavaScript data types to learn more about the different data types available in JavaScript.

  • Prev
  • Next


-Advertisement-


DeveloperTutorial
[email protected] © 2022-2023 Developers Tutorial All rights reserved.

Follow Us

Facebook Twitter LinkedIn Printerest Reddit

Announcement

Its a big achivement for us, We make a partnership with TutorialWithExample.com for the better content of our users.

Still Need Help ?

Let us now about your issue and a Professional will reach you out.