4

I have a syntax question, lets say i have the following function. It received text for spell check and returns the correct text or false in case the text was already spelled correctly.

var spellCheck = function (txt) {
    var spelledTxt = spell(txt);
    if (spelledTxt =! txt) { //the text had a typo.
        return spelledTxt;
    }
    return false;
}

Now in a different function i want to call this function from an ElseIf statement, and i want to get into that statement only if the text had a typo which was corrected. something like:

if(something){
    do something....
}else if(spellCheck(word)){
    do something with the spelledTxt that was returned from "spellcheck"
}

Can i just do:

else if(var spelledWord = spellCheck(word))
    do something with spelledWord.

I forgot a very important thing: spellCheck(word) is very heavy function and i'd like to avoid calling it if not needed. This mean that only if we arrived to the else if() it will be called, and not sooner.

TBE
  • 1,002
  • 1
  • 11
  • 32

2 Answers2

5

Any expression is valid inside an if statement, and that includes an assignment expression. The value of an assignment expression is the assigned value.

In your case the return value of the function call is the value of the expression, but the var makes it a statement and not a simple expression.

You need to remove the variable declaration part from the statement and then it's fine.

Alternatively, you could simply do it like this:

else {
 var spelledWord = spellCheck(word);
 if(spelledWord)
    do something with spelledWord
}
Amit
  • 45,440
  • 9
  • 78
  • 110
  • the only problem with my code was the `var` inside the `else if` statement. the variable needs to be declared outside the `If` statement. – TBE Nov 29 '15 at 15:32
  • @TBE - ahh! I didn't even notice that you had `var` in there as I focused on the assignment part. Let me correct that. – Amit Nov 29 '15 at 15:35
-1

You can do that. The assignment operation returns a value, which you could use as a boolean expression.

But you should remember that:

  1. In Javascript var statement is function-scoped.
  2. There is a 'hoist' behavior in Javascript.
  3. As a result of 1,2 and some later code refactoring, you could easily introduce a bug to this code.
  4. Type coercion in Javascript is a bit messy.
  5. Reading code with side effects, where one operation could lead to 2 different logic outcomes simultaneously - is really hard work.

I'd consider using the strict comparison operators at least: if (spelledWord = spellCheck(word) !== '') And if it's possible, try to memoize (cache) results from calling spellCheck function. In that case, you wouldn't need to combine two operations into one at all.

Community
  • 1
  • 1
Microfed
  • 2,832
  • 22
  • 25