JavaScript if Statements, Equality and Truthy/Falsy – Explained with Examples

JavaScript if Statements, Equality and Truthy/Falsy – Explained with Examples

By Deborah Kurata

Decisions, decisions, decisions. Go left? Or go right? In programming, we use an if statement when we want our code to make a decision.

In this tutorial, we'll deep dive into the JavaScript if statement. Along the way, we'll examine the difference between single equals, double equals, and triple equals. We'll also clarify the meaning of truthy and falsy in JavaScript.

You can watch the associated video here which walks through a demo.

Let's say we are building a number guessing game as shown in Figure 1 below. The game generates a random number. The user tries to guess that number by entering their guess and clicking the Guess button.

The game then checks the entered number. If the guess is too low, the game displays "too low". If the guess is too high, the game displays "too high". And if the guess is just right, the game displays "is correct ... You win!".

User interface for a number guessing game.

There are numerous "ifs" in that paragraph! To write the code for this game, we'll need some if statements.

Anatomy of an if Statement in JavaScript

In JavaScript, if is a block statement. A block statement groups a set of instructions. A block is delimited with curly braces.

Let's start with a simplified version of the logic required for our game. Here we determine if the user's guess is right or wrong.

The if statement begins with the if keyword. Note that all of JavaScript is case sensitive, including the key words. So if a keyword such as if is lowercase, it must be typed as lower case.

The if keyword is followed by parentheses. Inside the parentheses, we define the conditions for the if statement to make its decision, called the decision criteria .

In the above example, the decision criteria determine if the value in the variable guess equals the value in the variable randomNumber . Notice the triple equal === . We'll talk about that in a moment.

The if block body is enclosed in curly braces. The block can contain any number of statements, including additional if statements. If the decision criteria within the parentheses evaluate to true, the code within the block is executed. Otherwise, the code execution continues after the if block.

Single Equal vs Double Equal vs Triple Equal in JavaScript

In JavaScript, we use one, two, or three equal signs, depending on what we need.

The single equal sign = is an assignment. We use it to assign a value or expression to a variable.

In this code, we assign a string to the feedbackText variable. And assign a generated random number to the randomNumber variable.

The double equal == and triple equal === are comparison operators. They evaluate the equality of the two values. But how they perform that equality is slightly, yet significantly, different.

The double equal == compares the two values. If the values are of different types, it attempts to convert them to the same type before comparing.

Let's look at an example.

In the above code, instead of generating a random number we assign the number 8 to the randomNumber variable. And assign a string value of "8" to the guess variable. Since our if statement uses a double equal in this example, the data types are converted to the same type. The decision criteria then evaluates to true because the values are both 8. And the feedbackText variable is set to "You win!"

For more information on JavaScript variables and data types, check out this video.

The triple equal === is strict equality. It compares the data types and their values. It does not do any type coercion, meaning it won't attempt to convert the types. For strict equality to evaluate to true, the data type and the value must be the same.

Let's look at the same example, but using triple equal instead.

Using the triple equal === , the guess string value of "8" is not converted to a number. Because the values are not of the same data type, guess does not match randomNumber . The decision criteria evaluates to false and the code within the if block is not executed.

Figure 2 provides a summary. Use the triple equal any time you want an exact match, including their values and data types.

Image

if vs else vs else if in JavaScript

The if statement alone works great if you want the code to do something if some condition is true. But sometimes you also want the code to do something else if the condition is not true. That's the purpose of the else block.

In the above code example, if the user's guess is greater than the random number, the feedback variable is assigned 'Too high'. Otherwise (else), it is set to 'Too low'.

In general, if the decision criteria is false, the else block is executed.

We can also use an else if . The else if provides a second set of decision criteria. So the else block is only executed if those decision criteria are true.

Here is an example that uses if , else and else if :

Let's walk through this code.

When this code is run, the first decision criterion get evaluated. Since this criterion uses triple equal === , it's a strict compare, meaning it compares the data type and value. If both the data type and value are the same, the decision criterion evaluates to true and the if block code is executed. In this example, the if block has only one statement, but there could be any number of statements in the if block.

