By default when we first create a variable in JavaScript and don’t initialize it with a value, that variable will get the value undefined.
The undefined value basically means the target variable does not have a value stored to it yet.
Example:
<!DOCTYPE html>
<html>
<head>
<title>JS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Output:</h3>
<p id = "link"></p>
<script>
let name;
document.getElementById("link").innerText =`${name}`;
</script>
</body>
</html>
In the first statement we’ve just declared the variable name but we didn’t store any value into that variable. So if we call the variable to get its value, we will get the undefined value.
We can also use the typeof operator to check and see if the current value of a variable is undefined.
<!DOCTYPE html>
<html>
<head>
<title>JS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h3>Output:</h3>
<p id = "link"></p>
<script>
let name;
if (typeof name == "undefined"){
document.getElementById("link").innerText = `There's no value in the 'name' variable`;
}else{
document.getElementById("link").innerText =`${name}`;
}
</script>
</body>
</html>
Note: You might also want to check the undeclared section because people often times confuse these two concepts with each other.