Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

Variable reassignment, variable assignment by reference, copying by reference, the spread operator to the rescue, are mutations bad, frequently asked questions (faqs) about javascript variable assignment and mutation.

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

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.

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 :

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.

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.

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!

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.

Darren loves building web apps and coding in JavaScript, Haskell and Ruby. He is the author of Learn to Code using JavaScript , JavaScript: Novice to Ninja and Jump Start Sinatra .He is also the creator of Nanny State , a tiny alternative to React. He can be found on Twitter @daz4126.

SitePoint Premium

Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

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

Introduction to JavaScript assignment operators

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

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

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

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

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

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

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

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

Chaining JavaScript assignment operators

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

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

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

JavaScript Variables – A Beginner's Guide to var, const, and let

Madison Kanna

Variables are a fundamental concept in any programming language. In JavaScript, you can declare variables by using the keywords var, const, or let.

In this article, you’ll learn why we use variables, how to use them, and the differences between const, let and var.

What are variables used for in JavaScript?

In the context of coding, data is information that we use in our computer programs. For example, your Twitter username is a piece of data.

Much of programming is about manipulating or displaying data. In order to do this, programmers need a way of storing and keeping track of data. Let's demonstrate this with an example.

First we’ll open up our JavaScript console. To launch your JavaScript console on Chrome, you can use the shortcut Ctrl + Shift + J on Windows and Linux. For Mac, use Cmd + Option + J.

