How do JavaScript primitive/object types passed in functions?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to pass JavaScript primitive and object types to function −

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 {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Passing primitive/object types to function</h1>
<div class="result"></div>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to pass primitive and object to a function and call it</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let person = { name: "Rohan", age: 12, city: "Delhi" };
   function printObj(obj) {
      resEle.innerHTML = "Name = " + obj.name + "<br>";
      resEle.innerHTML += "age = " + obj.age + "<br>";
      resEle.innerHTML += "city = " + obj.city + "<br>";
   }
   function printPrimitive(prim) {
      resEle.innerHTML += prim;
   }
   BtnEle.addEventListener("click", () => {
      printObj(person);
      printPrimitive(22);
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


raja
Published on 16-Jul-2020 14:00:49
Advertisements