What is JavaScript type coercion?

JavascriptWeb DevelopmentObject Oriented Programming

Type coercion means conversion of a datatype to another automatically or implicitly.

Following is the code for JavaScript type coercion −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript type coercion</h1>
<div class="sample">22</div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to add the above number with 5.</h3>
<script>
   let sampleEle = document.querySelector('.sample');
   let resEle = document.querySelector(".result");
   document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = ' "22" + 5 = ' + sampleEle.innerHTML+5;
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 16-Jul-2020 07:16:17
Advertisements