Once the console has launched, think of your dog or cat’s current age (or any similar number if you don't have pets) and enter it into the console.

Now what if we want to refer to that number again? We’ll have to type it out for a second time.

We need a way to refer to this piece of data so we can reuse it throughout our program.

Introducing variables in JavaScript

A helpful analogy is to think of variables as labels for our values. Think of a container of blueberries with a label on it marked blueberries. In this example, the variable, blueberries , points to a value, which is the blueberries themselves.

Let's declare a variable, age, and use the assignment operator (the equals sign) to assign our value, 4, to this variable. We’ll use the var keyword.

Variables are how programmers give a name to a value so that we can reuse it, update it, or simply keep track of it. Variables can be used to store any JavaScript type.

Now that we’ve assigned this value to the variable age, we can refer back to this value later. If you now type in the variable age in your console, you’ll have the value of 4 returned back to you.

How to use the var keyword in JavaScript

Keywords in JavaScript are reserved words. When you use the var keyword, you’re telling JavaScript you’ll be declaring a variable.

When using the var keyword, variables can be reassigned. We’ll demonstrate this by first declaring a new variable, name, and assigning it to the value of Madison.

Next, we’ll reassign this variable to point to the value of a different name, Ben.

Now if you run console.log(name) you’ll get the output of Ben.

When using the var keyword, variables can also be declared with no initial value.

Here, we’ve declared a variable year but it does not point to any value. Later on if we want it to point to a value, we can use the assignment operator to do so.

Now our variable year will point to the value of 2020.

When JavaScript was first created, the only way to declare a variable was with the var keyword.

In recent updates to JavaScript (ECMAScript2015), const and let were created as other keywords to declared variables.

To explain why they were needed, we’ll look at problems with the var keyword. In order to look at these problems, we’ll learn about what scope is.

What is scope?

Scope refers to where in our code variables are available for use. When a variable is globally scoped , that means it is available anywhere in your program. Let’s look at an example.

Take the following code and enter it into your console.

Here we’ve created and called a function, printName, that will print the value of the name var, Madison . You’ll see this printed in your console.

Because our var was created outside of the function, it is globally scoped. This means that it is available anywhere in your code, including inside of any function. This is why our function, printName, has access to the name var.

Let’s now create a variable that is function-scoped. This means that the variable is only accessible inside the function it was created in. This next example will be very similar to the code above, but with a different placement of the variable.

Now in our console we’ll get an error: year is not defined. This is because the var year is function-scoped. That is, it only exists inside of the function it was created in. We don’t have access to it outside of the function, which is where we’re trying to access it when we run our console.log.

Function-scoped variables are helpful to programmers because we often want to create variables that are only useful or needed inside a certain function. Creating global variables can also lead to errors or mistakes.

Now that we have a basic understanding of scope, we can return to our discussion of problems with the var keyword.

Problems with the var keyword in JavaScript

Let's look at another example.

We'll create a variable, age . Next we’ll write an if statement that checks if age has a value, and if it does, returns a console.log of the number that is double that age.

This is a simplified example, but we’ll first check if age has a value because we want to make sure we are adding to a valid value.

Now in our console, you’ll see Double your current age is 47 .

Our variable, doubleAge , is now a global variable. If you enter doubleAge into your console, you’ll see that you have access to it.

As previously discussed, variables created with the var keyword are function-scoped. Function-scoped variables only exist inside of the function they were created in.

But since the doubleAge variable is not inside a function, that means it has been scoped globally. That is, the doubleAge variable is now available anywhere in our code.

The problem is, doubleAge is just a variable we used once inside of our if statement , and we don’t necessarily need it available everywhere in our code. It has “leaked” outside of the if statement it was created in, even though we didn’t need it to.

It would be great if we had a way of creating a variable that *only* existed inside the if statement it was created in. In other words, the block of code that exists in between the curly brackets.

To help fix this problem, the const and let keywords were introduced in JavaScript.

How to use the const keyword in JavaScript

const works similarly to var, but with a few big differences.

First, const is block -scoped, whereas var is function -scoped.

What is a block ?

A block refers to any space between an opening and closing bracket. This might seem confusing at first. Let's write out our previous example, but this time using const instead of let when declaring our doubleAge variable.

Now, type doubleAge into your console and hit enter. You should get an error, doubleAge is not defined. This is because const is block-scoped: it only exists in the block it was defined.

The   doubleAge variable is ‘trapped’ inside the two curly brackets it was defined in. Code that is also inside those brackets can access doubleAge, but no code outside of it can.

By using const instead of var , our previous problem is fixed. Our doubleAge var is no longer “leaking” into our global scope unnecessarily. Instead, it only exists inside of the block it was created in.

How do block-scoped variables work within the context of functions? To learn about this, let's create and then call a function, returnX.

By calling this function returnX , we can see that our function returns the value of x, which is 1.

If we next type in x , we’ll get back referenceError: x is not defined . This is because functions are also considered blocks, so our const x will exist only within the function.

The next thing to know about const is that it can only ever be declared once. Type this code into your console:

You should see an error,   Identifier 'x' has already been declared.

This is a difference between var and const. While const will give you an error, letting you know that you’ve already declared this variable, the var keyword won’t.

The variable x will point to the value of 2 without an error. This can cause bugs for you as a programmer, as perhaps you did not mean to reassign your value to a new variable. Thus, using const can help you as you’ll receive an error if you accidentally try to reassign a variable.

This is a strength of the const keyword that was introduced as an updated and better way of creating variables in JavaScript. However, what about the times when you do want to update your variable?

Let's look at an example that shows why we would want to do this.

Let's declare a variable, adult , and set it to false . We’ll also create an age variable and set it to 20 .

const adult = false

const age = 20.

Say we want to check a user’s age, and set our adult variable to false if age is over 18. We can write an if statement to do this.

What happens when we run this code?

Here we’ll see Error: Assignment to constant variable.

This is because, in accordance with the rules of const , we cannot redeclare this variable. That is, our variable age is already pointing to the value of true, and we cannot now point it to something else.  

If we print out adult again, we can see that it has stayed the same and still holds the value of false .

We cannot reassign our age variable, and const is working as expected. However, what if we do want to reassign this variable?

Often times programmers will want to be able to redeclare their variables.

This is where our third keyword, let, comes in.

How to use the let keyword in JavaScript

First let’s go over how let is similar to const .

Let , like const , is block-scoped. If you replaced const with let in our above doubleAge example, it would work the same.

However, let differs from const in a fundament way. Variables declared with the let keyword can be redeclared, while variables created with the const keyword cannot. Let’s go over an example.

Using our same example above, replace const with let. We’ll keep our age variable as a const with the value of 20 .

Now if we type out adult , instead of getting an error as we previously did, we’ll see the output of true .

By using the let keyword, we’ve updated our variable to point to the value of true as we wanted to. Sometimes in programming we’ll want to update our variable depending on certain data that we receive. We can use let to do this.

Wrapping up

In summary, we’ve learned that variables are used to keep track of and reuse data in our computer programs. Scope refers to where in our code variables are available for use.

Variables can be declared using var, const, or let. Var is function-scoped, while const and let are block-scoped. Const variables cannot be reassigned, while let variables can be.  

Var, const, and let can be confusing at first. It can help to read different tutorials on them, as well as test out your own code in different ways to solidify your understanding.

Having a strong foundation of var, const, and let will help you not just at the start of your JavaScript career but throughout its entirety.

Thank you for reading!

If you enjoyed this post, sign up for my email list where I send out my latest articles and announce meetings for my coding book club.

If you have feedback or questions on this post, feel free to Tweet me @ madisonkanna.

Read more posts .

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

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

11 Variables and assignment

11.1  let, 11.2.1  const and immutability, 11.2.2  const and loops.

  • 11.3  Deciding between const and let
  • 11.4.1  Shadowing variables
  • 11.5  (Advanced)
  • 11.6.1  Static phenomenon: scopes of variables
  • 11.6.2  Dynamic phenomenon: function calls

11.7.1  globalThis [ES2020]

11.8.1  const and let : temporal dead zone.

  • 11.8.2  Function declarations and early activation
  • 11.8.3  Class declarations are not activated early

11.8.4  var : hoisting (partial early activation)

  • 11.9.1  Bound variables vs. free variables
  • 11.9.2  What is a closure?
  • 11.9.3  Example: A factory for incrementors
  • 11.9.4  Use cases for closures

These are JavaScript’s main ways of declaring variables:

  • let declares mutable variables.
  • const declares constants (immutable variables).

Before ES6, there was also var . But it has several quirks, so it’s best to avoid it in modern JavaScript. You can read more about it in Speaking JavaScript .

Variables declared via let are mutable:

You can also declare and assign at the same time:

11.2  const

Variables declared via const are immutable. You must always initialize immediately:

In JavaScript, const only means that the binding (the association between variable name and variable value) is immutable. The value itself may be mutable, like obj in the following example.

You can use const with for-of loops, where a fresh binding is created for each iteration:

In plain for loops, you must use let , however:

11.3 Deciding between const and let

I recommend the following rules to decide between const and let :

  • const indicates an immutable binding and that a variable never changes its value. Prefer it.
  • let indicates that the value of a variable changes. Use it only when you can’t use const .

exercises/variables-assignment/const_exrc.mjs

11.4 The scope of a variable

The scope of a variable is the region of a program where it can be accessed. Consider the following code.

  • Scope A is the (direct) scope of x .
  • Scopes B and C are inner scopes of scope A.
  • Scope A is an outer scope of scope B and scope C.

Each variable is accessible in its direct scope and all scopes nested within that scope.

The variables declared via const and let are called block-scoped because their scopes are always the innermost surrounding blocks.

11.4.1 Shadowing variables

You can’t declare the same variable twice at the same level:

eval() delays parsing (and therefore the SyntaxError ), until the callback of assert.throws() is executed. If we didn’t use it, we’d already get an error when this code is parsed and assert.throws() wouldn’t even be executed.

You can, however, nest a block and use the same variable name x that you used outside the block:

Inside the block, the inner x is the only accessible variable with that name. The inner x is said to shadow the outer x . Once you leave the block, you can access the old value again.

See quiz app .

11.5 (Advanced)

All remaining sections are advanced.

11.6 Terminology: static vs. dynamic

These two adjectives describe phenomena in programming languages:

  • Static means that something is related to source code and can be determined without executing code.
  • Dynamic means at runtime.

Let’s look at examples for these two terms.

11.6.1 Static phenomenon: scopes of variables

Variable scopes are a static phenomenon. Consider the following code:

x is statically (or lexically ) scoped . That is, its scope is fixed and doesn’t change at runtime.

Variable scopes form a static tree (via static nesting).

11.6.2 Dynamic phenomenon: function calls

Function calls are a dynamic phenomenon. Consider the following code:

Whether or not the function call in line A happens, can only be decided at runtime.

Function calls form a dynamic tree (via dynamic calls).

11.7 Global variables and the global object

JavaScript’s variable scopes are nested. They form a tree:

  • The outermost scope is the root of the tree.
  • The scopes directly contained in that scope are the children of the root.

The root is also called the global scope . In web browsers, the only location where one is directly in that scope is at the top level of a script. The variables of the global scope are called global variables and accessible everywhere. There are two kinds of global variables:

  • They can only be created while at the top level of a script, via const , let , and class declarations.
  • They are created in the top level of a script, via var and function declarations.
  • The global object can be accessed via the global variable globalThis . It can be used to create, read, and delete global object variables.
  • Other than that, global object variables work like normal variables.

The following HTML fragment demonstrates globalThis and the two kinds of global variables.

Each ECMAScript module has its own scope. Therefore, variables that exist at the top level of a module are not global. Fig.  5 illustrates how the various scopes are related.

The global variable globalThis is the new standard way of accessing the global object. It got its name from the fact that it has the same value as this in global scope.

For example, in browsers, there is an indirection . That indirection is normally not noticable, but it is there and can be observed.

11.7.1.1 Alternatives to globalThis

Older ways of accessing the global object depend on the platform:

  • Global variable window : is the classic way of referring to the global object. But it doesn’t work in Node.js and in Web Workers.
  • Global variable self : is available in Web Workers and browsers in general. But it isn’t supported by Node.js.
  • Global variable global : is only available in Node.js.

11.7.1.2 Use cases for globalThis

The global object is now considered a mistake that JavaScript can’t get rid of, due to backward compatibility. It affects performance negatively and is generally confusing.

ECMAScript 6 introduced several features that make it easier to avoid the global object – for example:

  • const , let , and class declarations don’t create global object properties when used in global scope.
  • Each ECMAScript module has its own local scope.

It is usually better to access global object variables via variables and not via properties of globalThis . The former has always worked the same on all JavaScript platforms.

Tutorials on the web occasionally access global variables globVar via window.globVar . But the prefix “ window. ” is not necessary and I recommend to omit it:

Therefore, there are relatively few use cases for globalThis – for example:

  • Polyfills that add new features to old JavaScript engines.
  • Feature detection, to find out what features a JavaScript engine supports.

11.8 Declarations: scope and activation

These are two key aspects of declarations:

  • Scope: Where can a declared entity be seen? This is a static trait.
  • Activation: When can I access an entity? This is a dynamic trait. Some entities can be accessed as soon as we enter their scopes. For others, we have to wait until execution reaches their declarations.

Tbl.  1 summarizes how various declarations handle these aspects.

import is described in §27.5 “ECMAScript modules” . The following sections describe the other constructs in more detail.

For JavaScript, TC39 needed to decide what happens if you access a constant in its direct scope, before its declaration:

Some possible approaches are:

  • The name is resolved in the scope surrounding the current scope.
  • You get undefined .
  • There is an error.

Approach 1 was rejected because there is no precedent in the language for this approach. It would therefore not be intuitive to JavaScript programmers.

Approach 2 was rejected because then x wouldn’t be a constant – it would have different values before and after its declaration.

let uses the same approach 3 as const , so that both work similarly and it’s easy to switch between them.

The time between entering the scope of a variable and executing its declaration is called the temporal dead zone (TDZ) of that variable:

  • During this time, the variable is considered to be uninitialized (as if that were a special value it has).
  • If you access an uninitialized variable, you get a ReferenceError .
  • Once you reach a variable declaration, the variable is set to either the value of the initializer (specified via the assignment symbol) or undefined – if there is no initializer.

The following code illustrates the temporal dead zone:

The next example shows that the temporal dead zone is truly temporal (related to time):

Even though func() is located before the declaration of myVar and uses that variable, we can call func() . But we have to wait until the temporal dead zone of myVar is over.

11.8.2 Function declarations and early activation

In this section, we are using functions – before we had a chance to learn them properly. Hopefully, everything still makes sense. Whenever it doesn’t, please see §25 “Callable values” .

A function declaration is always executed when entering its scope, regardless of where it is located within that scope. That enables you to call a function foo() before it is declared:

The early activation of foo() means that the previous code is equivalent to:

If you declare a function via const or let , then it is not activated early. In the following example, you can only use bar() after its declaration.

11.8.2.1 Calling ahead without early activation

Even if a function g() is not activated early, it can be called by a preceding function f() (in the same scope) if we adhere to the following rule: f() must be invoked after the declaration of g() .

The functions of a module are usually invoked after its complete body is executed. Therefore, in modules, you rarely need to worry about the order of functions.

Lastly, note how early activation automatically keeps the aforementioned rule: when entering a scope, all function declarations are executed first, before any calls are made.

11.8.2.2 A pitfall of early activation

If you rely on early activation to call a function before its declaration, then you need to be careful that it doesn’t access data that isn’t activated early.

The problem goes away if you make the call to funcDecl() after the declaration of MY_STR .

11.8.2.3 The pros and cons of early activation

We have seen that early activation has a pitfall and that you can get most of its benefits without using it. Therefore, it is better to avoid early activation. But I don’t feel strongly about this and, as mentioned before, often use function declarations because I like their syntax.

11.8.3 Class declarations are not activated early

Even though they are similar to function declarations in some ways, class declarations are not activated early:

Why is that? Consider the following class declaration:

The operand of extends is an expression. Therefore, you can do things like this:

Evaluating such an expression must be done at the location where it is mentioned. Anything else would be confusing. That explains why class declarations are not activated early.

var is an older way of declaring variables that predates const and let (which are preferred now). Consider the following var declaration.

This declaration has two parts:

  • Declaration var x : The scope of a var -declared variable is the innermost surrounding function and not the innermost surrounding block, as for most other declarations. Such a variable is already active at the beginning of its scope and initialized with undefined .
  • Assignment x = 123 : The assignment is always executed in place.

The following code demonstrates the effects of var :

11.9 Closures

Before we can explore closures, we need to learn about bound variables and free variables.

11.9.1 Bound variables vs. free variables

Per scope, there is a set of variables that are mentioned. Among these variables we distinguish:

  • Bound variables are declared within the scope. They are parameters and local variables.
  • Free variables are declared externally. They are also called non-local variables .

Consider the following code:

In the body of func() , x and y are bound variables. z is a free variable.

11.9.2 What is a closure?

What is a closure then?

A closure is a function plus a connection to the variables that exist at its “birth place”.

What is the point of keeping this connection? It provides the values for the free variables of the function – for example:

funcFactory returns a closure that is assigned to func . Because func has the connection to the variables at its birth place, it can still access the free variable value when it is called in line A (even though it “escaped” its scope).

Static scoping is supported via closures in JavaScript. Therefore, every function is a closure.

11.9.3 Example: A factory for incrementors

The following function returns incrementors (a name that I just made up). An incrementor is a function that internally stores a number. When it is called, it updates that number by adding the argument to it and returns the new value.

We can see that the function created in line A keeps its internal number in the free variable startValue . This time, we don’t just read from the birth scope, we use it to store data that we change and that persists across function calls.

We can create more storage slots in the birth scope, via local variables:

11.9.4 Use cases for closures

What are closures good for?

For starters, they are simply an implementation of static scoping. As such, they provide context data for callbacks.

They can also be used by functions to store state that persists across function calls. createInc() is an example of that.

And they can provide private data for objects (produced via literals or classes). The details of how that works are explained in Exploring ES6 .

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

JavaScript Variables

  • JavaScript Local Variables
  • JavaScript Global Variables
  • JavaScript var
  • JavaScript Tutorial
  • JavaScript Let
  • How to unset JavaScript variables?
  • Variables in TypeScript
  • JavaScript Strings
  • Variable Shadowing in JavaScript
  • JavaScript Rest parameter
  • Variables and Datatypes in JavaScript
  • What is Variable Scope in JavaScript ?
  • How to pass JavaScript variables to PHP ?
  • Objects in Javascript
  • Uses of JavaScript
  • Global and Local variables in JavaScript
  • ES6 | Variables
  • Javascript Scope
  • JavaScript Set object key by variable

Variables are used to store data in JavaScript. Variables are used to store reusable values. The values of the variables are allocated using the assignment operator(“=”).

Examples of JavaScript Variables

Javascript assignment operator.

JavaScript assignment operator is equal (=) which assigns the value of the right-hand operand to its left-hand operand.

JavaScript Identifiers

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

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.

using const example output

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.

const, var and let example

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 we want mutable value or we can not use const
  • We use var only if we support old browser.

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

Similar reads.

  • javascript-basics
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

Javascript operators are used to perform different types of mathematical and logical computations.

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

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

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Get full access to JavaScript: The Definitive Guide, 6th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Assignment Expressions

JavaScript uses the = operator to assign a value to a variable or property. For example:

The = operator expects its left-side operand to be an lvalue: a variable or object property (or array element). It expects its right-side operand to be an arbitrary value of any type. The value of an assignment expression is the value of the right-side operand. As a side effect, the = operator assigns the value on the right to the variable or property on the left so that future references to the variable or property evaluate to the value.

Although assignment expressions are usually quite simple, you may sometimes see the value of an assignment expression used as part of a larger expression. For example, you can assign and test a value in the same expression with code like this:

If you do this, be sure you are clear on the difference between the = and == operators! Note that = has very low precedence and parentheses are usually necessary when the value of an assignment is to be used in a larger expression.

The assignment operator has right-to-left associativity, which means that when multiple assignment operators appear in an expression, they are evaluated from right to left. Thus, you can write code like this to assign a single value to multiple variables:

Assignment with Operation

Besides the normal = assignment operator, JavaScript supports a number of other assignment operators that provide shortcuts by combining assignment with some other operation. For example, the += operator performs addition and assignment. The following expression:

is equivalent to this one:

As you might expect, the += operator works for numbers or strings. For numeric operands, it performs addition and assignment; for string operands, it performs concatenation and assignment.

Similar operators include -= , *= , &= , and so on. Table 4-3 lists them all.

Table 4-3. Assignment operators

In most cases, the expression:

where op is an operator, is equivalent to the expression:

In the first line, the expression a is evaluated once. In the second it is evaluated twice. The two cases will differ only if a includes side effects such as a function call or an increment operator. The following two assignments, for example, are not the same:

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Destructuring assignment

The two most used data structures in JavaScript are Object and Array .

  • Objects allow us to create a single entity that stores data items by key.
  • Arrays allow us to gather data items into an ordered list.

However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.

Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.

Array destructuring

Here’s an example of how an array is destructured into variables:

Now we can work with variables instead of array members.

It looks great when combined with split or other array-returning methods:

As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.

It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.

It’s just a shorter way to write:

Unwanted elements of the array can also be thrown away via an extra comma:

In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).

