Vous êtes sur la page 1sur 4

1/21/2014

Comparison operators, if..else | JavaScript Tutorial


Log in

JavaScript Tutorial
Home Tutorial JavaScript: from the Ground to Closures First Steps Operators and constructs
Operators Loops and switch Tutorial

JavaScript: from the Ground to Closures


JavaScript: from the Ground to Closures Javascript and related technologies First Steps
First Steps

Comparison operators, if..else


Ilya Kantor

1. Logical conditions 2. Boolean conversions 3. String comparison 4. Comparison of different types 5. Strict equality 6. Special values 7. Ternary operator " ? "

Like

Setup your environment Hello, World! Variables and statements Browser Developer's Tools User interaction: alert, prompt and confirm Operators and constructs
Operators and constructs Operators

The i f . . e l s econstruct checks for a condition and executes different code whenever it is true or false. Most well-known comparison operators are: == >, <, >=, <= The i foperator checks it and executes the code if the condition is correct, or in other words, true: i f( p r i c e>1 0 0 ){ a l e r t ( ' E x p e n s i v e ! ' ) } The e l s eblock is executed when the condition is wrong or, in other words, false: 1 i f( p r i c e>1 0 0 ){ 2 a l e r t ( ' E x p e n s i v e ! ' ) 3 }e l s e{ 4 a l e r t ( ' G i v em e2 ! ' ) 5 } It is also possible to specify additional conditions using e l s ei f : 1 2 3 4 5 6 7 8 9 v a ra c c e s s / /t h ea c c e s sl e v e lo ft h eu s e rb a s e do nh i su s e r I d i f( u s e r I d>1 ){ a c c e s s=" v i s i t o r " ; }e l s ei f( u s e r I d= =1 ){ a c c e s s=" s u p e r u s e r " ; }e l s ei f( u s e r I d= =0 ){ a c c e s s=" a l l p o w e r e d g e n i e " ; }

Comparison operators, if..else Loops and switch

Functions: declarations and expressions Mastering data types Four scents of "this" Type detection Function arguments Static variables and methods Scopes and Closures Decorators

Document and Events Object Oriented Programming Timing Frames and windows Regular expressions in JavaScript Advanced and Extra stuff

Donate Donate to this project

Write the code to p r o m p tuser for a value, and a l e r t : 1, if the value is greater than zero, -1, if the value is less than zero, 0, if the value is zero. See it in action here: tutorial/intro/if_sign.html

Open solution

Logical conditions
Conditions can be combined by operators && (AND), || (OR) or negated by !(NOT). Check if xis more than 1 AND less than 5: 1 v a rx=3 2 3 i f( x > = 1& &x < = 5 ){ 4 a l e r t ( ' T h en u m b e ri sb e t w e e n1a n d5 ' ) 5 } Check if xis less than 10 OR more than 20: 1 v a rx=3

http://javascript.info/tutorial/comparison-operators-ifelse

1/4

1/21/2014

Comparison operators, if..else | JavaScript Tutorial

2 3 i f( x < 1 0| |x > 2 0 ){ 4 a l e r t ( ' T h en u m b e ri so u t s i d eo f1 0 . . 2 0i n t e r v a l ' ) 5 } Conditions can be grouped in brackets and negated by NOT: 1 v a rx=1 5 2 3 i f(! ( x < 1 0| |x > 2 0 )){ 4 a l e r t ( ' T h en u m b e ri s* i n s i d e *1 0 . . 2 0 ' ) 5 }

Write the code to p r o m p tfor a login. If the input is Monty, then p r o m p t for a password, for any other input a l e r tWrong login. If the user presses CANCEL (or Escape), do nothing. If the password is Cheese, then output Access granted, otherwise output Wrong password. See it in action here: tutorial/intro/if_pass.html

Open hint 1 Open solution

Warning! The task below looks complicated Write the code to p r o m p tfor a login. If the input is Monty or Chip, then p r o m p tfor a password, for any other input a l e r t Wrong login. If the user presses CANCEL (or Escape), do nothing. If the password is Cheese for Monty and Gadget for Chip , then output Access granted, otherwise output Wrong password. See it in action here: tutorial/intro/if_pass2.html

Open hint 1 Open solution

Boolean conversions
Traditionally, it is possible to put a value into i f . In this case, it gets converted into boolean.
Run!

1 v a rx=1 2 3 i f( x ){ 4 a l e r t ( ' t r u e ' ) 5 }

String comparison
String are compared in lexicographic order, also known as a phone-book order:
Run!

