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.

A real-life analogy

We can easily grasp the concept of a “variable” if we imagine it as a “box” for data, with a uniquely-named sticker on it.

For instance, the variable message can be imagined as a box labelled "message" with the value "Hello!" in it:

We can put any value in the box.

We can also change it as many times as we want:

When the value is changed, the old data is removed from the variable:

We can also declare two variables and copy data from one into the other.

A variable should be declared only once.

A repeated declaration of the same variable is an error:

So, we should declare a variable once and then refer to it without let .

It’s interesting to note that there exist so-called pure functional programming languages, such as Haskell , that forbid changing variable values.

In such languages, once the value is stored “in the box”, it’s there forever. If we need to store something else, the language forces us to create a new box (declare a new variable). We can’t reuse the old one.

Though it may seem a little odd at first sight, these languages are quite capable of serious development. More than that, there are areas like parallel computations where this limitation confers certain benefits.

Variable naming

There are two limitations on variable names in JavaScript:

  • The name must contain only letters, digits, or the symbols $ and _ .
  • The first character must not be a digit.

Examples of valid names:

When the name contains multiple words, camelCase is commonly used. That is: words go one after another, each word except first starting with a capital letter: myVeryLongName .

What’s interesting – the dollar sign '$' and the underscore '_' can also be used in names. They are regular symbols, just like letters, without any special meaning.

These names are valid:

Examples of incorrect variable names:

Variables named apple and APPLE are two different variables.

It is possible to use any language, including Cyrillic letters, Chinese logograms and so on, like this:

Technically, there is no error here. Such names are allowed, but there is an international convention to use English in variable names. Even if we’re writing a small script, it may have a long life ahead. People from other countries may need to read it sometime.

There is a list of reserved words , which cannot be used as variable names because they are used by the language itself.

For example: let , class , return , and function are reserved.

The code below gives a syntax error:

Normally, we need to define a variable before using it. But in the old times, it was technically possible to create a variable by a mere assignment of the value without using let . This still works now if we don’t put use strict in our scripts to maintain compatibility with old scripts.

This is a bad practice and would cause an error in strict mode:

To declare a constant (unchanging) variable, use const instead of let :

Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so would cause an error:

When a programmer is sure that a variable will never change, they can declare it with const to guarantee and communicate that fact to everyone.

Uppercase constants

There is a widespread practice to use constants as aliases for difficult-to-remember values that are known before execution.

Such constants are named using capital letters and underscores.

For instance, let’s make constants for colors in so-called “web” (hexadecimal) format:

  • COLOR_ORANGE is much easier to remember than "#FF7F00" .
  • It is much easier to mistype "#FF7F00" than COLOR_ORANGE .
  • When reading the code, COLOR_ORANGE is much more meaningful than #FF7F00 .

When should we use capitals for a constant and when should we name it normally? Let’s make that clear.

Being a “constant” just means that a variable’s value never changes. But some constants are known before execution (like a hexadecimal value for red) and some constants are calculated in run-time, during the execution, but do not change after their initial assignment.

For instance:

The value of pageLoadTime is not known before the page load, so it’s named normally. But it’s still a constant because it doesn’t change after the assignment.

In other words, capital-named constants are only used as aliases for “hard-coded” values.

Name things right

Talking about variables, there’s one more extremely important thing.

A variable name should have a clean, obvious meaning, describing the data that it stores.

Variable naming is one of the most important and complex skills in programming. A glance at variable names can reveal which code was written by a beginner versus an experienced developer.

In a real project, most of the time is spent modifying and extending an existing code base rather than writing something completely separate from scratch. When we return to some code after doing something else for a while, it’s much easier to find information that is well-labelled. Or, in other words, when the variables have good names.

Please spend time thinking about the right name for a variable before declaring it. Doing so will repay you handsomely.

Some good-to-follow rules are:

  • Use human-readable names like userName or shoppingCart .
  • Stay away from abbreviations or short names like a , b , and c , unless you know what you’re doing.
  • Make names maximally descriptive and concise. Examples of bad names are data and value . Such names say nothing. It’s only okay to use them if the context of the code makes it exceptionally obvious which data or value the variable is referencing.
  • Agree on terms within your team and in your mind. If a site visitor is called a “user” then we should name related variables currentUser or newUser instead of currentVisitor or newManInTown .

