Javascript : assign variable in if condition statement, good practice or not?
Posted
by Michael Mao
on Stack Overflow
See other posts from Stack Overflow
or by Michael Mao
Published on 2010-04-05T01:49:05Z
Indexed on
2010/04/05
1:53 UTC
Read the original article
Hit count: 302
JavaScript
Hi all:
I moved one years ago from classic OO languages such like Java to Javascript. The following code is definitely not recommended (or even not correct) in Java:
if(dayNumber = getClickedDayNumber(dayInfo))
{
alert("day number found");
}
function getClickedDayNumber(dayInfo)
{
dayNumber = dayInfo.indexOf("fc-day");
if(dayNumber != -1) //substring found
{
//normally any calendar month consists of "40" days, so this will definitely pick up its day number.
return parseInt(dayInfo.substring(dayNumber+6, dayNumber+8));
}
else return false;
}
Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean.
For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced javascript developers?
Many thanks in advance.
© Stack Overflow or respective owner