1 / /t r u e ,b e c a u s e" A n n a "w o u l dg oa f t e r" A b b a "i nap h o n eb o o k . 2 a l e r t (" A n n a ">" A b b a ") / /t r u e 1. The first character of the left string is compared against the first character of the right string. 2. If it is greater or less in alphabet order, then it becomes the result. 3. If they are equal, then go on to the next character. No-character is less than any character. Thats, again, like in the phone-book:
Run!

1 / /P o p ew o u l dg oa f t e rP o p 2 a l e r t (" P o p e ">" P o p ") / /t r u e

http://javascript.info/tutorial/comparison-operators-ifelse

2/4

1/21/2014
For strings, the comparison is case-sensivite . For example:
Run!

Comparison operators, if..else | JavaScript Tutorial

1 a l e r t ( ' a b b a '>' Z e n d ' )/ /t r u e Thats because a lowercased letter is always greater than an uppercased .

Comparison of different types


Comparison can be done for values of different types. To perform the comparison, the interpreter converts values to numbers. Here are the examples: a l e r t ( " 0 1 "<2 ) / /t r u e ," 0 1 "c o n v e r t st o1 a l e r t ( 1= =t r u e ) / /t r u e ,b e c a u s et r u ec o n v e r t st o1

Watch out when comparing numbers which you got as strings:


Run!

1 a l e r t (" 2 ">" 1 4 ")/ /t r u e Thats because of lexicographical order. Convert the values explicitly to make sure you are dealing with numbers.

Strict equality
Sometimes we need to differ between 0and f a l s e . How to check that?
Run!

1 a l e r t ( 0= =f a l s e )/ /t r u e ,b e c a u s ef a l s eb e c o m e s0 For such occasions, there are strict equality and inequality operators: = = =and ! = = . They do not convert type, so values of different types are always inequal.
Run!

1 a l e r t ( 0= = =f a l s e )/ /f a l s e ,b e c a u s ed i f f e r e n tt y p e s

Special values
Special values are inclined to really weird behavior in comparisons. Here is a couple of examples.

Crazy?
Come on, check it out:
Run!

1 a l e r t ( n u l l>0 ) ;/ /f a l s e 2 a l e r t ( n u l l= =0 ) ;/ /f a l s e And now tadaaaam:


Run!

1 a l e r t ( n u l l> =0 ) ;/ /t r u e8 ( ) How can it be? Its not greater, not equal, but > =returns true. Hint. Processing of n u l lis hardcoded. See ECMA-262 standard for the details. Hope youll never get into this pitfall.

Uncomparable
U n d e f i n e dand N a Nvalues cant be compared with a number.
Run!

1 a l e r t ( u n d e f i n e d>0 ) ;/ /f a l s e 2 a l e r t ( u n d e f i n e d = =0 ) ;/ /f a l s e 3 a l e r t ( u n d e f i n e d <0 ) ;/ /f a l s e Use strict comparisons = = =to check against u n d e f i n e d . But even a strict comparison fails with N a N , use i s N a N ( )function to check it.

http://javascript.info/tutorial/comparison-operators-ifelse

3/4

1/21/2014

Comparison operators, if..else | JavaScript Tutorial

Why does it behave like that? The short answer is: because thats written in the standard. A longer one is JavaScript was created in 10 days. What youd await?.

Ternary operator " ? "


A regular use-case is when a variable gets a value depending on a condition: 1 i f( c a s h>1 0 0 ){ 2 m e=" R i c h " 3 }e l s e{ 4 m e=" P o o r " 5 } The ternary operator comes in as a handy shortcut. The syntax is: r e s u l t=c o n d i t i o n?v a l u e _ i f _ t r u e:v a l u e _ i f _ f a l s e . It evaluates the c o n d i t i o nand returns the v a l u e _ i f _ t r u evalue if it is correct or v a l u e _ i f _ f a l s e otherwise. The i fcan be rewritten as: m e=( c a s h>1 0 0 )?' R i c h ':' P o o r ' Brackets around c a s h>1 0 0can be safely removed, because operator ? has lower priority. But they are usually kept for readability. The following statements are equal:
Run!

1 r i c h=( m o n e y>1 0 )?t r u e:f a l s e 2 / /s a m ea s 3 r i c h=m o n e y>1 0 Another example, getting the absolute value of x : a b s=( x>0 )?x:x Operators Loops and switch

The content of this site is available under the terms of CC BY-NC-SA. Ilya Kantor, 2011.

"JavaScript is a registered trademark of Oracle corp. This site is not affiliated with Oracle corp.

http://javascript.info/tutorial/comparison-operators-ifelse

4/4

Vous aimerez peut-être aussi