⬅ Previous Topic
JavaScript Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.
⬅ Previous Topic
JavaScript Data TypesIn JavaScript, type conversion refers to changing a value from one data type to another. It is an essential concept because JavaScript is a dynamically typed language, meaning you don't need to specify data types explicitly.
There are two types of type conversions:
JavaScript automatically converts data types when needed. This is called type coercion.
let result = '10' + 5;
console.log(result);
105
Explanation: The number 5
is implicitly converted to a string, and the result is string concatenation: '10' + '5' = '105'
.
let difference = '10' - 2;
console.log(difference);
8
Explanation: Here, JavaScript converts the string '10'
to the number 10
and then performs subtraction.
A: JavaScript treats +
as both a concatenation and arithmetic operator. If either operand is a string, it prefers string concatenation. For other operators like -
, *
, /
, it defaults to numeric operations.
Explicit conversion is when you manually convert a value using JavaScript functions like Number()
, String()
, or Boolean()
.
let str = "42";
let num = Number(str);
console.log(num);
console.log(typeof num);
42 number
Explanation: The Number()
function converts the string "42"
to a number.
let val = 100;
let strVal = String(val);
console.log(strVal);
console.log(typeof strVal);
100 string
Explanation: The String()
function converts the number 100
to a string.
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
Explanation: Boolean()
converts values to either true
or false
based on their "truthiness".
When converting to Boolean
, JavaScript considers the following values as falsy:
false
0
""
(empty string)null
undefined
NaN
All other values are truthy.
'5' + 1
becomes '51'
).Number()
, String()
, and Boolean()
for explicit conversion.+
operator due to its dual nature.What will be the output of the following?
console.log('5' * '2');
Answer:
10
Why? Both strings are implicitly converted to numbers before performing multiplication.
⬅ Previous Topic
JavaScript Data TypesYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.