…Actually, we can use it with any iterable, not only arrays:

That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.

We can use any “assignables” on the left side.

For instance, an object property:

In the previous chapter, we saw the Object.entries(obj) method.

We can use it with destructuring to loop over the keys-and-values of an object:

The similar code for a Map is simpler, as it’s iterable:

There’s a well-known trick for swapping values of two variables using a destructuring assignment:

Here we create a temporary array of two variables and immediately destructure it in swapped order.

We can swap more than two variables this way.

The rest ‘…’

Usually, if the array is longer than the list at the left, the “extra” items are omitted.

For example, here only two items are taken, and the rest is just ignored:

If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.

Default values

If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:

If we want a “default” value to replace the missing one, we can provide it using = :

Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.

For instance, here we use the prompt function for two defaults:

Please note: the prompt will run only for the missing value ( surname ).

Object destructuring

The destructuring assignment also works with objects.

The basic syntax is:

We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .

For instance:

Properties options.title , options.width and options.height are assigned to the corresponding variables.

The order does not matter. This works too:

The pattern on the left side may be more complex and specify the mapping between properties and variables.

If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:

The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.

For potentially missing properties we can set default values using "=" , like this:

Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.

In the code below prompt asks for width , but not for title :

We also can combine both the colon and equality:

If we have a complex object with many properties, we can extract only what we need:

