• Skip to main content
  • Select language
  • Skip to search

Making decisions in your code — conditionals

Logical operators: and, or and not, a switch example, ternary operator example.

In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article we'll explore how so-called conditional statements work in JavaScript.

You can have it on one condition..!

Human beings (and other animals) make decisions all the time that affect their lives, from small ("should I eat one cookie or two?") to large ("should I stay in my home country and work on my father's farm, or should I move to America and study astrophysics?")

Conditional statements allow us to represent such decision making in JavaScript, from the choice that must be made (e.g. "one cookie or two"), to the resulting outcome or those choices (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full up, but mom scolded me for eating all the cookies".)

conditional assignment in js

if ... else statements

Let's look at by far the most common type of conditional statement you'll use in JavaScript — the humble if ... else statement .

Basic if ... else syntax

Basic if...else syntax looks like so in pseudocode :

Here we've got:

  • The keyword if followed by some parentheses.
  • A condition to test, placed inside the parentheses (typically "is this value bigger than this other value", or "does this value exist"). This condition will make use of the comparison operators we discussed in the last module, and will return true or false .
  • A set of curly braces, inside which we have some code — this can be any code we like, and will only be run if the condition returns true .
  • The keyword else .
  • Another set of curly braces, inside which we have some more code — this can be any code we like, and will only be run if the condition is not true .

This code is pretty human-readable — it is saying " if the condition returns true , run code A, else run code B"

You should note that you don't have to include the else and the second curly brace block — the following is also perfectly legal code:

However, you need to be careful here — in this case, the second block of code is not controlled by the conditional statement, so it will always run, regardless of whether the condition returns true or false . This is not necessarily a bad thing, but it might not be what you want — often you will want to run one block of code or the other, not both.

As a final point, you may sometimes see if...else statements written without the curly braces, in the following shorthand style:

This is perfectly valid code, but using it is not recommended — it is much easier to read the code and work out what is going on if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation.

A real example

To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. The parent might say "Hey sweetheart, if you help me by going and doing the shopping, I'll give you some extra allowance so you can afford that toy you wanted." In JavaScript, we could represent this like so:

This code as shown will always result in the shoppingDone variable returning false , meaning disappointment for our poor child. It'd be up to us to provide a mechanism for the parent to set the shoppingDone variable to true if the child did the shopping.

Note : You can see a more complete version of this example on GitHub (also see it running live .)

The last example provided us with two choices, or outcomes — but what if we want more than two?

There is a way to chain on extra choices/outcomes to your if...else — using else if . Each extra choice requires an additional block to put in between if() { ... } and else { ... } — check out the following more involved example, which could be part of a simple weather forecast application:

  • Here we've got an HTML element represents a control that provides a menu of options:"> <select> element allowing us to make different weather choices, and a simple paragraph.
  • In the JavaScript, we are storing a reference to both the element represents a control that provides a menu of options:"> <select> and element represents a paragraph of text."> <p> elements, and adding an event listener to the <select> element so that when its value is changed, the setWeather() function is run.
  • When this function is run, we first set a variable called choice to the current value selected in the <select> element. We then use a conditional statement to show different text inside the paragraph depending on what the value of choice is. Notice how all the conditions are tested in else if() {...} blocks, except for the first one, which is tested in an if() {...} block .
  • The very last choice, inside the else {...} block, is basically a "last resort" option — the code inside it will be run if none of the conditions are true . In this case, it serves to empty the text out of the paragraph if nothing is selected, for example if a user decides to re-select the "--Make a choice--" placeholder option shown at the beginning.

Note : You can also find this example on GitHub ( see it running live on there also.)

A note on comparison operators

Comparison operators are used to test the conditions inside our conditional statements. We first looked at comparison operators back in our Basic math in JavaScript — numbers and operators article. Our choices are:

  • === and !==  — test if one value is identical to, or not identical to, another.
  • < and > — test if one value is less than or greater than another.
  • <= and >= — test if one value is less than or equal to, or greater than or equal to, another.

Note : Review the material at the previous link if you want to refresh your memories on these.

We wanted to make a special mention of testing boolean ( true / false ) values, and a common pattern you'll come across again and again. Any value that is not false , undefined , null , 0 , NaN , or an empty string ( '' ) actually returns true when tested as a conditional statement, therefore you can simply use a variable name on its own to test whether it is true , or even that it exists (i.e. it is not undefined.) So for example:

And, returning to our previous example about the child doing a chore for their parent, you could write it like this:

Nesting if ... else

It is perfectly OK to put one if...else statement inside another one — to nest them. For example, we could update our weather forecast application to show a further set of choices depending on what the temperature is:

Even though the code all works together, each if...else statement works completely independently of the other one.

If you want to test multiple conditions without writing nested if...else statements, logical operators can help you. When used in conditions, the first two do the following:

  • && — AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to true for the whole expression to return true .
  • || — OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to true for the whole expression to return true .

To give you an AND example, the previous example snippet can be rewritten to this:

So for example, the first code block will only be run if choice === 'sunny' and temperature < 86 return true .

Let's look at a quick OR example:

The last type of logical operator, NOT, expressed by the ! operator, can be used to negate an expression. Let's combine it with OR in the above example:

In this snippet, if the OR statement returns true , the NOT operator will negate it so that the overall expression returns false .

You can combine as many logical statements together as you want, in whatever structure. The following example executes the code inside only if both OR statements return true, meaning that the overall AND statement will return true:

A common mistake when using the logical OR operator in conditional statements is to try to state the variable whose value you are checking once, and then give a list of values it could be to return true, separated by || (OR) operators. For example:

In this case the condition inside if(...)  will always evaluate to true since 7 (or any other non-zero value) always evaluates to true. This condition is actually saying "if x equals 5, or 7 is true — which it always is". This is logically not what we want! To make this work you've got to specify a complete test either side of each OR operator:

switch statements

if...else statements do the job of enabling conditional code well, but they are not without their downsides. They are mainly good for cases where you've got a couple of choices, and each one requires a reasonable amount of code to be run, and/or the conditions are complex (e.g. multiple logical operators). For cases where you just want to set a variable to a certain choice of value or print out a particular statement depending on a condition, the syntax can be a bit cumbersome, especially if you've got a large number of choices.

switch statements are your friend here — they take a single expression/value as an input, and then look through a number of choices until they find one that matches that value, executing the corresponding code that goes along with it. Here's some more pseudocode, to give you an idea:

  • The keyword switch , followed by a set of parentheses.
  • An expression or value inside the parentheses.
  • The keyword case , followed by a choice that the expression/value could be, followed by a colon.
  • Some code to run if the choice matches the expression.
  • A break statement, followed by a semi-colon. If the previous choice matches the expression/value, the browser stops executing the code block here, and moves on to any code that appears below the switch statement.
  • As many other cases (bullets 3–5) as you like.
  • The keyword default , followed by exactly the same code pattern as one of the cases (bullets 3–5), except that default does not have a choice after it, and you don't need to break statement as there is nothing to run after this in the block anyway. This is the default option that runs if none of the choices match.

Note : You don't have to include the default section — you can safely omit it if there is no chance that the expression could end up equaling an unknown value. If there is a chance of this however, you need to include it to handle unknown cases.

Let's have a look at a real example — we'll rewrite our weather forecast application to use a switch statement instead:

Note : You can also find this example on GitHub (see it running live on there also.)

Ternary operator

There is one final bit of syntax we want to introduce you to, before we get you to play with some examples. The ternary or conditional operator is a small bit of syntax that tests a condition and returns one value/expression if it is true , and another if it is false — this can be useful in some situations, and can take up a lot less code than an if...else block if you simply have two choices that are chosen between via a true / false condition. The pseudocode looks like this:

So let's look at a simple example:

Here we have a variable called isBirthday — if this is true , we give our guest a happy birthday message; if not, we give her the standard daily greeting.

You don't just have to set variable values with the ternary operator; you can also run functions, or lines of code — anything you like. The following live example shows a simple theme chooser where the styling for the site is applied using a ternary operator.

Here we've got a element represents a control that provides a menu of options:"> <select> element to choose a theme (black or white), plus a simple is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h1> to display a website title. We also have a function called update() , which takes two colors as parameters (inputs). The website's background color is set to the first provided color, and its text color is set to the second provided color.

Finally, we've also got an onchange event listener that serves to run a function containing a ternary operator. It starts with a test condition — select.value === 'black' . If this returns true , we run the update() function with parameters of black and white, meaning that we end up with background color of black and text color of white. If it returns false , we run the update() function with parameters of white and black, meaning that the site color are inverted.

Active learning: A simple calendar

In this example you are going to help us finish a simple calendar application. In the code you've got:

  • A element represents a control that provides a menu of options:"> <select> element to allow the user to choose between different months.
  • An onchange event handler to detect when the value selected in the <select> menu is changed.
  • A function called createCalendar() that draws the calendar and displays the correct month in the is the most important and <h6> is the least. A heading element briefly describes the topic of the section it introduces. Heading information may be used by user agents, for example, to construct a table of contents for a document automatically."> <h1> element.

We need you to write a conditional statement inside the onchange handler function, just below the  // ADD CONDITIONAL HERE comment. It should:

  • Look at the selected month (stored in the choice variable. This will be the <select> element value after the value changes, so "January" for example.)
  • Set a variable called days to be equal to the number of days in the selected month. To do this you'll have to look up the number of days in each month of the year. You can ignore leap years for the purposes of this example.
  • You are advised to use logical OR to group multiple months together into a single condition; many of them share the same number of days.
  • Think about which number of days is the most common, and use that as a default value.

If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution.

Playable code

Active learning: more color choices.

In this example you are going to take the ternary operator example we saw earlier and convert the ternary operator into a switch statement that will allow us to apply more choices to the simple website. Look at the element represents a control that provides a menu of options:"> <select> — this time you'll see that it has not two theme options, but five. You need to add a switch statement just underneath the // ADD SWITCH STATEMENT comment:

  • It should accept the choice variable as its input expression.
  • For each case, the choice should equal one of the possible values that can be selected, i.e. white, black, purple, yellow, or psychedelic.
  • For each case, the update() function should be run, and be passed two color values, the first one for the background color, and the second one for the text color. Remember that color values are strings, so need to be wrapped in quotes.

Playable code 2

And that's all you really need to know about conditional structures in JavaScript right now! I'm sure you'll have understood these concepts and worked through the examples with ease; if there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

  • Comparison operators
  • Conditional statements in detail
  • if...else reference
  • Conditional (ternary) operator reference

Document Tags and Contributors

  • CodingScripting
  • Conditionals
  • l10n:priority
  • Complete beginners start here!
  • Getting started with the Web overview
  • Installing basic software
  • What will your website look like?
  • Dealing with files
  • HTML basics
  • JavaScript basics
  • Publishing your website
  • How the Web works
  • HTML — Structuring the Web
  • Introduction to HTML overview
  • Getting started with HTML
  • What's in the head? Metadata in HTML
  • HTML text fundamentals
  • Creating hyperlinks
  • Advanced text formatting
  • Document and website structure
  • Debugging HTML
  • Assessment: Marking up a letter
  • Assessment: Structuring a page of content
  • Multimedia and embedding overview
  • Images in HTML
  • Video and audio content
  • From object to iframe — other embedding technologies
  • Adding vector graphics to the Web
  • Responsive images
  • Assessment: Mozilla splash page
  • HTML tables overview
  • HTML table basics
  • HTML Table advanced features and accessibility
  • Assessment: Structuring planet data
  • CSS — Styling the Web
  • Introduction to CSS overview
  • How CSS works
  • Selectors introduction
  • Simple selectors
  • Attribute selectors
  • Pseudo-classes and pseudo-elements
  • Combinators and multiple selectors
  • CSS values and units
  • Cascade and inheritance
  • The box model
  • Debugging CSS
  • Assessment: Fundamental CSS comprehension
  • Styling text overview
  • Fundamental text and font styling
  • Styling lists
  • Styling links
  • Assessment: Typesetting a community school homepage
  • Styling boxes overview
  • Box model recap
  • Backgrounds
  • Styling tables
  • Advanced box effects
  • Assessment: Creating fancy letterheaded paper
  • Assessment: A cool-looking box
  • CSS layout overview
  • Introduction
  • Positioning
  • Practical positioning examples
  • JavaScript — Dynamic client-side scripting
  • JavaScript first steps overview
  • What is JavaScript?
  • A first splash into JavaScript
  • What went wrong? Troubleshooting JavaScript
  • Storing the information you need — Variables
  • Basic in JavaScript — Numbers and operators
  • Handling text — Strings in JavaScript
  • Useful string methods
  • Assessment: Silly story generator
  • JavaScript building blocks overview
  • Making decisions in your code — Conditionals
  • Looping code
  • Functions — Reusable blocks of code
  • Build your own function
  • Function return values
  • Introduction to events
  • Assessment: Image gallery
  • Introducing JavaScript objects overview
  • Object basics
  • Object-oriented JavaScript for beginners
  • Object prototypes
  • Inheritance in JavaScript
  • Working with JSON data
  • Object building practise
  • Assessment: Adding features to our bouncing balls demo
  • Accessibility — Make the web usable by everyone
  • Accessibility overview
  • What is accessibility?
  • HTML: A good basis for accessibility
  • CSS and JavaScript accessibility best practices
  • WAI-ARIA basics
  • Accessible multimedia
  • Mobile accessibility
  • Assessment: Accessibility troubleshooting
  • Tools and testing
  • Cross browser testing overview
  • Introduction to cross browser testing
  • Strategies for carrying out testing
  • Handling common HTML and CSS problems
  • Handling common JavaScript problems
  • Handling common accessibility problems
  • Implementing feature detection
  • Introduction to automated testing
  • Setting up your own test automation environment
  • Server-side website programming
  • First steps overview
  • Introduction to the server-side
  • Client-Server overview
  • Server-side web frameworks
  • Website security
  • Django web framework (Python) overview
  • Setting up a development environment
  • Tutorial: The Local Library website
  • Tutorial Part 2: Creating a skeleton website
  • Tutorial Part 3: Using models
  • Tutorial Part 4: Django admin site
  • Tutorial Part 5: Creating our home page
  • Tutorial Part 6: Generic list and detail views
  • Tutorial Part 7: Sessions framework
  • Tutorial Part 8: User authentication and permissions
  • Tutorial Part 9: Working with forms
  • Tutorial Part 10: Testing a Django web application
  • Tutorial Part 11: Deploying Django to production
  • Web application security
  • Assessment: DIY mini blog
  • Express Web Framework (Node.js/JavaScript) overview
  • Express/Node introduction
  • Setting up a Node (Express) development environment
  • Express tutorial: The Local Library website
  • Express Tutorial Part 2: Creating a skeleton website
  • Express Tutorial Part 3: Using a database (with Mongoose)
  • Express Tutorial Part 4: Routes and controllers
  • Express Tutorial Part 5: Displaying library data
  • Express Tutorial Part 6: Working with forms
  • Express Tutorial Part 7: Deploying to production
  • Further resources
  • WebGL: Graphics processing
  • HTML questions
  • CSS questions
  • JavaScript questions
  • Tools and setup
  • Design and accessibility
  • How to contribute

Tania Rascia

JavaScript Operators, Conditionals & Functions

Share this article

JavaScript Operators, Conditionals & Functions

JavaScript Operators

Conditional statements, frequently asked questions (faqs) about javascript operators, conditionals, and functions.

  • Arithmetic Operators: Perform operations and manipulate data. For example, the addition operator (+) can be used to add two numbers together.
  • Comparison Operators: Compare two or more values and return a boolean value (true or false) For example, using the greater than (>) operator to check if an integer variable is larger than another.
  • Logical Operators: Used to connect two or more comparison operators and return a boolean value. For example, using the AND operator (&&) to see if a variable is between two values, i.e. that it is larger than one number and smaller the other.
  • Conditional statements: Control the flow of a program based on certain conditions. For example, an if statement can be used to execute a block of code only if a certain condition is met.
  • Functions: Encapsulate a set of statements to be used multiple times, making code more organized and reusable. Functions can also accept inputs and return outputs, allowing for more dynamic and flexible code.

Table of Contents

Assignment operators, subtraction, multiplication, strict equal, strict not equal, less than or equal to, greater than, greater than or equal to, operator precedence, declaration, parameters and arguments.

Disclaimer: This guide is intended for complete beginners to JavaScript and programming. As such, many concepts will be presented in a simplified manner.

Arithmetic Operators

Comparison operators, logical operators.

  • Grouping ( () )
  • Multiplication ( * )
  • Division ( / )
  • Modulus ( % )
  • Addition ( + )
  • Subtraction ( - )
  • Less than ( < )
  • Less than or equal ( <= )
  • Greater than ( > )
  • Greater than or equal ( >= )
  • Equal ( = )
  • Not equal ( != )
  • Strict equal ( === )
  • Strict not equal ( !== )
  • And ( && )
  • Assignment ( = )
A local variable is a variable that will only work inside a specific code block.

What is the significance of operator precedence in JavaScript?

Operator precedence in JavaScript determines the way operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence. Understanding operator precedence is crucial as it helps to predict the outcome of an operation. For instance, multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-). Therefore, in an expression like 2 + 3 * 4, the multiplication happens first, resulting in 2 + 12 = 14, not 20.