If the first decision criterion is false, either because the variables have a different data type or a different value, the else if decision criterion is evaluated. If the guess is greater than the random number, the else if block is executed. In this case, the block only has one statement, but there could be any number of statements in this block.

If the else if decision criterion is false, the else block code is run. Again, there could be any number of statements within this else block.

To see this concept visually, Figure 3 shows this logic as a flow chart.

Flow chart of the `if` logic

On the flow chart, the decision criteria are shown as diamonds with paths for true and false.

If the user's guess exactly matches the randomNumber (data type and value), the decision criteria are true and we set the feedback to 'Correct ... You win!'.

If the if statement decision criteria are false, the else if decision criteria are evaluated. If the user's guess is larger than the random number, the else if decision criteria are true and we set the feedback to 'Too high'.

If the else if decision criteria are false, we set the feedback to 'Too low'.

In these if statements, it's generally clear when the decision criteria are true or false. The guess is exactly the same as the random number or it isn't. The guess is greater than the random number or it isn't.

But what about this if statement?

With no comparison operator, this is shorthand syntax for "if this variable is truthy". How do we know if guessInput is true or false?

Truthy vs Falsy Values in JavaScript

JavaScript has a unique sense of true and false, called truthy and falsy . Truthy and falsy are used when evaluating decision-criteria that aren't clearly true or false. Let's look at some examples.

As you would expect, a variable set to false is falsy. The code within the if block is not executed.

A value of 0 (zero) is also falsy.

And "" , which is an empty string, is falsy.

If a variable has not been assigned a value, it is undefined . An undefined variable is falsy. A common coding pattern is to ensure a variable has a value before doing something with that variable using an if statement as shown above.

A null variable is also falsy.

And if the code attempts to convert a value that is not a number to a number, the result is NaN , which stands for "not a number". Variables that are NaN evaluate to falsy.

Any other values are truthy.

In the first example, the variable is set to a non-zero number, so it is truthy. In the second example, the variable is set to a non-empty string, so it is truthy.

Basically, if the variable value is false, zero, empty, null, undefined, or Nan , it's falsy and the code within the if block is not run.

If the variable value is anything else, such as a number that is not zero, a non-empty string, an array, or an object, it's truthy and the code in the if block is run.

How about a more full-featured example?

Guessing Game Example

Our guessing game includes the following code:

We first find the HTML elements we want to work with. We find the guess button, and use addEventListener to listen for the button click event. When the user clicks the button, the code calls the function we passed to addEventListener , which is processGuess .

For more information on finding HTML elements and reacting to their events, check out this article .

We then find the guess input element so we can read the user's guess. And we find a feedback element we'll use to write the feedback text to the page.

The processGuess() function reads the user's guess from the input element and displays the appropriate feedback. Let's break it down.

The first if statement ensures we found the input element. If the element was found, we have a reference to that element in the guessInput variable. The guessInput variable evaluates to truthy, and the if block code is executed.

The code within the if block reads the value of the input element. It uses valueAsNumber , which reads a numeric input as a number instead of a string. That way we can more easily compare the guess value to the randomly generated number.

The code then strictly compares the guess to the generated random number. If the values have the same type and value, the decision criteria are true and this if block code is run.

If the guess is not correct, an else if block determines if the value is too high or too low. Based on that comparison, the feedback text is set.

Lastly, we check whether we have a reference to the feedback container. If so, the feedbackContainer variable is set, the if statement evaluates to truthy, and we write the appropriate feedback text to that container.

Wrapping Up

We use if statements to make decisions in our code. The statements inside an if block are run if the decision criteria defined within the parentheses evaluate to true or truthy. The statements inside an else block are run if the decision criteria evaluate to false or falsy.

When defining decision criteria, it's important to set the appropriate comparison:

  • A single equal = in JavaScript assigns a value to a variable. It should not be used in decision criteria.
  • The double equals == compares the values to see if they are equal. If the values are not the same data type, it tries to convert them to the same type before checking for equality.
  • The triple equals === strictly compares the values to see if they are equal. If they are not the same type, they are not equal.

And be mindful of JavaScript's rules for truthy and falsy, especially when defining decision criteria.

You can find the code for the guess a number game here: https://github.com/DeborahK/Gentle-Introduction-to-JavaScript