The rest pattern “…”

What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?

We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.

It looks like this:

In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.

This won’t work:

The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:

So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.

To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :

Nested destructuring

If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.

In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:

All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:

Finally, we have width , height , item1 , item2 and title from the default value.

Note that there are no variables for size and items , as we take their content instead.

Smart function parameters

There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.

Here’s a bad way to write such a function:

In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.

That’s ugly. And becomes unreadable when we deal with more parameters.

Destructuring comes to the rescue!

We can pass parameters as an object, and the function immediately destructurizes them into variables:

We can also use more complex destructuring with nested objects and colon mappings:

The full syntax is the same as for a destructuring assignment:

Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.

Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:

We can fix this by making {} the default value for the whole object of parameters:

In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.

Destructuring assignment allows for instantly mapping an object or array onto many variables.

The full object syntax:

This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.

Object properties that have no mapping are copied to the rest object.

The full array syntax:

The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .

It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.

We have an object:

Write the destructuring assignment that reads:

  • name property into the variable name .
  • years property into the variable age .
  • isAdmin property into the variable isAdmin (false, if no such property)

Here’s an example of the values after your assignment:

The maximal salary

There is a salaries object:

Create the function topSalary(salaries) that returns the name of the top-paid person.

  • If salaries is empty, it should return null .
  • If there are multiple top-paid persons, return any of them.

