TypeError: ‘undefined’ is not an object in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

The “TypeError: ‘undefined’ is not an object” error occurs when a property is accessed or a method is called on an undefined object. This error is shown only on safari browser.

Following is the code for TypeError − ‘undefined’ is not an object error in JavaScript −

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>TypeError: ‘undefined’ is not an object example</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to access the name property of person object</h3>
<script>
   var resEle = document.querySelector('.result');
   var BtnEle = document.querySelector('.Btn');
   var person;
   BtnEle.addEventListener('click',function(){
      try{
         alert(person.name);
      }
      catch(err){
         resEle.innerHTML=err;
      }
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


raja
Published on 17-Jul-2020 11:49:38
Advertisements