Why is variable assignment not happening?

I’m experimenting with the code below…

The first block of code manages to execute.


var ans = prompt('Are you sure you want to do that?', '');

if (ans) {
	alert('You answered ' + ans + '.');
} else {
	alert('You refused to answer!');
}

The second block of code is:


if (var ans = prompt('Are you sure you want to do that?', '')) {
	alert('You answered ' + ans + '.');
} else {
	alert('You refused to answer!');
}

I’m assuming that the second block of code does the same thing as the first block but for some reason…when i use the second block of code…it doesn’t work :frowning:

The prompt does not even appear when the page loads (something i expected to the browser to do)…

I’m new to this…please do let me know if i’m doing something wrong

Logics for the second block of code:

If the assignment of the variable “ans” succeeds via the value received from prompt, alert the ans else alert that you refused to answer.

The first block of code is better though, because it’s easier to read and less likely to lead to confusion. This is because it isn’t common to do variable assignments in the conditional bits of if statments.

What browser is this in? I seem to recall that creating variables in if-else statements is technically illegal, but most browsers allow it anyway. (It’s possible I’m just making that up.)


var ans;
if (ans = prompt('Are you sure you want to do that?', '')) {
    alert('You answered ' + ans + '.');
} else {
    alert('You refused to answer!');
}

Bye