+ 2
javascript variable declaration error
<script> var test1="hello"; console.log(test1 + test2); var test2="world"; </script> I thought this code will give error "test2 is not defined" because till second line var test2 was not defined but when i run i surprised it outputs without any error on console "helloundefined"; can someone explain please;
4 Answers
+ 2
@Vinod Kumar hi,
I think it has something to do with "hoisting" which means when javascripts read the file every variables and function are first placed at the top of the code ...
+ 2
You should write The definition
Of test 2 variable before console function
To let the program show test 2 before use it in console function
https://www.w3schools.com/js/js_hoisting.asp
+ 2
Vinod Kumar It will not give error because we are not doing operation with that variable but it print undefined because it's also a value.
But if we do some operation on test2 then it gives error. If you want to test just check this example:-
var test1="hello";
console.log(test1.toUpperCase());
console.log(test2.toUpperCase());//error will come
var test2="world";
console.log(test2.toUpperCase());
+ 2
Here is an article about hoisting,
the declaration is hoisted,but not it initialisation.
It works with var but not let or const.
https://www.w3schools.com/js/js_hoisting.asp