Sounds simple? Indeed it is, but creating descriptive and concise variable names in practice is not. Go for it.

And the last note. There are some lazy programmers who, instead of declaring new variables, tend to reuse existing ones.

As a result, their variables are like boxes into which people throw different things without changing their stickers. What’s inside the box now? Who knows? We need to come closer and check.

Such programmers save a little bit on variable declaration but lose ten times more on debugging.

An extra variable is good, not evil.

Modern JavaScript minifiers and browsers optimize code well enough, so it won’t create performance issues. Using different variables for different values can even help the engine optimize your code.

We can declare variables to store data by using the var , let , or const keywords.

  • let – is a modern variable declaration.
  • var – is an old-school variable declaration. Normally we don’t use it at all, but we’ll cover subtle differences from let in the chapter The old "var" , just in case you need them.
  • const – is like let , but the value of the variable can’t be changed.

Variables should be named in a way that allows us to easily understand what’s inside them.

Working with variables

  • Declare two variables: admin and name .
  • Assign the value "John" to name .
  • Copy the value from name to admin .
  • Show the value of admin using alert (must output “John”).

In the code below, each line corresponds to the item in the task list.

Giving the right name

  • Create a variable with the name of our planet. How would you name such a variable?
  • Create a variable to store the name of a current visitor to a website. How would you name that variable?

The variable for our planet

That’s simple:

Note, we could use a shorter name planet , but it might not be obvious what planet it refers to. It’s nice to be more verbose. At least until the variable isNotTooLong.

The name of the current visitor

Again, we could shorten that to userName if we know for sure that the user is current.

Modern editors and autocomplete make long variable names easy to write. Don’t save on them. A name with 3 words in it is fine.

And if your editor does not have proper autocompletion, get a new one .

Uppercase const?

Examine the following code:

Here we have a constant birthday for the date, and also the age constant.

The age is calculated from birthday using someCode() , which means a function call that we didn’t explain yet (we will soon!), but the details don’t matter here, the point is that age is calculated somehow based on the birthday .

Would it be right to use upper case for birthday ? For age ? Or even for both?

We generally use upper case for constants that are “hard-coded”. Or, in other words, when the value is known prior to execution and directly written into the code.

In this code, birthday is exactly like that. So we could use the upper case for it.

In contrast, age is evaluated in run-time. Today we have one age, a year after we’ll have another one. It is constant in a sense that it does not change through the code execution. But it is a bit “less of a constant” than birthday : it is calculated, so we should keep the lower case for it.

  • 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

JavaScript Variables

Variable means anything that can vary. In JavaScript, a variable stores data that can be changed later on.

Declare a Variable

In JavaScript, a variable can be declared using var , let , const keywords.

  • var keyword is used to declare variables since JavaScript was created. It is confusing and error-prone when using variables declared using var .
  • let keyword removes the confusion and error of var . It is the new and recommended way of declaring variables in JavaScript.
  • const keyword is used to declare a constant variable that cannot be changed once assigned a value.

Here, we will use the let keyword to declare variables. To declare a variable, write the keyword let followed by the name of the variable you want to give, as shown below.

In the above example, var msg; is a variable declaration. It does not have any value yet. The default value of variables that do not have any value is undefined .

You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.

In the above example, the msg variable is declared first and then assigned a string value in the next line.

You can declare a variable and assign a value to it in the same line. Values can be of any datatype such as string , numeric , boolean , etc.

Multiple variables can be declared in a single line, as shown below.

You can copy the value of one variable to another variable, as shown below.

JavaScript allows multiple white spaces and line breaks when you declare a variables.

Variable names are case-sensitive in JavaScript. You cannot declare a duplicate variable using the let keyword with the same name and case. JavaScript will throw a syntax error. Although, variables can have the same name if declared with the var keyword (this is why it is recommended to use let ).

JavaScript Variable Nameing Conventions

  • Variable names are case-sensitive in JavaScript. So, the variable names msg , MSG , Msg , mSg are considered separate variables.
  • Variable names can contain letters, digits, or the symbols $ and _.
  • A variable name cannot start with a digit 0-9.
  • A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return cannot be variable names.

Dynamic Typing

