How to Assign a Variable in an If Else Statment Check

Assign variable in if condition statement, good practice or not?

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>) {
...
}

Assign variable and check it within an IF evaluation

Yes you can do it, like so:

var myString = "Hello World";
int pos;

if ((pos = myString.IndexOf("World")) >= 0)
{
Console.WriteLine(pos); // prints 6
}
else if ((pos = myString.IndexOf("Some Other Substring")) >= 0)
{
// Do whatever
}

Note that I'm using myString.IndexOf(...) >= 0 as the index of the substring could be 0 (i.e starting at the first character), and the IndexOf method returns -1 if none was found

But you could rather just use string.Contains like so:

var myString = "Hello World";

if (myString.Contains("World"))
{
// Do whatever
}
else if (myString.Contains("Some Other Substring"))
{
// Do whatever
}

This is better if you don't explicitly need the location of the substring, but if you do, use the first one

Assigning value to variable using if statement

You cannot use a statement to assign into a variable. For the alternate solution use conditional/Ternary operator

Syntax

const var_name = condition ? true_value : false_value

Example

const w = 2 > 1 ? 1500 : 2500

How to assign a string to a variable using if else in javascript?

Remove let before amount in if else statements and the code will work as expected. The issue is, by using let again and again in if else statements, you're declaring amount variable again and again. Read about scope of let to learn more.

Assign variable value inside if-statement

Variables can be assigned but not declared inside the conditional statement:

int v;
if((v = someMethod()) != 0) return true;

Put a condition check and variable assignment in one 'if' statement

First, it assigns the value of B to A (A = B), then it checks if the result of this assignment, which is A and evaluates to 1, is equal to 1.

So technically you are correct: On the way it checks A against 1.

To make things easier to read, the code is equivalent to:

UINT A, B = 1;
A = B;
if(A == 1){
return(TRUE);
} else {
return(FALSE);
}


Related Topics



Leave a reply



Submit