Conditional branching: if, '?'

Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the if statement and the conditional operator ? , that’s also called a “question mark” operator.

The “if” statement

The if(...) statement evaluates a condition in parentheses and, if the result is true , executes a block of code.

For example:

In the example above, the condition is a simple equality check ( year == 2015 ), but it can be much more complex.

If we want to execute more than one statement, we have to wrap our code block inside curly braces:

We recommend wrapping your code block with curly braces {} every time you use an if statement, even if there is only one statement to execute. Doing so improves readability.

Boolean conversion

The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean.

Let’s recall the conversion rules from the chapter Type Conversions :

  • A number 0 , an empty string "" , null , undefined , and NaN all become false . Because of that they are called “falsy” values.
  • Other values become true , so they are called “truthy”.

So, the code under this condition would never execute:

…and inside this condition – it always will:

We can also pass a pre-evaluated boolean value to if , like this:

The “else” clause

The if statement may contain an optional else block. It executes when the condition is falsy.

Several conditions: “else if”

Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.

In the code above, JavaScript first checks year < 2015 . If that is falsy, it goes to the next condition year > 2015 . If that is also falsy, it shows the last alert .

There can be more else if blocks. The final else is optional.

Conditional operator ‘?’

Sometimes, we need to assign a variable depending on a condition.

For instance:

The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.

The operator is represented by a question mark ? . Sometimes it’s called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

The syntax is:

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2 .

Technically, we can omit the parentheses around age > 18 . The question mark operator has a low precedence, so it executes after the comparison > .

This example will do the same thing as the previous one:

But parentheses make the code more readable, so we recommend using them.

In the example above, you can avoid using the question mark operator because the comparison itself returns true/false :

Multiple ‘?’

A sequence of question mark operators ? can return a value that depends on more than one condition.

It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an ordinary sequence of tests:

  • The first question mark checks whether age < 3 .
  • If true – it returns 'Hi, baby!' . Otherwise, it continues to the expression after the colon “:”, checking age < 18 .
  • If that’s true – it returns 'Hello!' . Otherwise, it continues to the expression after the next colon “:”, checking age < 100 .
  • If that’s true – it returns 'Greetings!' . Otherwise, it continues to the expression after the last colon “:”, returning 'What an unusual age!' .

Here’s how this looks using if..else :

Non-traditional use of ‘?’

Sometimes the question mark ? is used as a replacement for if :

Depending on the condition company == 'Netscape' , either the first or the second expression after the ? gets executed and shows an alert.

We don’t assign a result to a variable here. Instead, we execute different code depending on the condition.

It’s not recommended to use the question mark operator in this way.

The notation is shorter than the equivalent if statement, which appeals to some programmers. But it is less readable.

Here is the same code using if for comparison:

Our eyes scan the code vertically. Code blocks which span several lines are easier to understand than a long, horizontal instruction set.

The purpose of the question mark operator ? is to return one value or another depending on its condition. Please use it for exactly that. Use if when you need to execute different branches of code.

if (a string with zero)

Will alert be shown?

Yes, it will.

Any string except an empty one (and "0" is not empty) becomes true in the logical context.

We can run and check:

The name of JavaScript

Using the if..else construct, write the code which asks: ‘What is the “official” name of JavaScript?’

If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “You don’t know? ECMAScript!”

Demo in new window

Show the sign

Using if..else , write the code which gets a number via prompt and then shows in alert :

  • 1 , if the value is greater than zero,
  • -1 , if less than zero,
  • 0 , if equals zero.

In this task we assume that the input is always a number.

Rewrite 'if' into '?'

Rewrite this if using the conditional operator '?' :

Rewrite 'if..else' into '?'

Rewrite if..else using multiple ternary operators '?' .

For readability, it’s recommended to split the code into multiple lines.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

A Guide to Variable Assignment and Mutation in JavaScript

Darren Jones

Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they’re made out to be?

In this article, we’re going to cover the concepts of variable assignment and mutation and see why — together — they can be a real pain for developers. We’ll look at how to manage them to avoid problems, how to use as few as possible, and how to keep your code predictable.

If you’d like to explore this topic in greater detail, or get up to speed with modern JavaScript, check out the first chapter of my new book Learn to Code with JavaScript for free.

Let’s start by going back to the very basics of value types …

Every value in JavaScript is either a primitive value or an object. There are seven different primitive data types:

  • numbers, such as 3 , 0 , -4 , 0.625
  • strings, such as 'Hello' , "World" , `Hi` , ''
  • Booleans, true and false
  • symbols — a unique token that’s guaranteed never to clash with another symbol
  • BigInt — for dealing with large integer values