P.S. Use Object.entries and destructuring to iterate over key/value pairs.

Open a sandbox with tests.

Open the solution with tests in a sandbox.

  • 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
  • United States
  • United Kingdom

User-defined variables in JavaScript

Javascript variables hold a wide variety of information and can be used with virtually any data type. here's how to use variables to store numbers, text strings, objects, and more..

Matthew Tyson

Contributor, |

User-defined variables in JavaScript

Without variables, programming languages are next to useless. Fortunately, JavaScript's variable system is incredibly powerful and versatile. This article shows you how to use JavaScript variables to store numbers, text strings, objects, and other data types. Once you've stored this information, you can use it anywhere in your program.

All about JavaScript variables

Here's what you'll learn in this article:

What is a user-defined variable in JavaScript?

Data types in javascript variables, how to create javascript variables, how to store data types in javascript variables, tips for naming javascript variables, dynamic typing and javascript variables.

  • How to work with string variables

What you need to know about variable scope

All JavaScript programming happens in an environment like a web browser, Node, or Bun.js. Each of these environments has its own set of pre-defined variables like window and console . These variables are not user-defined because they are set by the environment. Another kind of variable is the user-defined variable defined by other developers, such as in third-party frameworks or libraries you use. Then there are variables you create while writing your programs, using the let and const keywords. These are defined by you, the user. This article is about how to create your own user-defined variables.

Variables hold a wide variety of information temporarily. The JavaScript data types that can be stored in a variable include:

  • Numeric values, or "numbers": Variables hold numbers, which can be used in simple or complex mathematical computations. Example: 2 + 2 = 4.
  • Character strings: A string is a collection of text, such as "JavaScript" or "My name is Mudd."
  • True/False values: The Boolean data type, which has only values of true or false.
  • Objects: Variables can hold JavaScript objects or user-defined objects.

JavaScript variables can hold a few other kinds of data, but these are by far the most commonly used types.

Several JavaScript instructions are used to create variables, but the most basic way to create a variable manually is with the equals ( = ) assignment operator:

The first argument is the name of the variable. Variable names can be very long, but there are restrictions on the characters you can use. We'll discuss these in detail soon.

In practice, variables should be declared using either the let or const statements:

Both let and const restrict the visibility of the variable to the current code block. The const statement creates a “constant” variable, which cannot be changed. When possible, use const for cleaner code.

The second argument is the variable's content. You can put all sorts of data into a variable, including a number, a string, a math expression (such as 2 + 2), and various other things. In JavaScript, variables are dynamically typed, so the same variable can hold any kind of data.

Let's take a look at how to store the most common data types in JavaScript variables.

Storing numbers in JavaScript variables

A number is one or more digits stored in the computer in such a way that JavaScript can perform mathematical calculations with them. JavaScript supports both integers and floating-point values. To place a number in a variable, just provide the variable name, the equals sign ( aka the variable assignment operator), and the value you want to use. For example, the following code places the number 10 in a variable named myVar :

JavaScript makes it easy to deal with numbers. You can freely mix and match floats. For example, myVar = 10 * .3 is okay.

Storing strings in JavaScript variables

A string is one or more text characters arranged in memory in a single-file fashion. Strings can contain numbers (digits), letters, punctuation, or a combination of these. You cannot perform math calculations on strings (it will return NaN if you try, for Not a Number). Strings are assigned to JavaScript variables by being enclosed in a set of quotes, which can be single or double:

