Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError and undefined

Tags:

javascript

I'm a bit confused by this js behavior.

function foo(){
  console.log(a)
}

foo() // ReferenceError: a is not defined

In this case everything is understandable. There is no a defined in the global scope, therefore we get the ReferenceError.

Now, this is a second example:

function foo(){
  console.log(this.a)
}

foo() // undefined

So, this points to the global scope where there is no a defined. Shouldn't we get the same ReferenceError ? Why do we get undefined ?

like image 840
Noob Avatar asked Dec 13 '25 14:12

Noob


1 Answers

Basically Reference error will come when you use a variable which are not declared yet, whereas undefined will come when you try to get some properties from the object and key is not present in an object, or you make a variable itself undefined

Ex.

undefined

  const obj = { };
  const array = [];
  const newObj = undefined;

  console.log(obj.id);// undefined
  console.log(newObj);// undefined
  console.log(array[0]);// undefined

Reference Error

 const obj = { };
 console.log(obj[id] = id);

Note this is also an object, In your case you try to access value of a from this

So it's looks like

const this = {};
console.log(this.a) // undefined
like image 82
Neel Rathod Avatar answered Dec 15 '25 05:12

Neel Rathod