tags:

views:

291

answers:

6

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 : " + dayNumber);
}
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.

Edit : I will leave the question open for a moment just to collect more invaluable info :)

+1  A: 

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

quixoto
@quixoto : Could I do this trick in Java? I wonder... I don't have jdk by hand atm so I am unable to get a sample code in Java. From my poor memory, Java will just get you a Runtime error if the returning value evaluates something not boolean as in if conditional statement, right?
Michael Mao
Ah, yes, in Java it's type-checked to be a boolean type. But you *can* do `if (foo = getSomeBoolValue()) { }`
quixoto
@quixoto : yeah that's right. a boolean variable to test whether something succeeded and another variable to store the value returned. That's how Java does its job, I am too familiar with that so I feel strange to see Javascript can do two things in one mere line :)
Michael Mao
A: 

I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.

Justin Ethier
I don't consider it a good practice in C either.
Matthew Crumley
+2  A: 

I did it many times. To bypass the JavaScript warning, I add two parens:

if ((result = get_something())) { }

You should avoid it, if you really want to use it, write a comment above it saying what you are doing.

SHiNKiROU
@SHiNKiROU : how can I see javascript warnings? Is there a Javascript compiler? or the interpreter will generate some sort of warning? I am using Firefox console as in javascript debugging all the time but never see any similar outputs. Sorry about my limited experience.
Michael Mao
@Michael: JSLint (http://www.jslint.com/) is a popular program/library that checks JavaScript programs for possible mistakes or bad code.
Matthew Crumley
Use Mozilla Firefox with Firebug and/or Web Developer extension to check warnings.
SHiNKiROU
+2  A: 

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or ===. For example, when you see this:

if (value = someFunction()) {
    ...
}

you don't know if that's what they meant to do, or if they intended to write this:

if (value == someFunction()) {
    ...
}

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
    ...
}
Matthew Crumley
@Matthew Crumley : this answers my question in a clear way. I am not checking by assigning but checking whatever the value evaluates to be after the assignment. Is this understanding right?
Michael Mao
@Michael: yes, that's correct. Adding the comparison basically just makes your intentions more clear.
Matthew Crumley
A: 

It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.

You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.

thethanghn
@thethanghn: that exactly what I am afraid of. when I get older and lazy I just don't want to type more into the code if fewer keystrokes will just suffice :)
Michael Mao
+1  A: 

You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

The code:

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException 
{
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}
Nitrodist
@Nitrodist : thanks for this example. I am really not pro in either Java or javascript... It is good to know this approach is also feasible in Java :)
Michael Mao