Unlike some languages, JavaScript makes no distinction between the two forms of quotation marks. Here is an example of how to place a string into a variable:

Storing Boolean values in JavaScript variables

There are only two Boolean values: true or false. Some programming languages don't have a separate set of Boolean values; instead, they use 0 for false, and 1 or -1 (or any other non-zero value) for true. JavaScript lets you use these numbers to represent true and false but, in addition, reserves the words true and false to refer to the Boolean true and false values.

You can think of the Boolean true/false values as being equivalent to on/off or yes/no. To assign a Boolean value to a variable, enter the word true or false without quotes. Here's an example:

JavaScript “coerces” variables to Boolean when testing to true/false. Additionally, a variety of “falsy” and “truthy” variables exist in this vein. We’ve mentioned 0 and 1, which naturally map to false and true. In fact, any number other than 0 is coerced to true. Another coerced value is the empty string (false) and a string holding a value (true):

Another common use is to establish the falseness of undefined and null :

Storing objects in JavaScript variables

Variables can contain objects , which are containers for other values and are incredibly useful in many scenarios. There are two kinds of object variables in JavaScript:

  • Variables that contain built-in browser-related objects—window, document, and so on. These are references to objects you did not create. They are like copies, but the copies change if the original changes. In some cases, changing the object in the variable affects the original JavaScript object.
  • Variables that contain user-defined objects represent the actual object. A change to the object in the variable changes only that object.

To assign a JavaScript object to a variable, provide the name of the object, as in:

To assign a new copy of a user-defined object to a variable, use the new statement and provide the name of the object function:

Or, you could use an object literal:

JavaScript offers a great deal of latitude when it comes to naming variables. JavaScript variable names can be almost unlimited in length, although for practical reasons you'll probably want to keep your variable names under 10 or 15 characters. Shorter variable names are easier to type and remember.

Here are more tips to keep in mind when naming your variables:

  • Variable names should consist of letters only, without spaces. You can use numbers as long as the name doesn't start with a digit. For example, myVar1 is okay but 1MyVar is not.
  • Don't use punctuation characters in variable names, with one xception: the underscore character ( _ ). So, the variable my_Var is okay, but my*Var is not. Variables can begin with the underscore character.
  • Variable names are case sensitive. The variable MyVar is considered not the same variable as myVar , myVar , and other variations.
  • It is conventional to use camelCase for JavaScript variable names, for example:  thisIsMyVariable .
  • Avoid obscure abbreviations. An abbreviation like msg is okay because most people know it is short for "message." Less common abbreviations should be avoided.

Unlike some other programming languages, JavaScript does not require you to explicitly define the type of variable you want to create. This JavaScript behavior is sometimes called loose data typing , more formally known as dynamic or weak typing. JavaScript's loose data typing differs from C and Java, which both use strict data typing.

What this means is that in JavaScript, you don't need to declare a variable type. JavaScript will happily use the same variable for numbers, strings, and objects. (Part of TypeScript's power is that it adds a strongly typed layer on top of JavaScript .) 

Assigning variables with let and const

Good JavaScript uses the let and const keywords to declare variables. Here's an example:

You'll still see var in some older code. If possible, refactor it to use let . (Though doing that is sometimes not straightforward if the variable is used as a global.) You’ll also see variables declared without a keyword declaration—for instance, myVar = “foo” . That’s just bad style!

You can also use the let statement with a variable name to declare the variable but not define a value for it:

In this case, you've defined myVar in memory but have yet to assign a value to it. Later, you will be able to use the variable.

Working with string variable limits

String variable limits were once a common problem in front-end JavaScript. These days, the limit on how long a JavaScript string variable can be is dependent on the engine you are running in—whether it be Chrome, Edge, Node, Bun, etc. In general, you won’t run into problems with string variable limits.

You can create longer strings by "piecing" them together. After assigning a string to each variable, you combine them using the plus ( + ) character. This is called concatenation . The following example shows how concatenation works:

You can also use interpolation , which makes it easier to incorporate variables into a string:

The scope of a variable has nothing to do with optics or mouthwash, but rather the extent to which a variable is visible to other parts of a JavaScript program. In the old days, var would hoist a variable to the top of the scope. In modern JavaScript, let and const behave more in line with other languages, keeping the variable within the current code block. The current block is encompassed by curly braces, as shown here:

In this example, the console will output “bar”.  The foo defined inside the if block is held within that block. Global variables are a common source of logic errors, so keeping a variable in the smallest scope is always good practice.

Although variables are a fairly simple aspect of JavaScript, they are also universal and essential. Knowing how to work with them is like mastering the basic moves of a martial art: practice pays off. You never really leave the basics behind; you just get better at making them work for you.

Next read this:

  • Why companies are leaving the cloud
  • 5 easy ways to run an LLM locally
  • Coding with AI: Tips and best practices from developers
  • Meet Zig: The modern alternative to C
  • What is generative AI? Artificial intelligence that creates
  • The best open source software of 2023
  • Software Development
  • Programming Languages

Matthew Tyson is a founder of Dark Horse Group, Inc. He believes in people-first technology. When not playing guitar, Matt explores the backcountry and the philosophical hinterlands. He has written for JavaWorld and InfoWorld since 2007.

Copyright © 2024 IDG Communications, Inc.

variable assignment js

Change the hostname of your AL2 instance

When you launch an instance into a private VPC, Amazon EC2 assigns a guest OS hostname. The type of hostname that Amazon EC2 assigns depends on your subnet settings. For more information about EC2 hostnames, see Amazon EC2 instance hostname types in the Amazon EC2 User Guide for Linux Instances .

