+ 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
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.
+ 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
+ 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..
+ 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
+ 2
Calviղ Thank your for your answer. I wonder why this volatile method is not deprecated yet.
+ 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.
+ 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
0
Try this
document.write(name+" "+printName())
0
Because write method has last parameter printname that print john doe
To print lawdaJoh deo replace , by +
0
Abhay It doesn't work for me 😕.
- 1
Just remove extra space around + sign in my method
Spaces r ur bug
My method is true