Anything that isn’t a primitive value is an object , including arrays, dates, regular expressions and, of course, object literals. Functions are a special type of object. They are definitely objects, since they have properties and methods, but they’re also able to be called.

Variable Assignment

Variable assignment is one of the first things you learn in coding. For example, this is how we would assign the number 3 to the variable bears :

A common metaphor for variables is one of boxes with labels that have values placed inside them. The example above would be portrayed as a box containing the label “bears” with the value of 3 placed inside.

variables like a box

An alternative way of thinking about what happens is as a reference, that maps the label bears to the value of 3 :

variables like a reference

If I assign the number 3 to another variable, it’s referencing the same value as bears:

variables referencing the same value

The variables bears and musketeers both reference the same primitive value of 3. We can verify this using the strict equality operator, === :

The equality operator returns true if both variables are referencing the same value.

Some gotchas when working with objects

The previous examples showed primitive values being assigned to variables. The same process is used when assigning objects:

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

A big difference when assigning objects to variables, however, is that if you assign another object literal to another variable, it will reference a completely different object — even if both object literals look exactly the same! For example, the assignment below looks like the variable tmnt (Teenage Mutant Ninja Turtles) references the same object as the variable ghostbusters :

Even though the variables ghostbusters and tmnt look like they reference the same object, they actually both reference a completely different object, as we can see if we check with the strict equality operator:

variables referencing different objects

Variable Reassignment

When the const keyword was introduced in ES6, many people mistakenly believed that constants had been introduced to JavaScript, but this wasn’t the case. The name of this keyword is a little misleading.

Any variable declared with const can’t be reassigned to another value. This goes for primitive values and objects. For example, the variable bears was declared using const in the previous section, so it can’t have another value assigned to it. If we try to assign the number 2 to the variable bears , we get an error:

The reference to the number 3 is fixed and the bears variable can’t be reassigned another value.

The same applies to objects. If we try to assign a different object to the variable ghostbusters , we get the same error:

Variable reassignment using let

When the keyword let is used to declare a variable, it can be reassigned to reference a different value later on in our code. For example, we declared the variable musketeers using let , so we can change the value that musketeers references. If D’Artagnan joined the Musketeers, their number would increase to 4:

variables referencing different values

This can be done because let was used to declare the variable. We can alter the value that musketeers references as many times as we like.

The variable tmnt was also declared using let , so it can also be reassigned to reference another object (or a different type entirely if we like):

Note that the variable tmnt now references a completely different object ; we haven’t just changed the number property to 5.

In summary , if you declare a variable using const , its value can’t be reassigned and will always reference the same primitive value or object that it was originally assigned to. If you declare a variable using let , its value can be reassigned as many times as required later in the program.

Using const as often as possible is generally considered good practice, as it means that the value of variables remains constant and the code is more consistent and predictable, making it less prone to errors and bugs.

Variable Assignment by Reference

In native JavaScript, you can only assign values to variables. You can’t assign variables to reference another variable, even though it looks like you can. For example, the number of Stooges is the same as the number of Musketeers, so we can assign the variable stooges to reference the same value as the variable musketeers using the following:

This looks like the variable stooges is referencing the variable musketeers , as shown in the diagram below:

variables cannot reference another variable

However, this is impossible in native JavaScript: a variable can only reference an actual value; it can’t reference another variable . What actually happens when you make an assignment like this is that the variable on the left of the assignment will reference the value the variable on the right references, so the variable stooges will reference the same value as the musketeers variable, which is the number 3. Once this assignment has been made, the stooges variable isn’t connected to the musketeers variable at all.

variables referencing values

This means that if D’Artagnan joins the Musketeers and we set the value of the musketeers to 4, the value of stooges will remain as 3. In fact, because we declared the stooges variable using const , we can’t set it to any new value; it will always be 3.

In summary : if you declare a variable using const and set it to a primitive value, even via a reference to another variable, then its value can’t change. This is good for your code, as it means it will be more consistent and predictable.

A value is said to be mutable if it can be changed. That’s all there is to it: a mutation is the act of changing the properties of a value.

All primitive value in JavaScript are immutable : you can’t change their properties — ever. For example, if we assign the string "cake" to variable food , we can see that we can’t change any of its properties:

If we try to change the first letter to “f”, it looks like it has changed:

But if we take a look at the value of the variable, we see that nothing has actually changed:

