a friend of mine asked me why this code doesn't work properly by canceling prompt.
<script type="text/javascript">
var name = prompt("Enter your name:", "");
if (!name) {
name = "unknown";
}
var ans =("<h2>" + "Hello, "+ name + "!"+"</h2>");
document.write(ans);
</script>
Here is jsfidle https://jsfiddle.net/085svr3u/
I found out, that in the example above propmt returns "null" ie. null as string by cancel. And I have no idea why.
I tried to play with original code and refactored it a bit. Now it works as expected. But I still have no explanation.
<script type="text/javascript">
function test() {
var name = prompt("Enter your name:", "");
if (!name) {
name = "unknown";
}
var ans =("<h2>" + "Hello, "+ name + "!"+"</h2>");
document.write(ans);
}
test();
</script>
And here is modified version https://jsfiddle.net/085svr3u/1/
Thank you in advance.