Undeclared vs Undefined? In JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Undeclared − It occurs when a variable which hasn’t been declared using var, let or const is being tried to access.

Undefined − It occurs when a variable has been declared using var, let or const but isn’t given a value.

Following is the code for undeclared and undefined in JavaScript −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
<h1>Undeclared vs Undefined</h1>
<div class="result"></div>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to access undeclared and undefined variable</h3>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelectorAll(".result");
   let a;
   BtnEle.addEventListener("click", () => {
      resEle[0].innerHTML += "Accessing undefined variable = " + a;
      try {
         resEle[1].innerHTML = b;
      } catch (err) {
         resEle[1].innerHTML = "Accessing undeclared variable = " + err;


On clicking the ‘CLICK HERE’ button −

Published on 16-Jul-2020 17:22:25