The same thing happens if we try to change the length property:

Despite the return value implying that the length property has been changed, a quick check shows that it hasn’t:

Note that this has nothing to do with declaring the variable using const instead of let . If we had used let , we could set food to reference another string, but we can’t change any of its properties. It’s impossible to change any properties of primitive data types because they’re immutable .

Mutability and objects in JavaScript

Conversely, all objects in JavaScript are mutable, which means that their properties can be changed, even if they’re declared using const (remember let and const only control whether or not a variable can be reassigned and have nothing to do with mutability). For example, we can change the the first item of an array using the following code:

Note that this change still occurred, despite the fact that we declared the variable food using const . This shows that using const does not stop objects from being mutated .

We can also change the length property of an array, even if it has been declared using const :

Copying by Reference

Remember that when we assign variables to object literals, the variables will reference completely different objects, even if they look the same:

But if we assign a variable fantastic4 to another variable, they will both reference the same object:

This assigns the variable fantastic4 to reference the same object that the variable tmnt references, rather than a completely different object.

variables referencing the same object

This is often referred to as copying by reference , because both variables are assigned to reference the same object.

This is important, because any mutations made to this object will be seen in both variables.

So, if Spider-Man joins The Fantastic Four, we might update the number value in the object:

This is a mutation, because we’ve changed the number property rather than setting fantastic4 to reference a new object.

This causes us a problem, because the number property of tmnt will also also change, possibly without us even realizing:

This is because both tmnt and fantastic4 are referencing the same object, so any mutations that are made to either tmnt or fantastic4 will affect both of them.

This highlights an important concept in JavaScript: when objects are copied by reference and subsequently mutated, the mutation will affect any other variables that reference that object. This can lead to unintended side effects and bugs that are difficult to track down.

The Spread Operator to the Rescue!

So how do you make a copy of an object without creating a reference to the original object? The answer is to use the spread operator !

The spread operator was introduced for arrays and strings in ES2015 and for objects in ES2018. It allows you to easily make a shallow copy of an object without creating a reference to the original object.

The example below shows how we could set the variable fantastic4 to reference a copy of the tmnt object. This copy will be exactly the same as the tmnt object, but fantastic4 will reference a completely new object. This is done by placing the name of the variable to be copied inside an object literal with the spread operator in front of it:

What we’ve actually done here is assign the variable fantastic4 to a new object literal and then used the spread operator to copy all the enumerable properties of the object referenced by the tmnt variable. Because these properties are values, they’re copied into the fantastic4 object by value, rather than by reference.

variables referencing different objects

Now any changes that are made to either object won’t affect the other. For example, if we update the number property of the fantastic4 variable to 5, it won’t affect the tmnt variable:

Changes don't affect the other object

The spread operator also has a useful shortcut notation that can be used to make copies of an object and then make some changes to the new object in a single line of code.

For example, say we wanted to create an object to model the Teenage Mutant Ninja Turtles. We could create the first turtle object, and assign the variable leonardo to it:

The other turtles all have the same properties, except for the weapon and color properties, that are different for each turtle. It makes sense to make a copy of the object that leonardo references, using the spread operator, and then change the weapon and color properties, like so:

We can do this in one line by adding the properties we want to change after the reference to the spread object. Here’s the code to create new objects for the variables donatello and raphael :

Note that using the spread operator in this way only makes a shallow copy of an object. To make a deep copy, you’d have to do this recursively, or use a library. Personally, I’d advise that you try to keep your objects as shallow as possible.

Are Mutations Bad?

In this article, we’ve covered the concepts of variable assignment and mutation and seen why — together — they can be a real pain for developers.

Mutations have a bad reputation, but they’re not necessarily bad in themselves. In fact, if you’re building a dynamic web app, it must change at some point. That’s literally the meaning of the word “dynamic”! This means that there will have to be some mutations somewhere in your code. Having said that, the fewer mutations there are, the more predictable your code will be, making it easier to maintain and less likely to develop any bugs.

A particularly toxic combination is copying by reference and mutations. This can lead to side effects and bugs that you don’t even realize have happened. If you mutate an object that’s referenced by another variable in your code, it can cause lots of problems that can be difficult to track down. The key is to try and minimize your use of mutations to the essential and keep track of which objects have been mutated.

In functional programming, a pure function is one that doesn’t cause any side effects, and mutations are one of the biggest causes of side effects.

A golden rule is to avoid copying any objects by reference. If you want to copy another object, use the spread operator and then make any mutations immediately after making the copy.