For more information on programming with JavaScript and to build this guess a number game step by step, check out this course:

Now don't be iffy, use those if statements wisely!

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

  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript – Conditional Statements

JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

1. Using if Statement

The if statement is used to evaluate a particular condition. If the condition holds true, the associated code block is executed.

2. Using if-else Statement

The if-else statement will perform some action for a specific condition. Here we are using the else statement in which the else statement is written after the if statement and it has no condition in their code block.

3. else if Statement

The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating more than two options based on whether the conditions are true or false.

Please refer JavaScript If-Else for more detailed explanation.

4. Using Switch Statement (JavaScript Switch Case)

As the number of conditions increases, you can use multiple else-if statements in JavaScript. but when we dealing with many conditions, the switch statement may be a more preferred option.

Please refer JavaScript Switch Statement for details

5. Using Ternary Operator ( ?: )

The conditional operator, also referred to as the ternary operator (?:), is a shortcut for expressing conditional statements in JavaScript.

Please refer JavaScript Ternary Operator for more details

6. Nested if…else

Nested if…else statements in JavaScript allow us to create complex conditional logic by checking multiple conditions in a hierarchical manner. Each if statement can have an associated else block, and within each if or else block, you can nest another if…else statement. This nesting can continue to multiple levels, but it’s important to maintain readability and avoid excessive complexity.

This table outlines the key characteristics and use cases of each type of conditional statement. Now let’s understand each conditional statement in detail along with the examples.

Similar Reads

  • Web Technologies
  • javascript-basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Remember language

Assignment (=)

Baseline widely available.

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015 .

  • See full compatibility
  • Report feedback

The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .

An expression specifying the value to be assigned to x .

Return value

The value of y .

Thrown in strict mode if assigning to an identifier that is not declared in the scope.

Thrown in strict mode if assigning to a property that is not modifiable .

Description

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 together:

This is equivalent to:

Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:

Basic assignment and chaining

Value of assignment expressions.

The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.

Unqualified identifier assignment

The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .

Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:

So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.

In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.

Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

Assignment with destructuring

The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.

For more information, see Destructuring assignment .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Assignment operators in the JS guide
  • Destructuring assignment

JS Reference

Html events, html objects, other references, javascript if...else.

If the hour is less than 20, output "Good day":

Output "Good day" or "Good evening":

More examples below.

Description

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to select one of many blocks of code to be executed

The if statement specifies a block of code to be executed if a condition is true:

The else statement specifies a block of code to be executed if the condition is false:

The else if statement specifies a new condition if the first condition is false:

Parameter Values

Advertisement

More Examples

If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening":

If the first <div> element in the document has an id of "myDIV", change its font-size:

Change the value of the source attribute (src) of an <img> element, if the user clicks on the image:

Display a message based on user input:

Validate input data:

Related Pages

JavaScript Tutorial: JavaScript If...Else Statements

JavaScript Tutorial: JavaScript Switch Statement

Browser Support

if...else is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

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.

  • How to start JavaScript
  • Work with me
  • Recommended tools

JavaScript: Define a variable in IF statement

javascript variable assignment in if

Have you ever tried to write an IF statement to check a primitive/constant value against a JavaScript variable, but accidentally re-defined the variable?

Accidents happen, what I really meant to write was:

This statement has 3 equals symbols ( === ) which means something completely different.

When I came across this problem for the first time, I asked myself..

Can you define variables inside an IF statement?

The answer is yes you can. Let’s look at the code example above again:

What I did there, was re-define a JavaScript variable inside the IF statement.

But you can create a new variable right inside the IF statement parenthesis.

So my next question, which I’m sure your’s is too, should anyone be doing this?

Should you define a variable inside IF statement?

Honestly, there’s no right or wrong answer to this question. JavaScript allows it, so you can make your decision from there.

I haven’t come across a use-case where this makes sense for me to do.

And personally, I think this is prone to bugs. It may also make it difficult to be catch when debugging, and your peers may be speed reading your code and not catch that variable definition.

They may mistake it for an equals check.

To avoid this, there’s a writing style I use called Yoda conditions.

A guide to Yoda conditions

Yoda conditions is a programming style when writing expressions. It’s also known as Yoda notation.

