In this articles, we learn JavaScript Hoisting, Global Pollution, Undefined, and Reference Error.
1.JavaScript Hoisting:
Hosting is a JavaScript mechanism where
variables and function declarations are moved to the top of their scope before
code execution.
Hoisting is a mechanism in JavaScript that moves
the declaration of variables and functions at the top. So, in JavaScript, we can
use variables and functions before declaring them.
JavaScript hoisting is applicable only for
declaration, not initialization. It is required to initialize the variables and
functions before using their values.
Example of JavaScript Variable Hoisting:
Program:
Example of JavaScript Function Hoisting:
Program:
Output:
2.Global Pollution:
In JavaScript, we have to declare the variables with 'var' keyword, then the variable declared as local if we do not declare variables with var keyword then the variables become global and this variable split outside a function so that anyone can modify those variables.
Without a 'var' keyword, the variable is considered as a global variable and it can be accessed anywhere in the program.
Example:
Output:
Here, the value of x is not displayed because the variable is declared with the 'var' keyword,i.e called a local variable.
Output:
Here, variable x is not declared with the var keyword, i.e called as global pollution.
3.Undefined:
JavaScript is interpreted language that means it complies the code line by line.
Undefined means the variable is declared but not assigned any value then variable returns undefined value.
If we print one variable before declaring and assigning value then it gives the message is undefined.
Output:
4. Reference Error:
The reference error the object represents an error when a non-existent variable referenced somewhere.
No comments:
Post a Comment