JavaScript is a loosely typed language. It means that you don't need to specify what data type a variable will contain. You can update the value of any type after initialization. It is also called dynamic typing.

Constant Variables in JavaScript

Use const keyword to declare a constant variable in JavaScript.

  • Constant variables must be declared and initialized at the same time.
  • The value of the constant variables can't be changed after initialized them.

The value of a constant variable cannot be changed but the content of the value can be changed. For example, if an object is assigned to a const variable then the underlying value of an object can be changed.

It is best practice to give constant variable names in capital letters to separate them from other non-constant variables.

Variable Scope

In JavaScript, a variable can be declared either in the global scope or the local scope.

Global Variables

Variables declared out of any function are called global variables. They can be accessed anywhere in the JavaScript code, even inside any function.

Local Variables

Variables declared inside the function are called local variables of that function. They can only be accessed in the function where they are declared but not outside.

The following example includes global and local variables.

Learn global and local scope in JavaScript for more information.

Declare Variables without var and let Keywords

Variables can be declared and initialized without the var or let keywords. However, a value must be assigned to a variable declared without the var keyword.

The variables declared without the var keyword become global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.

It is Recommended to declare variable using the let keyword.

javascript assignment of variable

  • Variables can be defined using let keyword. Variables defined without let or var keyword become global variables.
  • Variables should be initialized before accessing it. Unassigned variable has value undefined .
  • JavaScript is a loosely-typed language, so a variable can store any type value.
  • Variables can have local or global scope. Local variables cannot be accessed out of the function where they are declared, whereas the global variables can be accessed from anywhere.

.NET Tutorials

Database tutorials, javascript tutorials, programming tutorials.

  • JavaScript Minifier
  • JSON Formatter
  • XML Formatter

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

The Addition Operator + adds numbers:

The Assignment Operator = assigns a value to a variable.

Operators

JavaScript Assignment

The Assignment Operator ( = ) assigns a value to a variable:

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator ( += ) adds a value to a variable.

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

Note that strings are compared alphabetically:

JavaScript String Addition

The + can also be used to add (concatenate) strings:

The += assignment operator can also be used to add (concatenate) strings:

The result of text1 will be:

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

The result of x , y , and z will be:

If you add a number and a string, the result will be a string!

JavaScript Logical Operators

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers. Because of this, in JavaScript, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

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.

Multiple Variable Assignment in JavaScript

  • JavaScript Howtos
  • Multiple Variable Assignment in …

Use the = Operator to Assign Multiple Variable in JavaScript

Multiple variable assignment using destructuring assignment with fill() function in javascript.

Multiple Variable Assignment in JavaScript

This tutorial explains multiple variable assignments in JavaScript because variables are the most important part of our coding.

Sometimes, we have to do many variable declarations and assignments as they have the same value. How? Let’s understand.

Assume we have variable1 , variable2 , and variable3 and want all three variables to have a value of 1 .

They seem equivalent, but they are not. The reason is variables’ scope and assignment precedence .

The assignment operator is right-associative in JavaScript, which means it parses the left-most after parsing the right-most.

Let’s have another example to understand variable scope and assignment precedence .

Focus on the code and see that variable1 , variable2 , and variable3 are in function scope and local to the test1() .

They are not available outside of test1() method that’s why returning undefined . Here, var variable1 = 1, variable2 = 1, varialbe3 = 1; is equivalent to var variable1 = 1; var variable2 = 1; var varialbe3 = 1; .

Now, observe the test2() function. The variable1 is in function scope due to the var keyword, but variable2 and variable3 are leaking because they are not written with the var keyword.

They are globally accessible outside the test2() function. Remember that the variable declarations are hoisted only.

However, the precedence is right-associative which means var variable1 = (window.variable2 =(window.variable3 = 1)); .

Which Means the variable3 will be assigned to 1 first, then the value of variable3 will be allocated to variable2 , and lastly, the value of variable2 will be assigned to variable1 .

To avoid a variable leak in test2() , we can split the variable declaration and assignment into two separate lines. In this way, we can restrict variable1 , variable2 , and variable3 to test2() function scope.

The destructuring assignment helps in assigning multiple variables with the same value without leaking them outside the function.

The fill() method updates all array elements with a static value and returns the modified array. You can read more about fill() here .

Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

