Home Ask Us Test Your Skill : Why is the variable showing as undefined

Test Your Skill : Why is the variable showing as undefined

by Anup Maurya
2 minutes read

Why is the p variable showing as undefined when setting the innerText of the name element to p.name?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="usname"> </p>
    <script>    
    const p="";

    const app= async()=>{
       const data= await fetch("https://api.github.com/users/Anup-maurya");
       const p= await data.json();
       console.log(p);
    }
  
    app();
    const name=document.getElementById("usname");
       name.innerText=p.name;

    
    </script>
</body>
</html>

The issue you’re encountering is related to the asynchronous nature of JavaScript. When you try to access p.name immediately after calling app(), the p variable hasn’t been assigned the fetched data yet because await fetch() is still pending. As a result, p remains an empty string ("") when you access it outside the app() function.

To fix this, you need to set the text content of the <p> element inside the app() function after you have fetched and processed the data. Here’s the corrected code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="usname"> </p>
    <script>    
    const app = async () => {
       try {
           const data = await fetch("https://api.github.com/users/Anup-maurya");
           const userData = await data.json();
           console.log(userData);
           const nameElement = document.getElementById("usname");
           nameElement.innerText = userData.name;
       } catch (error) {
           console.error("Error fetching data:", error);
       }
    }
  
    app();
    </script>
</body>
</html>

In this corrected code:

  1. The nameElement.innerText = userData.name; line is moved inside the app() function after the data has been fetched and processed.
  2. I’ve renamed the variable p to userData to make it clearer that it contains the fetched user data.

This way, the <p> element’s text content will be set to the user’s name after the data has been successfully fetched and processed.

related posts

Leave a Comment

Enable Notifications OK No thanks