Next up, we’ll look into array mutations in JavaScript .

Don’t forget to check out my new book Learn to Code with JavaScript if you want to get up to speed with modern JavaScript. You can read the first chapter for free. And please reach out on Twitter if you have any questions or comments!

Frequently Asked Questions (FAQs) about JavaScript Variable Assignment and Mutation

What is the difference between variable assignment and mutation in javascript.

In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand, mutation refers to the process of changing the value of an existing variable. For example, if we later write x = 10; we are mutating the variable x by changing its value from 5 to 10.

How does JavaScript handle variable assignment and mutation differently for primitive and non-primitive data types?

JavaScript treats primitive data types (like numbers, strings, and booleans) and non-primitive data types (like objects and arrays) differently when it comes to variable assignment and mutation. For primitive data types, when you assign a variable, a copy of the value is created and stored in a new memory location. However, for non-primitive data types, when you assign a variable, both variables point to the same memory location. Therefore, if you mutate one variable, the change is reflected in all variables that point to that memory location.

What is the concept of pass-by-value and pass-by-reference in JavaScript?

Pass-by-value and pass-by-reference are two ways that JavaScript can pass variables to a function. When JavaScript passes a variable by value, it creates a copy of the variable’s value and passes that copy to the function. Any changes made to the variable inside the function do not affect the original variable. However, when JavaScript passes a variable by reference, it passes a reference to the variable’s memory location. Therefore, any changes made to the variable inside the function also affect the original variable.

How can I prevent mutation in JavaScript?

There are several ways to prevent mutation in JavaScript. One way is to use the Object.freeze() method, which prevents new properties from being added to an object, existing properties from being removed, and prevents changing the enumerability, configurability, or writability of existing properties. Another way is to use the const keyword when declaring a variable. This prevents reassignment of the variable, but it does not prevent mutation of the variable’s value if the value is an object or an array.

What is the difference between shallow copy and deep copy in JavaScript?

In JavaScript, a shallow copy of an object is a copy of the object where the values of the original object and the copy point to the same memory location for non-primitive data types. Therefore, if you mutate the copy, the original object is also mutated. On the other hand, a deep copy of an object is a copy of the object where the values of the original object and the copy do not point to the same memory location. Therefore, if you mutate the copy, the original object is not mutated.

How can I create a deep copy of an object in JavaScript?

One way to create a deep copy of an object in JavaScript is to use the JSON.parse() and JSON.stringify() methods. The JSON.stringify() method converts the object into a JSON string, and the JSON.parse() method converts the JSON string back into an object. This creates a new object that is a deep copy of the original object.

What is the MutationObserver API in JavaScript?

The MutationObserver API provides developers with a way to react to changes in a DOM. It is designed to provide a general, efficient, and robust API for reacting to changes in a document.

How does JavaScript handle variable assignment and mutation in the context of closures?

In JavaScript, a closure is a function that has access to its own scope, the scope of the outer function, and the global scope. When a variable is assigned or mutated inside a closure, it can affect the value of the variable in the outer scope, depending on whether the variable was declared in the closure’s scope or the outer scope.

What is the difference between var, let, and const in JavaScript?

In JavaScript, var, let, and const are used to declare variables. var is function scoped, and if it is declared outside a function, it is globally scoped. let and const are block scoped, meaning they exist only within the block they are declared in. The difference between let and const is that let allows reassignment, while const does not.

How does JavaScript handle variable assignment and mutation in the context of asynchronous programming?

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

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

JavaScript: Define a variable in IF statement

javascript if variable assignment

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 if variable assignment

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?

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop

JavaScript break Statement

JavaScript continue Statement

JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript while and do...while Loop

  • JavaScript Ternary Operator

JavaScript if...else Statement

In computer programming, there may arise situations where you have to run a block of code among more than one alternatives. For example, assigning grades A , B or C based on marks obtained by a student.

In such situations, you can use the JavaScript if...else statement to create a program that can make decisions.

In JavaScript, there are three forms of the if...else statement.

  • if statement
  • if...else statement
  • if...else if...else statement
  • JavaScript if Statement

The syntax of the if statement is:

The if statement evaluates the condition inside the parenthesis () .

  • If the condition is evaluated to true , the code inside the body of if is executed.
  • If the condition is evaluated to false , the code inside the body of if is skipped.

Note: The code inside { } is the body of the if statement.

Working of if statement in JavaScript

Example 1: if Statement

Suppose the user entered 2 . In this case, the condition number > 0 evaluates to true . And, the body of the if statement is executed.

