Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions explicit-and-implicit-conversion-in-javascript.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,31 @@ if (isValid) {
let age = "25";
let totalAge = age + 5;
console.log("Total Age: " + totalAge);
// Example 1: Subtraction operator triggers implicit type conversion from string to number
let result = "5" - 2; // "5" is implicitly converted to number 5 during subtraction
console.log("The result is: " + result); // Output: 3

// Example 2: Boolean conversion of a non-empty string ("false") is true
let isValid = Boolean("false"); // "false" is a non-empty string, so Boolean() returns true
if (isValid) {
console.log("This is valid!"); // This will run because isValid is true
}

// Example 3: String concatenation with + operator, no type conversion involved
let age = "25"; // age is a string
let totalAge = age + 5; // '+' concatenates strings if any operand is a string
console.log("Total Age: " + totalAge); // Output: "Total Age: 255"
// Fix for Example 2: Explicitly convert the string "false" to a Boolean value
let isValid = Boolean("false"); // This is correct technically, but to demonstrate explicit conversion:

// Better way: explicitly convert string to Boolean based on content
let isValidExplicit = String("false") === "true"; // Now, isValidExplicit is false
if (isValidExplicit) {
console.log("This is valid!");
} else {
console.log("This is NOT valid!"); // This will run because "false" !== "true"
}

// Fix for Example 3: Convert age string to number before adding
let totalAgeCorrected = Number(age) + 5; // Explicitly convert string to number
console.log("Total Age (number): " + totalAgeCorrected); // Output: 30