Undefined and Not Defined

Undefined and Not Defined

Table of contents

Undefined :

You can only find undefined in Javascript, not in any other languages. But you guys must be wondering what undefined is.

Undefined is a very special word in Javascript that gets stored inside the variable during the memory execution phase, let's get deep into it.

so when our Javascript Program Executes, a global execution context is created which is divided into two phases

  1. Memory Phase

  2. Code Execution Phase

var username = 'deepak'
console.log(username)

function displayDetails(){
  console.log(firstname)
}

displayDetails()

so how this piece of code will execute?

1st of all memory allocation phase will be done in this phase all the variables and functions were being allocated some memory, and this is the time when the undefined will come into the picture in PhaseOne (Memory Phase) variable username is being stored with a special keyword called undefined.

and it will remain stored inside it until and unless we move to the code execution phase.

so this is what undefined is a special keyword that is being assigned to the variables during the memory allocation phase.

Not Defined :

if we will try to access something which is not declared. lets get into an example:

var username = 'deepak'
console.log(username)

function displayDetails(){
  console.log(firstname)
}

displayDetails()

in the above piece of code we will get an error as :

ReferenceError: firstname is not defined

because I haven't declared firstname anywhere in the program and the javascript engine will not be able to find it, It is the username that I have declared. if we will console for username then we will not get any error.