Suppose the user entered -1 . In this case, the condition number > 0 evaluates to false . Hence, the body of the if statement is skipped.

Since console.log("The if statement is easy"); is outside the body of the if statement, it is always executed.

Comparison and logical operators are used in conditions. So to learn more about comparison and logical operators, you can visit JavaScript Comparison and Logical Operators .

  • JavaScript if...else statement

An if statement can have an optional else clause. The syntax of the if...else statement is:

The if..else statement evaluates the condition inside the parenthesis.

If the condition is evaluated to true ,

  • the code inside the body of if is executed
  • the code inside the body of else is skipped from execution

If the condition is evaluated to false ,

  • the code inside the body of else is executed
  • the code inside the body of if is skipped from execution

Working of if-else statement in JavaScript

Example 2: if…else Statement

Suppose the user entered 2 . In this case, the condition number > 0 evaluates to true . Hence, the body of the if statement is executed and the body of the else statement is skipped.

Suppose the user entered -1 . In this case, the condition number > 0 evaluates to false . Hence, the body of the else statement is executed and the body of the if statement is skipped.

  • JavaScript if...else if statement

The if...else statement is used to execute a block of code among two alternatives. However, if you need to make a choice between more than two alternatives, if...else if...else can be used.

The syntax of the if...else if...else statement is:

  • If condition1 evaluates to true , the code block 1 is executed.
  • If the condition2 is true , the code block 2 is executed.
  • If the condition2 is false , the code block 3 is executed.

Working of if-else ladder statement in JavaScript

Example 3: if...else if Statement

Suppose the user entered 0 , then the first test condition number > 0 evaluates to false . Then, the second test condition number == 0 evaluates to true and its corresponding block is executed.

  • Nested if...else Statement

You can also use an if...else statement inside of an if...else statement. This is known as nested if...else statement.

Example 4: Nested if...else Statement

Suppose the user entered 5 . In this case, the condition number >= 0 evaluates to true , and the control of the program goes inside the outer if statement.

Then, the test condition, number == 0 , of the inner if statement is evaluated. Since it's false, the else clause of the inner if statement is executed.

Note: As you can see, nested if...else makes our logic complicated and we should try to avoid using nested if...else whenever possible.

Body of if...else With Only One Statement

If the body of if...else has only one statement, we can omit { } in our programs. For example, you can replace

More on Decision Making

In certain situations, a ternary operator can replace an if...else statement. To learn more, visit JavaScript Ternary Operator .

If you need to make a choice between more than one alternatives based on a given test condition, the switch statement can be used. To learn more, visit JavaScript switch .

Table of Contents

Video: javascript if...else.

Sorry about that.

Related Tutorials

JavaScript Tutorial

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.

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 variables, variables are containers for storing data.

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • Using const

In this first example, x , y , and z are undeclared variables.

They are automatically declared when first used:

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

Example using const, mixed example.

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

From the example above, you can guess that the total is calculated to be 11.

Variables are containers for storing values.

Advertisement

JavaScript Identifiers

All JavaScript variables must be identified with unique names .

These unique names are called identifiers .

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

JavaScript identifiers are case-sensitive.

The Assignment Operator

In JavaScript, the equal sign ( = ) is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

After the declaration, the variable has no value (technically it is undefined ).

To assign a value to the variable, use the equal sign:

You can also assign a value to the variable when you declare it:

In the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma :

A declaration can span multiple lines:

Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined .

The variable carName will have the value undefined after the execution of this statement:

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var , it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these statements:

You cannot re-declare a variable declared with let or const .

This will not work:

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :

You can also add strings, but strings will be concatenated:

Also try this:

If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.

Now try this:

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements".

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

Test Yourself With Exercises

Create a variable called carName and assign the value Volvo to it.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Home

3 Ways to Check if a Variable is Defined in JavaScript

From time to time you have to check whether a variable is defined in JavaScript. For example, to determine if an external script has been successfully loaded into the web page, or to determine if the browser supports a Web API ( IntersectionObserver , Intl ).

How to check if a variable is defined in JavaScript? The answer is not straightforward, so let's find out!

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn't easy... but fortunately with a good teacher you can shortcut.

Take "Modern JavaScript From The Beginning 2.0" course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

1. The states of a variable

Before jumping into specific techniques, I'd like to have an agreement on the related terms.

In the following 2 sections, let's make clear what it means for a variable to be "defined"/"not defined" and "initialized"/"uninitialized".

1.1 Defined / not defined variable

