JS If Else


Check wether a condition is satisfied:

var n1 = 0;
var n2 = 0;
for (var i=1; i<=10; i++)
{
	if (arr[i] % 2 ==0 ) n2 += arr[i];
	else n1 += arr[i];
}


Check a value is true or false (false can be represented as 0, false, undefined, null, NaN or ""):

var x=true;
if (x) alert("true")
if (y) alert("true") // y is undefined


Use && (and), || (or) for multiple conditions:

for (var i=1; i<14; i++)
{
	if (arr[i] % 2 == 0 && (arr[i] % 3 == 0 || arr[i] % 5 == 0))
		alert(arr[i]); //6, 10
}


If () {...} else if (){...} else {...}:

for (var i=1; i<10; i++)
{
	if (arr[i] % 2 == 0)
	{
		alert("2"); //2,4,6,8
	}
	else if (arr[i] % 3 == 0)
	{
		alert("3"); //3,6,9
	}
	else
		alert("other"); //1,5,7
}

endmemo.com © 2020  Terms of Use | Home