Type Coercion and Falsy, Truthy values.
Table of contents
Type Coercion and Falsy values
Javascript automatically or implicitly converts values from one data type to another.
This means conversion from
Number to String
String to Number
Boolean to Number
etc. note - We can perform all the activities Using mathematical operators
- Number + String = String
let str = '2'+3;
console.log(typeof str, str);
Output - string 23
The above example will converted numbers into string
- Number - String = Number
let num = "23"-10;
num = Number("23")-10 // Number("23") is equal to 23
console.log(num, typeof num);
Output - 13 number
- Number / String = Number
let num2 = "20"/ 2;
console.log(num2, typeof num2);
Output - 10 number
- Number * String = Number
let num2 = "20" * 2;
console.log(num2, typeof num2);
Output - 20 number
- Number % String = Number
let num2 = "20" % 3;
console.log(num2, typeof num2);
Output - 2 number
- With the expression
console.log(2 + 6 + "15" -3 );
// 8+'15'-3
// '815'-3
// 812
output - 812
Falsy Values
Basically, falsy values are Booleans which return a false value or 0 as an output
We have 0, null, undefined, NaN
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean(null));
console.log(Boolean(undefined));
console.log(Boolean(NaN));
output -
false
false
false
false
false
Truthy Values
The rest except falsy values are truty values
console.log(Boolean("bharat"));
console.log(Boolean(15));
console.log(Boolean([]));
console.log(Boolean({}));
console.log(Boolean(" "));
Output -
true
true
true
true
true
Subscribe to my newsletter
Read articles from Chavhan Bharat directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Chavhan Bharat
Chavhan Bharat
passionate Aspiring Full Stack Developer | MERN Enthusiast Greetings! 👋 I'm Bharat, a dedicated and aspiring Full Stack Developer with a strong passion for crafting seamless, user-centric web applications. My journey in the world of programming has led me to specialize in the MERN stack—leveraging MongoDB, Express.js, React, and Node.js to build robust and scalable solutions.