A variable is defined when it has been declared in the current scope using a declaration statement.

The usual way to declarate variables is const , let and var statements, plus the function and class declaration statements.

Examples of defined variables :

Contrary, a variable is not defined when it hasn't been declared in the current scope using a declaration statement.

Examples of not defined variables :

The scope sets the limits where the variable is defined and accessible. A scope in JavaScript is defined by a code block (for const and let variables) and by a function body (for const , let , var ).

Accessing a variable that's not defined throws a ReferenceError :

1.2 Initialized / uninitialized variable

A variable is initialized when the declared variable has been assigned with an initial value.

Examples of initialized variables :

On the other side, a variable is uninitialized when the declared variable has not been assigned with an initial value.

Examples of uninitialized variables :

The value of an uninitialized variable is always undefined :

2. Using typeof

Knowing the possible states of variables, let's consider the techniques to find whether a variable is defined or not.

The typeof operator determines the variable's type. typeof myVar can evaluate to one of the values: 'boolean' , 'number' , 'string' , 'symbol' , 'object' , 'function' and 'undefined' .

The expression typeof missingVar doesn't throw a ReferenceError if the missingVar is not defined, contrary to simple access of the not defined variable:

That's great because you can use the expression typeof myVar === 'undefined' to determine if the variable is not defined:

Be aware that typeof myVar === 'undefined' evaluates to true when myVar is not defined , but also when defined and uninitialized . All because accessing a defined but uninitialized variable evaluates to undefined .

Usually, that's not a problem. When you check if the variable is defined, you want it initialized with a payload too.

Of course, if the variable is defined and has a value, typeof myVar === 'undefined' evaluates to false :

3. Using try/catch

When accessing a not defined variable, JavaScript throws a reference error:

So... what about wrapping the checked variable in a try block, and try to catch the reference error? If the error is caught, that would mean that the variable is not defined:

missingVar in the above example is not defined. When trying to access the variable in a try block, a ReferenceError error is thrown and catch block catches this reference error. That's another way to check the variable's existence.

Of course, if the variable is defined, no reference error is thrown:

Compared to typeof approach, the try/catch is more precise because it determines solely if the variable is not defined , despite being initialized or uninitialized.

4. Using window.hasOwnProperty()

Finally, to check for the existence of global variables, you can go with a simpler approach.

Each global variable is stored as a property on the global object ( window in a browser environment, global in NodeJS). You can use this idea to determine if the global variable myGlobalVar is defined: simply check the global object for corresponding property existence: window.hasOwnProperty('myGlobalVar') .

For example, here's how to check if the browser defines an IntersectionObserver variable:

var variables and function declarations, when used in the outermost scope (aka global scope), do create properties on the global object:

However, be aware that const and let variables, as well as class declarations, do not create properties on the global object:

In JavaScript, a variable can be either defined or not defined, as well as initialized or uninitialized.

typeof myVar === 'undefined' evaluates to true if myVar is not defined, but also defined and uninitialized. That's a quick way to determine if a variable is defined.

Another approach is to wrap the variable in a try { myVar } block, then catch the possible reference error in a catch(e) { } block. If you've caught a ReferenceError , then the variable is not defined.

Finally, to check the existence of a global variable myGlobalVar invoke window.hasOwnProperty('myGlobalVar') . This approach is useful to check if the browser supports a Web API.

What is your preferred way to check if a variable is defined?

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

  • Developing Applications with Oracle Visual Builder in Oracle Integration Generation 2
  • Develop Applications
  • Work with Pages and Flows
  • Work With Code Editors

Work with the JavaScript Editor

Use the JavaScript editor to add custom JavaScript functions that meet your business requirements, for example, a JavaScript function to validate whether required fields in a form have values.

Any JavaScript code that you add will have a defined scope based on the editor where you write the code. If your code will only be called from within a specific page (for example, to load some data when the page loads), you can write your code in the page-level JavaScript editor. If you want a JavaScript function to be used on multiple pages (for example, to load libraries for customizing navigation elements or custom web components), then you'll need to use the JavaScript editor for the flow or the application. You can also define JavaScript functions at the layout and fragment level.

The JavaScript editor displays a particular artifact's JS file. So if you open the main flow's JavaScript editor (for example), you're seeing the contents of the main-flow.js file. Each artifact has its own JS file: an application artifact uses the app-flow.js file, a flow uses flow-name -flow.js , and a page uses page-name -page.js . A layout uses layout.js and a fragment uses fragment-name -fragment.js .

