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
447
votes
8 answers

How to make "if not true condition"?

I would like to have the echo command executed when cat /etc/passwd | grep "sysa" is not true. What am I doing wrong? if ! [ $(cat /etc/passwd | grep "sysa") ]; then echo "ERROR - The user sysa could not be looked up" exit 2 fi
Sandra Schlichting
  • 25,050
  • 33
  • 110
  • 162
431
votes
5 answers

if, elif, else statement issues in Bash

I can't seem to work out what the issue with the following if statement is in regards to the elif and then. Keep in mind the printf is still under development I just haven't been able to test it yet in the statement so is more than likely wrong. The…
StuStirling
  • 15,601
  • 23
  • 93
  • 150
420
votes
14 answers

Is "else if" faster than "switch() case"?

I'm an ex Pascal guy, currently learning C#. My question is the following: Is the code below faster than making a switch? int a = 5; if (a == 1) { .... } else if(a == 2) { .... } else if(a == 3) { .... } else if(a == 4) { …
Ivan Prodanov
  • 34,634
  • 78
  • 176
  • 248
399
votes
8 answers

How to check if a string contains an element from a list in Python

I have something like this: extensionsToCheck = ['.pdf', '.doc', '.xls'] for extension in extensionsToCheck: if extension in url_string: print(url_string) I am wondering what would be the more elegant way to do this in Python (without…
tkit
  • 8,082
  • 6
  • 40
  • 71
399
votes
13 answers

Else clause on Python while statement

I've noticed the following code is legal in Python. My question is why? Is there a specific reason? n = 5 while n != 0: print n n -= 1 else: print "what the..." Many beginners accidentally stumble on this syntax when they try to put an…
Ivan
  • 28,999
  • 6
  • 24
  • 21
397
votes
7 answers

What's the scope of a variable initialized in an if statement?

This could be a simple scoping question. The following code in a Python file (module) is confusing me slightly: if __name__ == '__main__': x = 1 print x In other languages I've worked in, this code would throw an exception, as the x…
froadie
  • 79,995
  • 75
  • 166
  • 235
387
votes
12 answers

Pythonic way to combine for-loop and if-statement

I know how to use both for loops and if statements on separate lines, such as: >>> a = [2,3,4,5,6,7,8,9,0] ... xyz = [0,12,4,6,242,7,9] ... for x in xyz: ... if x in a: ... print(x) 0,4,6,7,9 And I know I can use a list comprehension to…
ChewyChunks
  • 4,449
  • 3
  • 22
  • 14
377
votes
17 answers

How to write an inline IF statement in JavaScript?

How can I use an inline if statement in JavaScript? Is there an inline else statement too? Something like this: var a = 2; var b = 3; if(a < b) { // do something }
356
votes
32 answers

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

So far whenever I needed to use a conditional statement within a Widget I have done the following (Using Center and Containers as simplified dummy examples): new Center( child: condition == true ? new Container() : new Container() ) Though when…
Marko
  • 4,857
  • 5
  • 17
  • 21
346
votes
4 answers

break out of if and foreach

I have a foreach loop and an if statement. If a match is found i need to ultimately break out of the foreach. foreach ($equipxml as $equip) { $current_device = $equip->xpath("name"); if ($current_device[0] == $device) { // Found a…
au_stan
  • 4,011
  • 2
  • 19
  • 24
339
votes
5 answers

An "and" operator for an "if" statement in Bash

I'm trying to create a simple Bash script to check if the website is down and for some reason the "and" operator doesn't work: #!/usr/bin/env bash WEBSITE=domain.example SUBJECT="$WEBSITE DOWN!" EMAILID="an@email.example" STATUS=$(curl -sI $WEBSITE…
HTF
  • 6,632
  • 6
  • 30
  • 49
319
votes
13 answers

if...else within JSP or JSTL

I want to output some HTML code based on some condition in a JSP file. if (condition 1) { Some HTML code specific for condition 1 } else if (condition 2) { Some HTML code specific for condition 2 } How can I do that? Should I use JSTL?
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
313
votes
13 answers

JavaScript single line 'if' statement - best syntax, this alternative?

It's been clearly put, although opinion none the less, that forgoing curly brackets on a single line if statement is not ideal for maintainability and readability. But what about this? if (lemons) { document.write("foo gave me a bar"); } It's even…
David Hobs
  • 4,351
  • 2
  • 21
  • 22
294
votes
6 answers

Meaning of "[: too many arguments" error from if [] (square brackets)

I couldn't find any one simple straightforward resource spelling out the meaning of and fix for the following BASH shell error, so I'm posting what I found after researching it. The error: -bash: [: too many arguments Google-friendly version: bash…
user56reinstatemonica8
  • 32,576
  • 21
  • 101
  • 125
293
votes
8 answers

"elseif" syntax in JavaScript

How can I achieve an elseif in a JavaScript condition?
Hari Gillala
  • 11,736
  • 18
  • 70
  • 117