let x;
x = prompt("Write something: ", "");
console.log("NaN" == 1); //this will always be false
console.log(1 * x); //x is multiplied by 1 if it is a number
//if x is a letter prints 'NaN'
//if x is null prints 0 because x is converted to a number and when we do this conversion null becomes 0
//if x is empty space also prints zero because when javascript converts " " to a number the result is 0
console.log(x + ""); //x is converted to a string if it is a number, but this essentially just prints the value of x
console.log("NaN" == 1 * x + "");
//because of the order of operations, our first step is to multiply 1 by x
//if x is a space, the result is 0 | 1 * " " = 0
//if x is null, the result is 0 | 1 * null = 0
//if x is a letter, returns NaN | 1 * A = NaN
//if x is a number, returns the number | 1 * 2 = 2
//next we add "" to whatever value we got in the first step
//if the current value of x is 0 we are left with "NaN" == 0, which is false
//if the current value of x is a letter, we are left with "NaN" == "NaN", which is true
//if the current value of x is a number, we are left with "NaN" == *a number* which is false
if ((x === null) || ( x.trim() === "")) { //check if x is empty space
alert("Nothing was written");
} else {
if (Number(x) === "NaN") { //will return true if x contains letters
alert(Number(x));
} else {
alert(Number(x)); //we end up here if x is a number
}
}
Ok, so the above should answer your first question. As for the second, it doesn't matter how you initialize x because on the next line you assign it a value. This value is a String, and JavaScript only tries to convert it to a number once you start doing math with it.