Description of js-code-complete-example.png follows

Selecting a structure will let you easily switch the variables in the structure.

  • https://www.w3schools.com/js/js_es6.asp
  • https://www.javascripttutorial.net/es6/

Add a Custom JavaScript Function

To add a custom JavaScript function, you define the function within the class provided in the JavaScript editor for your page, flow, or application . You can also add JavaScript functions to layouts and fragments.

Description of page-functions-editor.png follows

An application uses the app-flow.js file, a flow uses flow-name -flow.js , and a page uses page-name -page.js . A layout uses layout.js and a fragment fragment-name -fragment.js .

Just as flow-level functions use FlowModule , application functions use AppModule and page-level functions use PageModule .

Description of javascript-function-example.png follows

  • In an action chain, use the Call Function action. See Add a Call Function Action .

Description of js_functions_variablepicker.png follows

To write efficient expressions that handle situations where a referenced field might not be available or the field's value could be null, see How Do I Write Expressions If a Referenced Field Might Not Be Available Or Its Value Could Be Null?

Use RequireJS to Reference External JavaScript Files

If you want to use RequireJS to refer to external JavaScript libraries in your application , you can add a requirejs statement to your application 's definition, then import the library.

  • In the Web Apps pane, select your application node, then click the JSON tab, or
  • In the Source view, locate the file for your application under webapps .

