While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior.
Let's explore this scenario:
function hello(name) {
let greet = 'Hello '
alert(greet + name)
}
hello('world')
alert(greet)
Initially, "Hello world" is displayed, followed by a
ReferenceError: greet is not defined
.
Now, consider the following:
function hello(name) {
var greet = 'Hello '
alert(greet + name)
}
hello('world')
alert(greet)
Once again, we encounter a ReferenceError
, as anticipated.
Finally, let's see the last example:
function hello(name) {
greet = 'Hello '
alert(greet + name)
}
hello('world')
alert(greet)
We observe "Hello world" followed by "Hello ", which is the expected outcome.
Strangely enough, reverting back to the first or second example still produces results from the last example. The ReferenceError
never resurfaces.
Could this be a peculiar glitch in Firefox's scratchpad? Or is there a deeper aspect of the language that I am unaware of?