+ 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;

16th Mar 2020, 3:32 AM
@HanuV9d
@HanuV9d - avatar
4 Respostas
+ 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 ...
16th Mar 2020, 3:52 AM
EmmanueLZ.
EmmanueLZ. - avatar
+ 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
16th Mar 2020, 4:00 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 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());
16th Mar 2020, 4:08 AM
A͢J
A͢J - avatar
+ 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
16th Mar 2020, 4:11 AM
EmmanueLZ.
EmmanueLZ. - avatar