A typical Amazon EC2 private DNS name for an EC2 instance configured to use IP-based naming with an IPv4 address looks something like this: ip-12-34-56-78.us-west-2.compute.internal , where the name consists of the internal domain, the service (in this case, compute ), the region, and a form of the private IPv4 address. Part of this hostname is displayed at the shell prompt when you log into your instance (for example, ip-12-34-56-78 ). Each time you stop and restart your Amazon EC2 instance (unless you are using an Elastic IP address), the public IPv4 address changes, and so does your public DNS name, system hostname, and shell prompt.

This information applies to Amazon Linux. For information about other distributions, see their specific documentation.

Change the system hostname

If you have a public DNS name registered for the IP address of your instance (such as webserver.mydomain.com ), you can set the system hostname so your instance identifies itself as a part of that domain. This also changes the shell prompt so that it displays the first portion of this name instead of the hostname supplied by AWS (for example, ip-12-34-56-78 ). If you do not have a public DNS name registered, you can still change the hostname, but the process is a little different.

In order for your hostname update to persist, you must verify that the preserve_hostname cloud-init setting is set to true . You can run the following command to edit or add this setting:

If the preserve_hostname setting is not listed, add the following line of text to the end of the file:

To change the system hostname to a public DNS name

Follow this procedure if you already have a public DNS name registered.