Related Article - JavaScript Variable

  • How to Access the Session Variable in JavaScript
  • How to Check Undefined and Null Variable in JavaScript
  • How to Mask Variable Value in JavaScript
  • Why Global Variables Give Undefined Values in JavaScript
  • How to Declare Multiple Variables in a Single Line in JavaScript
  • How to Declare Multiple Variables in JavaScript
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Cheat Sheet
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JS Web Technology

Related Articles

  • Solve Coding Problems
  • JavaScript Display Objects
  • JS 2015 or ECMAScript 6 (ES6)
  • JavaScript Data Types
  • JavaScript Function() Constructor
  • Interesting Facts About Javascript
  • Elegant patterns in JavaScript
  • 7 Loops of JavaScript
  • Uses of JavaScript
  • JavaScript Code Execution
  • ECMAScript 2021 (JS 2021/2022)
  • Garbage Collection in JavaScript
  • JS 2020 - ECMAScript 2020
  • JS 2019 - ECMAScript 2019
  • JS 2018 - ECMAScript 2018
  • Web Components: Building Custom Elements with JavaScript
  • Interactive Data Visualizations in JavaScript
  • JS 2016 or ECMAScript 2016
  • JS 2017 - ECMAScript 2017
  • Understanding variable scopes in JavaScript

JavaScript Variables

JavaScript Variables are the building blocks of any programming language. In JavaScript, variables can be used to store reusable values. The values of the variables are allocated using the assignment operator(“=”).

JavaScript Identifiers

JavaScript variables must have unique names. These names are called Identifiers.

There are some basic rules to declare a variable in JavaScript:

  • These are case-sensitive
  • Can only begin with a letter, underscore(“_”) or “$” symbol
  • It can contain letters, numbers, underscore, or “$” symbol
  • A variable name cannot be a reserved keyword.

JavaScript is a dynamically typed language so the type of variables is decided at runtime. Therefore there is no need to explicitly define the type of a variable. We can declare variables in JavaScript in three ways:

  • JavaScript var keyword
  • JavaScript let keyword
  • JavaScript const keyword  

Note: In JavaScript, variables can be declared automatically.

All three keywords do the basic task of declaring a variable but with some differences Initially, all the variables in JavaScript were written using the var keyword but in ES6 the keywords let and const were introduced.

Example 1: In this example, we will declare variables using var.

Example 2: In this example, we will declare variables using let.

To learn more about JavaScript let check this article JavaScript Let

Example 3: In this example, we will declare the variable using the const keyword.

javascript assignment of variable

Explanation: const keyword is used when we assign a value permanently to a variable. So when we try to change the value of a variable declared with the const keyword it will throw an error. The variables declared with var and let are mutable that is their value can be changed but variables declared using const are immutable. 

To learn more about JavaScript const check this article JavaScript Const

Note: The newly introduced keywords let and const are block scoped whereas var is function scoped. 

Let us see an example to understand the difference:

Example: In this example, we are trying to access the block scoped variables outside the block that’s why we are getting error.

javascript assignment of variable

Explanation: Since variables “a” and “c” are block scoped so we were not able to access them outside their block.

When to Use var, let, or const

  • We declare variables using const if the value should not be changed
  • We use const if the type of the variables should not be changed such as working with Arrays and objects
  • We should use let if not using const

To learn more about the scope of variables refer to this article Understanding variable scopes in JavaScript

Comparison of properties of let, var, and const keywords in JavaScript:

Please Login to comment...

  • javascript-basics
  • Web Technologies
  • Atul_kumar_Shrivastava
  • surinderdawra388
  • amit_singh27
  • meetahaloyx4

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Developing Applications with Oracle Visual Builder
  • Develop Applications
  • Work with JavaScript Action Chains
  • Built-In Actions

Add an Assign Variable Action

You use an Assign Variable action to assign a local, page, flow, or application variable a value. This action can also be used to create a local variable.

For example, if your action chain sends a request to a GET endpoint, you can use the Assign Variable action to map the response to a page variable that's bound to a page component. Or, suppose you want to capture the ID of an item selected in a list. You could use a Selection event to start an action chain that assigns the selected item’s ID to a variable.

To use an Assign Variable action to create a local variable:

  • Enter the variable's name in the Variable field and hit Enter on your keyboard.
  • Use the Type drop-down to select its data type.

