Why does the following JavaScript code work?
Hello ();
function Hello () {
alert ("Hello, world!");
}
But for C, this would be an error:
#include "stdio.h"
void Main () {
hello ();
}
void Hello () {
printf ("Hello, worldn");
}
Since hello is not previously declared, the Code "Hello ()" is considered to be an implicit declaration, and the return type of the implicit declaration is int, so the hint Hello type error.
It is easy to solve this problem by either declaring it beforehand or putting the main function behind the Hello function.
So what does it mean for JavaScript to work?
The statement that was promoted
The JavaScript engine interprets the code first, the declaration is promoted, and then executes. For example, in order to determine whether a variable is defined or not, if we write this, the reference is incorrect:
if (Somevar = = undefined) {
alert ("Somevar undefined");
}
But if this doesn't go wrong:
if (Somevar = = undefined) {
var somevar = 1;
Alert ("Somevar not Defined");
}
The visible declaration was elevated, but only the declaration was promoted, because Somevar remained equal to undefined, not 1.
It is worth mentioning that this kind of writing will also be an error:
if (Somevar = = undefined) {
somevar = 1;
Alert ("Somevar not Defined");
}
This proves that implicit declarations are of no effect at the interpretation stage! And to make the code logically clear, use explicit declarations!