How can I change the order of operations in JavaScript?

You can change the order of operations in JavaScript by using parentheses. The expressions inside parentheses are evaluated first. For example, in the expression (2 + 3) * 4, the addition operation is performed first because it’s inside the parentheses, resulting in 5 * 4 = 20.

What are conditional statements in JavaScript?

Conditional statements in JavaScript are used to perform different actions based on different conditions. The most common conditional statements are if, else if, and else. These statements allow the program to make decisions and execute the appropriate code block based on the condition’s truthiness.

How do JavaScript functions work?

Functions in JavaScript are blocks of code designed to perform a particular task. A JavaScript function is executed when something invokes it (calls it). Functions can be defined using the function keyword, followed by a name, and parentheses (). The code to be executed by the function is placed inside curly brackets {}.

What are the different types of operators in JavaScript?

JavaScript includes various types of operators such as arithmetic operators (+, -, *, /, %, ++, –), assignment operators (=, +=, -=, *=, /=, %=), comparison operators (==, ===, !=, !==, >, <, >=, <=), logical operators (&&, ||, !), and bitwise operators (&, |, ^, ~, <<, >>, >>>).

How does the ternary operator work in JavaScript?

The ternary operator is a shorthand way of writing an if-else statement. It’s called the ternary operator because it takes three operands – a condition, a result for true, and a result for false. For example, the code let result = (a > b) ? ‘a is greater’ : ‘b is greater’; will assign the string ‘a is greater’ to the result if a is greater than b, and ‘b is greater’ if a is not greater than b.