For AL2: Use the hostnamectl command to set your hostname to reflect the fully qualified domain name (such as webserver.mydomain.com ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the fully qualified domain name (such as webserver.mydomain.com ).

Reboot the instance to pick up the new hostname.

Alternatively, you can reboot using the Amazon EC2 console (on the Instances page, select the instance and choose Instance state , Reboot instance ).

Log into your instance and verify that the hostname has been updated. Your prompt should show the new hostname (up to the first ".") and the hostname command should show the fully-qualified domain name.

To change the system hostname without a public DNS name

For AL2: Use the hostnamectl command to set your hostname to reflect the desired system hostname (such as webserver ).

For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect the desired system hostname (such as webserver ).

Open the /etc/hosts file in your favorite text editor and change the entry beginning with 127.0.0.1 to match the example below, substituting your own hostname.

You can also implement more programmatic solutions, such as specifying user data to configure your instance. If your instance is part of an Auto Scaling group, you can use lifecycle hooks to define user data. For more information, see Run commands on your Linux instance at launch and Lifecycle hook for instance launch in the AWS CloudFormation User Guide .

Change the shell prompt without affecting the hostname

If you do not want to modify the hostname for your instance, but you would like to have a more useful system name (such as webserver ) displayed than the private name supplied by AWS (for example, ip-12-34-56-78 ), you can edit the shell prompt configuration files to display your system nickname instead of the hostname.

To change the shell prompt to a host nickname

Create a file in /etc/profile.d that sets the environment variable called NICKNAME to the value you want in the shell prompt. For example, to set the system nickname to webserver , run the following command.

Open the /etc/bashrc (Red Hat) or /etc/bash.bashrc (Debian/Ubuntu) file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/bashrc and /etc/bash.bashrc are owned by root .

Edit the file and change the shell prompt variable ( PS1 ) to display your nickname instead of the hostname. Find the following line that sets the shell prompt in /etc/bashrc or /etc/bash.bashrc (several surrounding lines are shown below for context; look for the line that starts with [ "$PS1" ):

Change the \h (the symbol for hostname ) in that line to the value of the NICKNAME variable.

(Optional) To set the title on shell windows to the new nickname, complete the following steps.

Create a file named /etc/sysconfig/bash-prompt-xterm .

Make the file executable using the following command.

Open the /etc/sysconfig/bash-prompt-xterm file in your favorite text editor (such as vim or nano ). You need to use sudo with the editor command because /etc/sysconfig/bash-prompt-xterm is owned by root .

Add the following line to the file.

Log out and then log back in to pick up the new nickname value.

Change the hostname on other Linux distributions

The procedures on this page are intended for use with Amazon Linux only. For more information about other Linux distributions, see their specific documentation and the following articles:

How do I assign a static hostname to a private Amazon EC2 instance running RHEL 7 or Centos 7?

Warning

To use the Amazon Web Services Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions.

Thanks for letting us know we're doing a good job!

If you've got a moment, please tell us what we did right so we can do more of it.

Thanks for letting us know this page needs work. We're sorry we let you down.

If you've got a moment, please tell us how we can make the documentation better.

  • Using Project Execution Management

Variable Hours Assignment for Resource Requests

If you don't need the resource to work on the project full-time, you can request or assign one or more resources for variable hours on a project.

You can assign the resource to work various hours some or all days of the week (including non-working days) or request for number of hours per week with flexible days to meet the schedule requirements. This helps you schedule resources better.

Specify variable hours in the requested hours to create or update a resource request, assign resources for weekly pattern that's repeated for the duration of the assignment or the request. You can also adjust resource assignment schedule to add variable hours or weekly hours.

If you request for a particular number of hours per week, the resource managers can review available capacity based on the resource's total weekly hours available. For example, if a request is for 25 hours each week, they can assign any resource that has 25 hours of remaining capacity for each week to fulfill the request.

Available capacity calculation is based on the requested hours. If the request is for weekly hours, the available capacity is based on the total remaining available hours a resource has each week of the requested duration. If the requested hours specifies using the project calendar hours, hours per day, or variable hours, the available capacity is based on the resource's available hours each day of the requested duration.

If you want to update the requests or assignments in group, you could adjust the hours by calendar or by working days in case the hours of the variable hours fall on non-working days.

Consider these examples:

Within a single assignment, a resource may work Mondays and Tuesdays for 8 hours each day, Thursdays and Fridays for 4 hours each day and not work any hours on Wednesdays. A project manager can request for such a resource assignment.

A project needs a system administrator to work once each week on Tuesday or Thursday to handle weekly builds. The project manager requests a resource for Thursdays 4 hours per day for the duration of the project. The resource manager adjusts the daily hours to Tuesday and assigns the resource.

A project manager raises a request for a DBA analyst for 5 hours every week. The resource manager knows that there is a flexibility of days and assigns resource whose availability score is at least 5 hours every week.

A resource manager created several assignments for a project where the work is scheduled to start on a Saturday, which is a non-working day on the project calendar. The project gets delayed by two weeks. To adjust these assignments, she can select all the impacted assignments on the Change Assignment Schedule page and adjust the start and finish dates by 14 calendar days to ensure the assignments start on the Saturday again but 2 weeks later than originally planned.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Object.assign()

The Object.assign() static method copies all enumerable own properties from one or more source objects to a target object . It returns the modified target object.

The target object — what to apply the sources' properties to, which is returned after it is modified.

The source object(s) — objects containing the properties you want to apply.

Return value

The target object.

Description

Properties in the target object are overwritten by properties in the sources if they have the same key . Later sources' properties overwrite earlier ones.

The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters . Therefore it assigns properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.

For copying property definitions (including their enumerability) into prototypes, use Object.getOwnPropertyDescriptor() and Object.defineProperty() instead.

Both String and Symbol properties are copied.

In case of an error, for example if a property is non-writable, a TypeError is raised, and the target object is changed if any properties are added before the error is raised.

Note: Object.assign() does not throw on null or undefined sources.

Cloning an object

Warning for deep clone.

For deep cloning , we need to use alternatives like structuredClone() , because Object.assign() copies property values.

If the source value is a reference to an object, it only copies the reference value.

Merging objects

Merging objects with same properties.

The properties are overwritten by other objects that have the same properties later in the parameters order.

Copying symbol-typed properties

Properties on the prototype chain and non-enumerable properties cannot be copied, primitives will be wrapped to objects, exceptions will interrupt the ongoing copying task, copying accessors, specifications, browser compatibility.

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

  • Polyfill of Object.assign in core-js
  • Object.defineProperties()
  • Enumerability and ownership of properties
  • Spread in object literals

COMMENTS

  1. 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. ... JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

  2. JavaScript Assignment

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

  3. JavaScript Variables

    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). ... To assign a value to the variable, use the equal sign: carName = "Volvo"; You can also assign a value to the variable when you declare it:

  4. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

  5. A Guide to 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 ...

  6. Storing the information you need

    Declaring a variable. To use a variable, you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword let followed by the name you want to call your variable: js. let myName; let myAge; Here we're creating two variables called myName and myAge.

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

  8. 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 =:

  9. JavaScript Variables

    Let's declare a variable, age, and use the assignment operator (the equals sign) to assign our value, 4, to this variable. We'll use the var keyword. var age = 4. Variables are how programmers give a name to a value so that we can reuse it, update it, or simply keep track of it. Variables can be used to store any JavaScript type.

  10. Expressions and operators

    Evaluation example 1. y = x = f() is equivalent to y = (x = f()), because the assignment operator = is right-associative.However, it evaluates from left to right: The assignment expression y = x = f() starts to evaluate.. The y on this assignment's left-hand side evaluates into a reference to the variable named y.; The assignment expression x = f() starts to evaluate.

  11. 11 Variables and assignment

    11 Variables and assignment. ... JavaScript's variable scopes are nested. They form a tree: The outermost scope is the root of the tree. The scopes directly contained in that scope are the children of the root. And so on. The root is also called the global scope. In web browsers, the only location where one is directly in that scope is at the ...

  12. JavaScript Variables

    Variables are used to store reusable values. The values of the variables are allocated using the assignment operator("="). Examples of JavaScript Variables JavaScript Assignment Operator. JavaScript assignment operator is equal (=) which assigns the value of the right-hand operand to its left-hand operand.

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

  14. Assignment Expressions

    Assignment Expressions. JavaScript uses the = operator to assign a value to a variable or property. For example: i = 0 // Set the variable i to 0. o.x = 1 // Set the property x of object o to 1. The = operator expects its left-side operand to be an lvalue: a variable or object property (or array element).

  15. var

    For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are scoped to the current function. Only a variable's declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached.

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

  17. Logical OR assignment (||=)

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

  18. Destructuring assignment

    It's called "destructuring assignment," because it "destructurizes" by copying items into variables. However, the array itself is not modified. It's just a shorter way to write: // let [firstName, surname] = arr; let firstName = arr [0]; let surname = arr [1]; Ignore elements using commas.

  19. User-defined variables in JavaScript

    To assign a JavaScript object to a variable, provide the name of the object, as in: myVar = window;; To assign a new copy of a user-defined object to a variable, use the new statement and provide ...

  20. Change the hostname of your AL2 instance

    For AL2: Use the hostnamectl command to set your hostname to reflect the desired system hostname (such as webserver ). [ec2-user ~]$ sudo hostnamectl set-hostname webserver.localdomain. For Amazon Linux AMI: On your instance, open the /etc/sysconfig/network configuration file in your favorite text editor and change the HOSTNAME entry to reflect ...

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

    If you aren't absolutely married to the idea of the values being at the end of the statement, this works: var a = "one", b = "two"; If you want to assign to variables that have already been declared, you can use the comma operator to make it a one-liner. a = "ONE", b = "TWO"; answered May 13, 2022 at 13:36. Ryan.

  22. Variable Hours Assignment for Resource Requests

    Specify variable hours in the requested hours to create or update a resource request, assign resources for weekly pattern that's repeated for the duration of the assignment or the request. You can also adjust resource assignment schedule to add variable hours or weekly hours. Note: You can update a resource request in Open status only.

  23. Object.assign()

    Later sources' properties overwrite earlier ones. The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

  24. javascript

    0. Yes, you just have to give an id to the input, for instance "id = my_input_id"; Then, in the javascript, just write : $("my_input_id").value=totalPopulation; That's how ajax works: find html elements ids and fill them dinamically using javascript values. Just be carefull that the html in read before the JS.