+ 2

Why is document.prototype.write() not writing a variable which was declared afterwards?

I've seen the code below in a JavaScript challenge, and I can't figure out why it returns "John Doe" and not "LawrenceJohn Doe". EDIT: "John Doe" only appears when you run the code the first time after loading it. https://code.sololearn.com/Wgxy1BjZ2mFs/?ref=app

31st May 2020, 6:40 AM
Michael55555
Michael55555 - avatar
11 ответов
+ 4
Michael55555 document.write could give peculiar output, we should never use document.write for webpage updating. Check out the warning about document.write here https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#document.write() I still dont understand why do so many tutorials show the code example in document.write, document.write should be avoided at all costs. Beginners should learn document class methods like document.querySelector, document.getElementById to update their web documents.
31st May 2020, 7:52 AM
Calviղ
Calviղ - avatar
+ 4
I'm not answering the question but adding to it: When you run code first time it gives you "John doe" and then run it again instantly then it will give you LawrenceJohn Doe
31st May 2020, 7:18 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 2
https://code.sololearn.com/WBS9QvxnQkwu/?ref=app https://code.sololearn.com/WduqP1t76BIY/?ref=app Here are the two parts separated.. I guess in the first attempt method calls are faster than accessing variables declared later.. Maybe this is because of Sololearn.. I'll edit this after trying on Pc..
31st May 2020, 7:42 AM
$hardul B
$hardul B - avatar
+ 2
https://code.sololearn.com/W5cHNRqSxoXe/?ref=app Calviղ is the issue cause document.write first did function call printed it and then it found the variable but displayed the update on refreshing /re running the code? 😅 Cause the time in first run seems smaller than the second run
31st May 2020, 8:01 AM
$hardul B
$hardul B - avatar
+ 2
Calviղ Thank your for your answer. I wonder why this volatile method is not deprecated yet.
31st May 2020, 8:29 AM
Michael55555
Michael55555 - avatar
+ 1
Abhay It doesn't work and it doesn't solve my question unfortunately. I was asking about this specific code, and for the reason why it's not working.
31st May 2020, 6:49 AM
Michael55555
Michael55555 - avatar
+ 1
Abhay I'm not quite sure if I understand that 🤔. I tried your code in the way you suggested it below, and it doesn't seem to work. https://code.sololearn.com/WcQDYA11TK4u/?ref=app
31st May 2020, 6:58 AM
Michael55555
Michael55555 - avatar
0
Try this document.write(name+" "+printName())
31st May 2020, 6:44 AM
Abhay
Abhay - avatar
0
Because write method has last parameter printname that print john doe To print lawdaJoh deo replace , by +
31st May 2020, 6:54 AM
Abhay
Abhay - avatar
0
Abhay It doesn't work for me 😕.
31st May 2020, 5:36 PM
Michael55555
Michael55555 - avatar
- 1
Just remove extra space around + sign in my method Spaces r ur bug My method is true
31st May 2020, 4:29 PM
Abhay
Abhay - avatar