Either way, make sure the requirejs entry is a sibling of the id or description entries. If a requirejs section already exists, simply add your entry under paths .

  • To load and use your library in a module, use the define statement to make your library a dependency for your module. In your JS file, enter, for example: define(['myLib'], (MyLib) => { 'use strict'; ...

Use Variables with a JavaScript Module

You can't directly get or set variables from within your JavaScript modules. However, you can use the Call Module Function action to access your JS module. This action takes an array of parameters which can include variables and can return a result that you can assign to a variable.

This approach ensures that the variable has a consistent state from the beginning to the end of your action chain's execution.

To "get" a value, pass the variable in as a parameter to the module function that you are calling using a callModuleFunction action in the action chain.

To "set" a variable based on the return value from that callModuleFunction , use an Assign Variables action to copy the result of the function into the desired variable in whatever scope.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Logical AND (&&)

The logical AND ( && ) (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy .

Description

Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy , the value of the last operand is returned.

If a value can be converted to true , the value is so-called truthy . If a value can be converted to false , the value is so-called falsy .

Examples of expressions that can be converted to false are:

  • empty string ( "" or '' or `` );
  • undefined .

The AND operator preserves non-Boolean values and returns them as they are:

Even though the && operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a boolean primitive . To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.

Short-circuit evaluation

The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.

Consider the pseudocode below.

The expr part is never evaluated because the first operand (some falsy expression) is evaluated as falsy . If expr is a function, the function is never called. See the example below:

Operator precedence

The AND operator has a higher precedence than the OR operator, meaning the && operator is executed before the || operator (see operator precedence ).

The following code shows examples of the && (logical AND) operator.

Conversion rules for booleans

Converting and to or.

The following operation involving booleans :

is always equal to:

Converting OR to AND

Removing nested parentheses.

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.

The following composite operation involving booleans :

Specifications

Browser compatibility.

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

IMAGES

  1. JavaScript if...else Statement (with Examples)

    javascript if variable assignment

  2. Two Ways To Declare Variables In JavaScript

    javascript if variable assignment

  3. JavaScript if Statement

    javascript if variable assignment

  4. JS: Assigning values to multiple variables : r/learnjavascript

    javascript if variable assignment

  5. Javascript If Else (with Examples)

    javascript if variable assignment

  6. JavaScript Assignment Operators

    javascript if variable assignment

VIDEO

  1. Lecture 1 of JS (Introduction of JS, variables, and datatypes)

  2. JavaScript

  3. Javascript 102: Javascript Variable & Operator

  4. Let Variable in JavaScript #coding #javascript #js #shorts

  5. Learn JavaScript In Arabic 2021

  6. JavaScript: Variable and DataTypes

COMMENTS

  1. Best Way for Conditional Variable Assignment

    Best Way for Conditional Variable Assignment Ask Question Asked 11 years, 8 months ago Modified 8 months ago Viewed 154k times 65 Which is the better way for conditional variable assignment? 1st method if (true) { var myVariable = 'True'; } else { var myVariable = 'False'; } 2nd Method var myVariable = 'False'; if (true) { myVariable = 'True'; }

  2. Assignment (=)

    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. Try it Syntax js x = y Parameters x

  3. if...else

    statement1 // With an else clause if (condition)

  4. Logical OR assignment (||=)

    Syntax js x ||= y 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.

  5. Conditional branching: if,

    The "else" clause The if statement may contain an optional else block. It executes when the condition is falsy. For example: let year = prompt('In which year was the ECMAScript-2015 specification published?', ''); if ( year == 2015) { alert( 'You guessed it right!' ); } else { alert( 'How can you be so wrong?' ); // any value except 2015 }

  6. A Guide to Variable Assignment and Mutation in JavaScript

    May 18, 2021 Share Mutations are something you hear about fairly often in the world of JavaScript, but what exactly are they, and are they as evil as they're made out to be? In this article,...

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

    Variable assignment inside an 'if' condition in JavaScript Ask Question Asked 9 years, 10 months ago Modified 5 years, 3 months ago Viewed 6k times 36 How does the below code execute? if (a=2 && (b=8)) { console.log (a) } OUTPUT a=8 javascript operators Share Improve this question Follow edited Nov 12, 2018 at 10:52 Salman A 266k 82 431 525

  8. JavaScript Assignment

    Assignment operators assign values to JavaScript variables. Shift Assignment Operators Bitwise Assignment Operators Logical Assignment Operators Note The Logical assignment operators are ES2020 . The = Operator The Simple Assignment Operator assigns a value to a variable. Simple Assignment Examples let x = 10; Try it Yourself » let x = 10 + y;

  9. JavaScript: Define a variable in IF statement

    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.

  10. JavaScript if/else Statement

    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 ...

  11. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  12. JavaScript if...else Statement (with Examples)

    JS Variables & Constants; JS console.log; JavaScript Data types; JavaScript Operators; JavaScript Comments; JS Type Conversions; JS Control Flow. JS Comparison Operators; JavaScript if else Statement; JavaScript for loop; JavaScript while loop; JavaScript break Statement; JavaScript continue Statement; JavaScript switch Statement; JS Functions ...

  13. IF statement as assignment expression in JavaScript

    IF statement as assignment expression in JavaScript Ask Question Asked 9 years, 2 months ago Modified 9 years, 2 months ago Viewed 2k times 4 The JSLint Error Explanations document ( https://jslinterrors.com/unexpected-assignment-expression) says that if we evaluate an assignment expression (x = 0) the IF body will never be executed (y = 1).

  14. 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:

  15. JavaScript Variables

    JavaScript Variables can be declared in 4 ways: Automatically Using var Using let Using const In this first example, x , y, and z are undeclared variables. They are automatically declared when first used: Example x = 5; y = 6; z = x + y; Try it Yourself » Note It is considered good programming practice to always declare variables before use.

  16. 3 Ways to Check if a Variable is Defined in JavaScript

    1. The states of a variable Before jumping into specific techniques, I'd like to have an agreement on the related terms. In the following 2 sections, let's make clear what it means for a variable to be "defined"/"not defined" and "initialized"/"uninitialized". 1.1 Defined / not defined variable

  17. JavaScript OR (||) variable assignment explanation

    var a; var b = null; var c = undefined; var d = 4; var e = 'five'; var f = a || b || c || d || e; alert(f); // 4 Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?

  18. Meaningful Names in JavaScript Code

    Update Names with Refactoring: If the purpose of a variable, function, or class changes, its name should be updated to reflect the new purpose. Conclusion. Naming is a powerful tool in the developer's arsenal, especially in a flexible and dynamic language like JavaScript.

  19. Nullish coalescing assignment (??=)

    The nullish coalescing assignment ( ??=) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ). Try it Syntax js x ??= y Description

  20. Work with the JavaScript Editor

    This approach ensures that the variable has a consistent state from the beginning to the end of your action chain's execution. To "get" a value, pass the variable in as a parameter to the module function that you are calling using a callModuleFunction action in the action chain.. To "set" a variable based on the return value from that callModuleFunction, use an Assign Variables action to copy ...

  21. var

    Syntax js var name1; var name1 = value1; var name1 = value1, name2 = value2; var name1, name2 = value2; var name1 = value1, name2, /* …, */ nameN = valueN; nameN The name of the variable to declare.

  22. Logical AND (&&)

    Description. Logical AND ( &&) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned. If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called ...

  23. How does variable assignment work in JavaScript?

    102 So I was playing around the other day just to see exactly how mass assignment works in JavaScript. First I tried this example in the console: a = b = {}; a.foo = 'bar'; console.log(b.foo); The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object.