What is the difference between == and === operators in JavaScript?

The == operator checks for equality in value but not type. It performs type coercion if the variables being compared are not of the same type. On the other hand, the === operator, also known as the strict equality operator, checks for both value and type. It does not perform type coercion, so if the variables being compared are not of the same type, it will return false.

How can I define a function in JavaScript?

A function in JavaScript can be defined using the function keyword, followed by a unique function name, a list of parameters (that might be empty), and a statement block surrounded by curly braces. For example, function myFunction(parameter1, parameter2) { // code to be executed }.

What are JavaScript logical operators?

JavaScript logical operators are used to determine the logic between variables or values. The three logical operators are AND (&&), OR (||), and NOT (!). The AND operator returns true if both operands are true, the OR operator returns true if at least one operand is true, and the NOT operator returns the inverse of the given boolean value.

How does the switch statement work in JavaScript?

The switch statement in JavaScript is used to perform different actions based on different conditions. It’s a more efficient way to code when dealing with many conditions. The switch expression is evaluated once, and its value is compared with the values of each case. If there’s a match, the associated block of code is executed.

A web developer from Chicago who blogs about code and design, and enjoys losing at Age of Empires 2 in her spare time.

SitePoint Premium

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

Summary : in this tutorial, you will learn how to use JavaScript assignment operators to assign a value to a variable.

Introduction to JavaScript assignment operators

An assignment operator ( = ) assigns a value to a variable. The syntax of the assignment operator is as follows:

In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a .

The following example declares the counter variable and initializes its value to zero:

The following example increases the counter variable by one and assigns the result to the counter variable:

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the second assignment, the counter variable is 1 .

To make the code more concise, you can use the += operator like this:

In this syntax, you don’t have to repeat the counter variable twice in the assignment.

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

Chaining JavaScript assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.

JavaScript If-Else and If-Then – JS Conditional Statements

Jessica Wilkins

There will be times where you will want to write commands that handle different decisions in your code.

For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives.

In this article, I will explain what an if...else statement is and provide code examples. We will also look at the conditional (ternary) operator which you can use as a shorthand for the if...else statement.

What is an if...else statement in JavaScript?

The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

Truthy and falsy values are converted to true or false in   if statements.

Any value that is not defined as falsy would be considered truthy in JavaScript.

Here is a list of   falsy values:

  • -0 (negative zero)
  • 0n (BigInt zero)
  • "" , '' , `` (empty string)
  • NaN (not a number)

Examples of if...else statements in JavaScript

In this example, the condition for the if statement is true so the message printed to the console would be "Nick is an adult."

Screen-Shot-2021-08-09-at-3.18.12-AM

But if I change the age variable to be less than 18, then the condition would be false and the code would execute the else block instead.

Screen-Shot-2021-08-09-at-3.17.07-AM

Examples of multiple conditions (if...else if...else statements) in JavaScript

There will be times where you want to test multiple conditions. That is where the else if block comes in.

When the if statement is false , the computer will move onto the else if statement. If that is also false , then it will move onto the else block.

In this example, the else if block would be executed because Alice is between the ages of 18 and 21.

Screen-Shot-2021-08-09-at-3.33.33-AM

When to use switch statements over if...else statements?

There are times in JavaScript where you might consider using a switch statement instead of an if else statement.

switch statements can have a cleaner syntax over complicated if else statements.

Take a look at the example below – instead of using this long if else statement, you might choose to go with an easier to read switch statement.

switch statements will not be appropriate to use in all situations. But if you feel like the if else statements are long and complicated, then a switch statement could be an alternative option.

The logical AND (&&) operator and if...else statements in JavaScript

In the logical AND ( && ) operator, if both conditions are true , then the if block will be executed. If one or both of the conditions are false , then the else block will be executed.

In this example, since age is greater than 16 and the ownsCar variable is true , the if block will run. The message printed to the console will be "Jerry is old enough to drive and has his own car."

Screen-Shot-2021-08-09-at-4.22.49-AM

If I change the age variable to be less than 16, then both conditions are no longer true and the else block would be executed instead.

Screen-Shot-2021-08-09-at-4.20.19-AM

The logical OR (||) operator and if...else statements in JavaScript

In the logical OR ( || ) operator, if one or both of the conditions are true , then the code inside the if statement will execute.

In this example, even though the isSale variable is set to false , the code inside the if block will still execute because the boyfriendIsPaying variable is set to true .

Screen-Shot-2021-08-09-at-4.40.36-AM

If I were to change the value of the boyfriendIsPaying variable to false , then the else block would execute because both conditions are false .

Screen-Shot-2021-08-09-at-4.42.12-AM

The logical NOT (!) operator and if...else statements in JavaScript

The logical NOT ( ! ) operator will take something that is true and make it false . It will also take something that is false and make it true .

We can modify the example from earlier to use the ! operator to make the boyfriendIsPaying variable   false . Since both conditions are false , the else block would be executed.

Screen-Shot-2021-08-09-at-5.02.04-AM

Conditional (ternary) operator in JavaScript

If you have a short if else statement, then you might choose to go with the ternary operator.  The word ternary means something composed of three parts.

This is the basic syntax for a ternary operator:

The condition goes before the ? mark and if it is true , then the code between the ? mark and : would execute. If the condition is false , then the code after the   : would execute.

In this example, since age is greater than 18, then the message to the console would be "Can vote".

Screen-Shot-2021-08-09-at-5.25.14-AM

This is what the code would look like using an if else statement:

if else statements will execute a block of code when the condition in the if statement is truthy . If the condition is falsy , then the else block will be executed.

There will be times where you want to test multiple conditions and you can use an if...else if...else statement.

If you feel like the if else statement is long and complicated, then a switch statement could be an alternative option.

Using logical operators to test multiple conditions can replace nested if else statements.

The ternary operator can be used to write shorter code for a simple if else statement.

I am a musician and a programmer.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

IMAGES

  1. Conditional Statements in JavaScript : if, else if, else.

    conditional assignment in js

  2. 24: Conditional statements in JavaScript

    conditional assignment in js

  3. JavaScript Conditional Statements

    conditional assignment in js

  4. #24 The Ternary (Conditional) Operator

    conditional assignment in js

  5. JavaScript Conditional Statements Tutorial with Example

    conditional assignment in js

  6. Types of Conditional Statements in JavaScript with Example

    conditional assignment in js

VIDEO

  1. Types of Pointers in C in hindi

  2. Animschool 180 Turn Assignment

  3. If

  4. Essa feature do #TypeScript não é muito comum!

  5. Você conhecia essa feature do #JavaScript?

  6. O que são tipos recursivos no #TypeScript?

COMMENTS

  1. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...

  2. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if ...

  3. How do you use the ? : (conditional) operator in JavaScript?

    It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator". ... the whole point of the conditional ternary is to shorten conditional assignment values otherwise you should just use an if statement - TheRealMrCrowley. May 5, 2017 at 18:05.

  4. Making decisions in your code

    In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article, we'll explore how so-called conditional ...

  5. Quick Tip: How to Use the Ternary Operator in JavaScript

    The ternary operator accepts three operands; it's the only operator in JavaScript to do that. You supply a condition to test, followed by a questions mark, followed by two expressions separated ...

  6. How to Use the Ternary Operator in JavaScript

    Inside the function, we use the ternary operator to check if the number is even or odd. If the number modulo 2 equals 0 (meaning it's divisible by 2 with no remainder), then the condition evaluates to true, and the string "even" is assigned to the result variable. If the condition evaluates to false (meaning the number is odd), the string "odd ...

  7. Making decisions in your code

    Conditional statements allow us to represent such decision making in JavaScript, from the choice that must be made (e.g. "one cookie or two"), to the resulting outcome or those choices (perhaps the outcome of "ate one cookie" might be "still felt hungry", and the outcome of "ate two cookies" might be "felt full up, but mom scolded me for eating ...

  8. How to Use the Ternary Operator in JavaScript

    In this example, I used the ternary operator to determine whether a user's age is greater than or equal to 18. Firstly, I used the prompt() built-in JavaScript function. This function opens a dialog box with the message What is your age? and the user can enter a value. I store the user's input in the age variable.

  9. A definitive guide to conditional logic in JavaScript

    Using isEven and JavaScript's built-in universal function, we can run [2, 4, 6, 8].every(isEven) and find that this is true. Array.prototype.every is JavaScript's Universal Statement Existential Statements. An existential statement makes a specific claim about a set: at least one element in the set returns true for the predicate function ...

  10. Make Your Code Cleaner with JavaScript Ternary Operator

    console .log(message); Code language: JavaScript (javascript) Here's the syntax of the ternary operator: In this syntax, the condition is an expression that evaluates to a Boolean value, either true or false. If the condition is true, the first expression ( expresionIfTrue) executes. If it is false, the second expression ( expressionIfFalse ...

  11. JavaScript Conditionals: The Basics with Examples

    Conditional statements control behavior in JavaScript and determine whether or not pieces of code can run. There are multiple different types of conditionals in JavaScript including: "If" statements: where if a condition is true it is used to specify execution for a block of code.

  12. if...else

    statement1. else. statement2. An expression that is considered to be either truthy or falsy. Statement that is executed if condition is truthy. Can be any statement, including further nested if statements. To execute multiple statements, use a block statement ( { /* ... */ }) to group those statements.

  13. JavaScript Operators, Conditionals & Functions

    Assignment operators, in their most basic form, ... In this article, we learned three very important fundamental concepts of JavaScript: operators, conditional statements, and functions. ...

  14. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  15. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  16. JavaScript Assignment Operators

    An assignment operator ( =) assigns a value to a variable. The syntax of the assignment operator is as follows: let a = b; Code language: JavaScript (javascript) In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a. The following example declares the counter variable and initializes its value to zero:

  17. JavaScript If-Else and If-Then

    What is an if...else statement in JavaScript? The if...else is a type of conditional statement that will execute a block of code when the condition in the if statement is truthy. If the condition is falsy, then the else block will be executed. Truthy and falsy values are converted to true or false in if statements.

  18. Variable assignment inside an 'if' condition in JavaScript

    To understand what is going on, refer to the operator precedence and associativity chart.The expression a = 2 && (b = 8) is evaluated as follows: && operator is evaluated before = since it has higher priority the left hand expression 2 is evaluated which is truthy; the right hand expression b = 8 is evaluated (b becomes 8 and 8 is returned); 8 is returned; a = 8 is evaluated (a becomes 8 and 8 ...

  19. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  20. Oops

    United Airlines - Airline Tickets, Travel Deals and Flights If you're seeing this message, that means JavaScript has been disabled on your browser, please enable JS ...

  21. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  22. javascript

    3. The spread operator now fixes this. Here is an example with two comparisons. Note: I changed date: to const date = so that it is valid runnable javascript. This can also be used with data: if it is supposed to be inside of a deep object structure. const compareValue = 13; const data = {.