This is a hard one. I will try to explain with some simple examples. So one important thing, in this question is also to understand the execution context
.
Lexical Environment
Means where you write something in the code is important. Not all programming languages are like that, but javascript is.
So if you have a function like
function hello() {
var myVar = 'hello';
}
Now the variable myVar
sits lexically inside the function. That's physically the code that you're writing.
In short, if talking about lexical environment
means where it is written and what surrounds it.
Variable Environment
Every time you call a function a new execution context will be created. So even myVar is declared 3 times (see next example) they do not touch each other. That's when you talk about Variable Environment
function b() {
var myVar;
console.log('three', myVar) // three undefined
// cause myVar is newly declared in b()
// but has no value
}
function a() {
var myVar = 2;
console.log('two', myVar) // two 2
b();
}
var myVar = 1;
console.log('one', myVar) // one 1
a();
console.log('four', myVar) // one 1
Now you where asking for the difference which I guess it is just the theoretical talk about two things. But also the lexical environment
kinda knows where the variables are sitting in memory.
So that is actually the answer to your question. But I will show some more examples just to make sure where things can go wrong with misunderstanding.
Because there is also this thing called hoisting
in javascript which can give you errors if you write code at the wrong place. And it can have strange behaviour. The next examples are actually very simple but all depend on Lexical Environemnt
, Variable Environment
, Execution Context
and hoisting
console.log(myVar); // undefined
var myVar = 'hello';
console.log(myVar); // hello
but
function a() {
console.log(myVar) // gives Error myVar is not defined
}
a();
but again:
function a() {
console.log(myVar); // undefined no Error
// cause it would take myVar from global
// execution context
// but also no error cause we define it again
// in this function (hoisting)
var myVar = 0; // define myVar newly in this lexical environment
console.log(myVar); // 0
}
var myVar = 'hello';
a();
console.log(myVar); // hello
But again if we do like so
function a() {
myVar = 0; // overwrite global myVar
console.log(myVar); // 0
}
var myVar = 'hello';
a();
console.log(myVar); // 0 did you expect myVar to be 0 ?