Description of jsac-assign-new-local-var.png follows

To use an Assign Variable action for a value assignment:

  • Drag the action from the Actions palette onto the canvas, dropping the action either at the bottom edge of the action it is to follow, or at the top edge of the action it is to precede.
  • Double-click the action in the Actions palette to add it to an empty canvas or to the end of an action chain.
  • On the canvas, select the action you want the new action to follow, then double-click the new action in the Actions palette.

Description of jsac-assign-variables-action.jpg follows

  • To set the variable's value, hover over the far-right side of the Value property and either click the down arrow to choose the value, or click fx to create an expression for the value.

Description of jsac-assign-another-var.png follows

Use Filter Builder to Create Filter Criteria for an SDP

If you're using an SDP to provide a table or list's data, and you'd like to filter out rows, you can use the Assign Variable action to create and assign the filter criteria to the SDP's filterCriterion property. For further details about using an SDP to filter a table or list's rows, see Filter Data by Filter Criteria .

Description of jsac-assign-action-pick-sdp.png follows

To use the Assign Variable action's Filter Builder to create the filter criterion for an SDP:

Description of jsac-assign-action-filter-builder-link.png follows

  • For the first Attribute textbox, enter the name of the column (field in record, like "city") that you want compared against a specific value (like "Tokyo").
  • For the Operator drop-down list, select the operator for the criterion.

Description of jsac-assign-action-filter-builder.png follows

  • Click Done when you're finished.

Filter Builder's Code Editor

You can use the Filter Builder's Code tab to view and edit the filter's code. After defining a condition on the Builder tab, you will see that the Code tab contains an attribute , op and value property.

Here's an example of a filter with two conditions combined by an AND operator:

  • The Oracle JET operator is " $eq " (it must include the dollar sign (“ $ ”)).
  • The attribute property is set to the name of the field (column) that you want to be evaluated against the value property.
  • The value property ( $page.variables.customerListSDP.filterCriterion.criteria[0].value ) is mapped to a page variable ( $page.variables.filterVar ) that holds the value to be evaluated against each field (column) value.
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Logical OR assignment (||=)

The logical OR assignment ( ||= ) operator only evaluates the right operand and assigns to the left if the left operand is falsy .

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 :

Neither would the following trigger the setter:

In fact, if x is not falsy, y is not evaluated at all.

Setting default content

If the "lyrics" element is empty, display a default value:

Here the short-circuit is especially beneficial, since the element will not be updated unnecessarily and won't cause unwanted side-effects such as additional parsing or rendering work, or loss of focus, etc.

Note: Pay attention to the value returned by the API you're checking against. If an empty string is returned (a falsy value), ||= must be used, so that "No lyrics." is displayed instead of a blank space. However, if the API returns null or undefined in case of blank content, ??= should be used instead.

Specifications

Browser compatibility.

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

  • Logical OR ( || )
  • Nullish coalescing operator ( ?? )
  • Bitwise OR assignment ( |= )

IMAGES

  1. Two Ways To Declare Variables In JavaScript

    javascript assignment of variable

  2. Quick Tip: How to Declare Variables in JavaScript

    javascript assignment of variable

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

    javascript assignment of variable

  4. A Simple Explanation of JavaScript Variables: const, let, var

    javascript assignment of variable

  5. Javascript Variable (with Examples)

    javascript assignment of variable

  6. JavaScript Variables

    javascript assignment of variable

VIDEO

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

  2. 06

  3. Javascript assignment operators in 2 minutes (Tagalog)

  4. Javascript for beginner Variable

  5. JavaScript for Beginners

  6. JavaScript