Let’s look at the code example above. I’ve also corrected the statement.

In the code example above, I’m checking to see if the variable, state , equals the string "not-woosah" .

If that statement is true, than it will print, “Not relaxed!”. Otherwise it will print, “relaxed :)”.

Like I mentioned above, accidents happen, and you may accidentally forget to type the additional equals symbols ( === ).

To avoid this error, I use the Yoda condition programming style.

All I did above, was switch the constant, "not-woosah" , to the left-hand side.

So just in-case you’re typing really fast, and you write something like this:

Your console should yell at you with this error message:

Oh wow, you’ve made it this far! If you enjoyed this article perhaps like or retweet the thread on Twitter:

Did you know that in JavaScript you can create variables inside an IF statement? Thread 1/5 pic.twitter.com/6FNV15zJdV — ʀᴜʙᴇɴ (@rleija_) July 19, 2020

I like to tweet about JavaScript and post helpful code snippets. Follow me there if you would like some too!

javascript variable assignment in if

Ruben Leija

I launched this blog in 2019 and now I write to 85,000 monthly readers about JavaScript. Say hi to me at Twitter, @rleija_ .

Do you want more JavaScript articles ?

Hey, here at Linguine Code, we want to teach you everything we know about JavaScript . Our only question is, are you in?

IMAGES

  1. Javascript Variable (with Examples)

    javascript variable assignment in if

  2. 住所 戦術 規則性 html variable text

    javascript variable assignment in if

  3. Types of JavaScript Variables

    javascript variable assignment in if

  4. How to Declare Variables in Javascript

    javascript variable assignment in if

  5. How to Declare a Variable in Javascript (with Pictures)

    javascript variable assignment in if

  6. Tag: variable in javascript

    javascript variable assignment in if

VIDEO

  1. Javascript Variables

  2. Javascript variable understanding #Javascript #front-end #webdevelopment #Technology

  3. Lecture 1: Notes Variable & Data types in Javascript @shradhaKD

  4. 03. JavaScript for LWC: Variables

  5. JavaScript

  6. Variables👬🏻| let ⛹🏻| var 🏋🏻‍♀️

COMMENTS

  1. javascript - Assign variable in if condition statement, good ...

    Assignment in a conditional statement is valid in javascript, because your just asking "if assignment is valid, do something which possibly includes the result of the assignment". But indeed, assigning before the conditional is also valid, not too verbose, and more commonly used.

  2. Making decisions in your code — conditionals - Learn web ...

    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 looks like this: Here we've got: The keyword if followed by some parentheses.

  3. JavaScript if Statements, Equality and Truthy/Falsy ...

    In programming, we use an if statement when we want our code to make a decision. In this tutorial, we'll deep dive into the JavaScript if statement. Along the way, we'll examine the difference between single equals, double equals, and triple equals. We'll also clarify the meaning of truthy and falsy in JavaScript.

  4. JavaScript Variables - W3Schools

    You can also assign a value to the variable when you declare it: let carName = "Volvo"; In the example below, we create a variable called carName and assign the value "Volvo" to it.

  5. JavaScript - Conditional Statements - GeeksforGeeks

    JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

  6. Assignment (=) - JavaScript | MDN - MDN Web Docs

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  7. setting a javascript variable with an if statement -- should ...

    Initialize your variables first, then compare using if statement and assign new values where necessary . var a = "red"; var b; if(a=="red"){ b="hot"; } else{ b="cold"; }

  8. JavaScript Assignment - W3Schools

    Assignment operators assign values to JavaScript variables. The Logical assignment operators are ES2020. The Simple Assignment Operator assigns a value to a variable. The Addition Assignment Operator adds a value to a variable. The Subtraction Assignment Operator subtracts a value from a variable.

  9. JavaScript if/else Statement - W3Schools">JavaScript if/else Statement - W3Schools

    The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

  10. JavaScript: Define a variable in IF statement - linguinecode.com">JavaScript: Define a variable in IF statement - linguinecode.com

    Have you ever tried to write an IF statement to check a primitive/constant value against a JavaScript variable, but accidentally re-defined the variable? let state = "woosah"; if (state = "not-woosah") { console.log("not relaxed!"); } else { console.log("relaxed :)"); }