Questions tagged [if-statement]

An "if" statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If statements are also commonly also called conditionals. When using this tag please also include an appropriate language tag, such as e.g. "java" if your question is language-specific.

An if statement is a flow control structure in most programming languages that branches execution flow depending on a binary condition, generally evaluated at runtime. If-statements are also commonly known as conditionals.

When using this tag please also include an appropriate language tag, such as e.g. if your question is language-specific.


Basic Syntax

The if statement has the following syntax:

if <condition>
then
     <statement-1>
else
     <statement-2>

<condition> may be parenthesized (as it is in JavaScript), the keyword then may be omitted (Python, C-like languages, JavaScript and others).

The else section is optional in most languages.

An example if statement in JavaScript:

var myVariable = 100;

if (myVariable >= 20) {
    console.log('My variable is greater than or equal to 20!');
} else {
    console.log('My variable is less than 20!');
}

if-else statements may also be nested, where another if may appear in if statement, and/or in else statement. For example:

if ( number1 > 20 )
   if ( number2 > 50 )
      print('Both numbers satisfy condition')
   else
      print('Second number doesn't satisfy condition')
else
   if( number2 > 50 )
      print('Only Second number satisfies condition')
   else
      print('None of the two numbers satisfy condition')

else+if is used to chain if statements:

if ( number > 20 )
     print('Greater than 20')
else+if ( number > 10 )
     print('Greater than 10')
else
     print('Less than 11')

else+if statements may simply be an else statement followed by an if (e.g else if; done in JavaScript and many C-like languages), or a special keyword such as elif (Python), or elsif (Perl).


As a ternary operator

In C and C-like languages, conditional expressions can take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:

(condition)?(evaluate if condition was true):(evaluate if condition was false)

In Python, if is used explicitly, and the ordering is slightly different:

(evaluate if condition was true) if (condition) else (evaluate if condition was false)

An example of the ternary operator in JavaScript:

var myVariable = 100;

myVariable>20 ? console.log('Greater than 20!') : console.log('Less than or equal to 20!');

See also:

61703 questions
7
votes
4 answers

Why if/else vs. or/exit in PHP?

Seeing the exit() PHP documentation got me thinking: $filename = '/path/to/data-file'; $file = fopen($filename, 'r') or exit("unable to open file ($filename)"); Couple questions: What are common use cases besides opening files for using…
tim peterson
  • 23,653
  • 59
  • 177
  • 299
7
votes
1 answer

Excel conditional Hyperlink outputs the Hyperlink for both conditions

I think I must be going mad here, what I want to do is to write a simple Excel formula that performs an IF test, and if the result is false I want to hyperlink some text, if it is true I want to display some text which is not hyperlinked. So for…
McVicar
  • 113
  • 1
  • 3
  • 7
7
votes
3 answers

Using ifelse on factor in R

I am restructuring a dataset of species names. It has a column with latin names and column with trivial names when those are available. I would like to make a 3rd column which gives the trivial name when available, otherwise the latin name. Both…
ego_
  • 1,409
  • 6
  • 21
  • 31
7
votes
1 answer

How to represent an if statement on a sequence diagram in DIA?

Does anyone know how to represent an if statement on a sequence diagram in DIA?
luistm
  • 1,027
  • 4
  • 18
  • 43
7
votes
3 answers

Groovy: does if-then statement have a local scope?

Not sure if I am asking correctly, but I have something like the following: def x = 1 if (x == 1) { def answer = "yes" } println answer I get the error - No such property: answer for class... However, this works: def x = 1 def answer =…
user1435174
  • 71
  • 2
  • 3
7
votes
3 answers

SQL Server performance - IF Select + Update vs Update

I'm writing a big script, full of update statements that will run daily. Some of this updates will affect rows others won't. I believe that update statements that won't affect anything is not very good practice, but my question is: How badly can…
7
votes
6 answers

If statement - 'or' but NOT 'and'

In C Sharp, how can I set up an if statement that checks if one of several conditions is true? It must be only one of the conditions, if zero or two or more are true the if should be false.
Wilson
  • 8,570
  • 20
  • 66
  • 101
7
votes
3 answers

Difference between `if (isset($_SESSION))` and `if ($_SESSION)`?

I've noticed that frequently people simply write while I have been using: Could someone explain the difference when checking if a variable is set (that's…
d-_-b
  • 21,536
  • 40
  • 150
  • 256
7
votes
3 answers

if number is between two numbers by plus/minus 10 addclass

http://jsfiddle.net/kM8xE/2/ If I have the divs ​
15
20
​ and jQuery var actual = $(".value").html(); var comparison = $(".value2").html(); how can i add class .isbetween to .value2 if it's html…
Yusaf Khaliq
  • 3,333
  • 11
  • 42
  • 82
6
votes
3 answers

MySQL If statement issue

I am trying to make this IF statement work, but I can't seem to make it do what I want. If I do a select @result, It'll give me the value 0, then why doesn't the IF statement work? SET @message = '((sometihng here))'; select LEFT(@message, 1) into…
Myy
  • 18,107
  • 11
  • 37
  • 57
6
votes
5 answers

Pythonic way to increment and assign ids from dictionary

This seems to be a pretty common pattern: for row in reader: c1=row[0] if ids.has_key(c1): id1=ids.get(c1) else: currid+=1 id1=currid ids[c1]=currid I want to know if there is a better way to achieve…
Sid
  • 7,511
  • 2
  • 28
  • 41
6
votes
5 answers

Test for multiple values in an if statement in C#

Is there a shorthand syntax in C# to make this: if ((x == 1) || (x==2) || (x==5) || (x==13) || (x==14)) ... shorter? Something like (hypothetically) if (x in {1, 2, 5, 13, 14}) I "feel" like it exists, I'm just coming up short mentally and Googly.…
Adamlive
  • 139
  • 1
  • 2
  • 9
6
votes
8 answers

If Then Else Shorthand Won't Work Without Assignment

In C#, I am trying to shorten some of my return code. What I want to do is something like condition ? return here:return there; or condition ?? return here; I am having some issues though, the compiler says the expression is not valid. Here is…
Travis J
  • 81,153
  • 41
  • 202
  • 273
6
votes
5 answers

if statement in javascript always true

So, I have the code, its not done, but all i want it to do is display one alert box if I write the word 'help', and say something else if anything else is entered. function prompter() { var reply = prompt("This script is made to help you learn…
Billjk
  • 10,387
  • 23
  • 54
  • 73
6
votes
1 answer

razor syntax: loop with ifs and divs

It's my first post, hence hello :) I want to conditionally open and close div. What am I doing wrong? @foreach (var m in Model.Recipes) { if (left) {
} if (left) {
Mariusz.W
  • 1,347
  • 12
  • 19
1 2 3
99
100