COMMENTS

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

  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. A Guide to Variable Assignment and Mutation in JavaScript

    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: const bears = 3; A common metaphor for...

  4. JavaScript Assignment

    The Simple Assignment Operator assigns a value to a variable. Simple Assignment Examples let x = 10; Try it Yourself » let x = 10 + y; Try it Yourself » The += Operator The Addition Assignment Operator adds a value to a variable. Addition Assignment Examples let x = 10; x += 5; Try it Yourself » let text = "Hello"; text += " World";

  5. Best Way for Conditional Variable Assignment

    javascript - Best Way for Conditional Variable Assignment - Stack Overflow Best Way for Conditional Variable Assignment Ask Question Asked 11 years, 8 months ago Modified 8 months ago Viewed 153k times 65 Which is the better way for conditional variable assignment? 1st method

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

  7. Variables

    A variable is a "named storage" for data. We can use variables to store goodies, visitors, and other data. To create a variable in JavaScript, use the let keyword. The statement below creates (in other words: declares) a variable with the name "message": let message; Now, we can put some data into it by using the assignment operator =:

  8. JavaScript Variables (With Examples)

    In the above example, var msg; is a variable declaration. It does not have any value yet. The default value of variables that do not have any value is undefined. You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it.

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

  10. Expressions and operators

    This expression uses the = operator to assign the value seven to the variable x. The expression itself evaluates to 7. The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7.

  11. JavaScript Operators

    Assignment operators assign values to JavaScript variables. The Addition Assignment Operator (+=) adds a value to a variable. Assignment. let x = 10;

  12. Multiple Variable Assignment in JavaScript

    Use the = Operator to Assign Multiple Variable in JavaScript Multiple Variable Assignment Using Destructuring Assignment With fill () Function in JavaScript This tutorial explains multiple variable assignments in JavaScript because variables are the most important part of our coding.

  13. Javascript How to define multiple variables on a single line?

    javascript multiple variable assignment in one line. 1. Declaring multiple variables on one line in JavaScript. 1. How can I declare and define multiple variables in one statement? Hot Network Questions Animated movie with dragons and a boy and girl from warring factions/kingdoms

  14. JavaScript Variables

    There are some basic rules to declare a variable in JavaScript: These are case-sensitive. Can only begin with a letter, underscore ("_") or "$" symbol. It can contain letters, numbers, underscore, or "$" symbol. A variable name cannot be a reserved keyword. JavaScript is a dynamically typed language so the type of variables is ...

  15. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Try it Syntax js

  16. javascript

    6,697 2 43 49 asked Apr 5, 2010 at 1:49 Michael Mao 9,948 23 76 91 "The following code is definitely not recommended (or event not correct) in Java..." Is it even correct in JavaScript? Because, as far as I can see, you return an integer ( return parseInt (...)) if dayNumber != -1 is true, but a boolean if it is false. - Daniel Kvist

  17. Add an Assign Variable Action

    To set the variable's value, hover over the far-right side of the Value property and either click the down arrow to choose the value, or click fx to create an expression for the value.; If you need to do another assignment, click the + Assign Variable button in the Properties pane: Description of the illustration jsac-assign-another-var.png

  18. variables

    Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;. If the value of any of these variables is 1 after this statement, then logically it must have started from the right, otherwise the value or var1 and var2 would be undefined.

  19. Addition assignment (+=)

    Description x += y is equivalent to x = x + y, except that the expression x is only evaluated once. Examples Using addition assignment js let baz = true; // Boolean + Number -> addition baz += 1; // 2 // Number + Boolean -> addition baz += false; // 2 js

  20. Logical OR assignment (||=)

    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.

  21. Assigning a function to a variable in JavaScript

    Assigning a function to a variable in JavaScript Ask Question Asked 8 years, 8 months ago Modified 8 years, 8 months ago Viewed 2k times 0 function abc () { //multiple variables and functions a:function () {alert ("a")}; } function test () { var k=abc (); k.a (); } In the above case, I have a huge function abc () to be assigned to a variable.

  22. How to assign multiple variables at once in JavaScript?

    5 Answers Sorted by: 65 In ES6 you can do it this way: var [a, b] = ["one", "two"]; The above code is ES6 notation and is called array destructuring/object destructuring (if it's an object). You provide the array on the right-hand side of the expression and you have comma-separated variables surrounded by square brackets on the left-hand side.

  23. javascript

    Typically we assign certain attributes to an element on an HTML page using, label: { text: "Some text" }, name: "someAttributeValue", value: data['someAttributeValue'], and on another page we are referring to that value and displaying it using,

  24. What is the best way to ignore elements in a list assignment?

    Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

  25. UnboundLocalError: local variable 'dest_eröff' referenced before assignment

    dest_dir = "I:\\\\My Drive\\\\Programmieren\\\\Buchführung" if not os.path.exists(dest_dir): os.mkdir(dest_dir) for file_name in os.listdir(dest_dir): if...