JS Tutorial

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

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

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

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

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

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

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

Right Shift Assignment Example

The >>>= operator.

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

Unsigned Right Shift Assignment Example

The &= operator.

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

Bitwise AND Assignment Example

The |= operator.

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

Bitwise OR Assignment Example

The ^= operator.

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

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

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

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

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

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

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

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

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

[email protected]

Top Tutorials

Top references, top examples, get certified.

A Guide to Variable Assignment and Mutation in JavaScript

Darren Jones

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

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

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

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

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

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

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

Variable Assignment

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

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

variables like a box

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

variables like a reference

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

variables referencing the same value

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

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

Some gotchas when working with objects

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

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

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

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

variables referencing different objects

Variable Reassignment

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

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

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

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

Variable reassignment using let

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

variables referencing different values

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

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

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

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

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

Variable Assignment by Reference

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

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

variables cannot reference another variable

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

variables referencing values

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

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

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

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

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

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

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

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

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

Mutability and objects in JavaScript

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

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

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

Copying by Reference

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

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

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

variables referencing the same object

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

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

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

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

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

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

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

The Spread Operator to the Rescue!

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

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

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

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

variables referencing different objects

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

Changes don't affect the other object

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

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

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

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

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

Are Mutations Bad?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

How can I prevent mutation in JavaScript?

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

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

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

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

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

What is the MutationObserver API in JavaScript?

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

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

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

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

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

A real-life analogy

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

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

We can put any value in the box.

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

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

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

A variable should be declared only once.

A repeated declaration of the same variable is an error:

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

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

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

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

Variable naming

There are two limitations on variable names in JavaScript:

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

Examples of valid names:

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

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

These names are valid:

Examples of incorrect variable names:

Variables named apple and APPLE are two different variables.

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

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

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

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

The code below gives a syntax error:

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

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

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

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

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

Uppercase constants

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

Such constants are named using capital letters and underscores.

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

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

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

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

For instance:

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

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

Name things right

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

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

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

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

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

Some good-to-follow rules are:

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

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

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

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

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

An extra variable is good, not evil.

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

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

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

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

Working with variables

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

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

Giving the right name

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

The variable for our planet

That’s simple:

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

The name of the current visitor

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

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

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

Uppercase const?

Examine the following code:

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

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

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

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

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

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

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

Lesson navigation

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

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

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 .

Popular Tutorials

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

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

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope

JavaScript Hoisting

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

Exceptions and Modules

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

JavaScript Asynchronous

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

Miscellaneous

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

JavaScript Tutorials

JavaScript let Vs var

JavaScript Variable Scope

JavaScript Keywords and Identifiers

  • JavaScript Data Types
  • JavaScript console.log()

JavaScript Variables and Constants

  • JavaScript Variables

In programming, a variable is a container (storage area) to hold data. For example,

Here, num is a variable. It's storing 5 .

  • JavaScript Declare Variables

In JavaScript, we use either var or let keyword to declare variables. For example,

Here, x and y are variables.

  • JavaScript var Vs let

Both var and let are used to declare variables. However, there are some differences between them.

Note: It is recommended we use let instead of var . However, there are a few browsers that do not support let . Visit JavaScript let browser support to learn more.

  • JavaScript Initialize Variables

We use the assignment operator = to assign a value to a variable.

Here, 5 is assigned to variable x .

You can also initialize variables during its declaration.

In JavaScript, it's possible to declare variables in a single statement.

If you use a variable without initializing it, it will have an undefined value.

Here x is the variable name and since it does not contain any value, it will be undefined.

You will learn about undefined and other data types in the next tutorial in detail.

  • Change the Value of Variables

It's possible to change the value stored in the variable. For example,

The value of a variable may vary . Hence, the name variable .

  • Rules for Naming JavaScript Variables

The rules for naming variables are:

  • Variable names must start with either a letter, an underscore _ , or the dollar sign $ . For example, //valid let a = 'hello'; let _a = 'hello'; let $a = 'hello';
  • Variable names cannot start with numbers. For example, //invalid Let 1a = 'hello'; // this gives an error
  • JavaScript is case-sensitive. So y and Y are different variables. For example, let y = "hi"; let Y = 5; console.log(y); // hi console.log(Y); // 5
  • Keywords cannot be used as variable names. For example, //invalid let new = 5; // Error! new is a keyword.
  • Though you can name variables in any way you want, it's a good practice to give a descriptive variable name. If you are using a variable to store the number of apples, it better to use apples or numberOfApples rather than x or n .
  • In JavaScript, the variable names are generally written in camelCase if it has multiple words. For example, firstName , annualSalary , etc.
  • JavaScript Constants

The const keyword was also introduced in the ES6(ES2015) version to create constants. For example,

Once a constant is initialized, we cannot change its value.

Simply, a constant is a type of variable whose value cannot be changed.

Also, you cannot declare a constant without initializing it. For example,

Note: If you are sure that the value of a variable won't change throughout the program, it's recommended to use const . However, there are a few browsers that do not support const . Visit JavaScript const browser support to learn more.

Table of Contents

Video: javascript variables.

Sorry about that.

Related Tutorials

JavaScript Tutorial

Home » JavaScript Tutorial » JavaScript Variables

JavaScript Variables

Summary : in this tutorial, you’ll learn about JavaScript variables and how to use variables to store values in the application.

A variable is a label that references a value like a number or string. Before using a variable, you need to declare it.

Declare a variable

To declare a variable, you use the var keyword followed by the variable name as follows:

A variable name can be any valid identifier. By default, the message variable has a special value undefined if you have not assigned a value to it.

Variable names follow these rules:

  • Variable names are case-sensitive. This means that the message and Message are different variables.
  • Variable names can only contain letters, numbers, underscores, or dollar signs and cannot contain spaces. Also, variable names must begin with a letter, an underscore ( _ ) or a dollar sign ( $) .
  • Variable names cannot use the reserved words.

By convention, variable names use camelcase like message , yourAge , and myName .

JavaScript is a dynamically typed language. This means that you don’t need to specify the variable’s type in the declaration like other static-typed languages such as Java or C# .

Starting in ES6, you can use the let keyword to declare a variable like this:

It’s a good practice to use the let keyword to declare a variable. Later, you’ll learn the differences between var and let keywords . And you should not worry about it for now.

Initialize a variable

Once you have declared a variable, you can initialize it with a value. To initialize a variable, you specify the variable name, followed by an equals sign ( = ) and a value.

For example, The following declares the message variable and initializes it with a literal string "Hello" :

To declare and initialize a variable at the same time, you use the following syntax:

For example, the following statement declares the message variable and initializes it with the literal string "Hello" :

JavaScript allows you to declare two or more variables using a single statement. To separate two variable declarations, you use a comma ( , ) like this:

Since JavaScript is a dynamically typed language, you can assign a value of a different type to a variable. Although, it is not recommended. For example:

Change a variable

Once you initialize a variable, you can change its value by assigning a different value. For example:

Undefined vs. undeclared variables

It’s important to distinguish between undefined and undeclared variables.

An undefined variable is a variable that has been declared but has not been initialized with a value. For example:

In this example, the message variable is declared but not initialized. Therefore, the message variable is undefined.

In contrast, an undeclared variable is a variable that has not been declared. For example:

In this example, the counter variable has not been declared. Hence, accessing it causes a ReferenceError .

A constant holds a value that doesn’t change. To declare a constant, you use the const keyword. When defining a constant, you need to initialize it with a value. For example:

Once you define a constant, you cannot change its value.

The following example attempts to change the value of the workday constant to 4 and causes an error:

Later, you’ll learn that the const keyword actually defines a read-only reference to a value in the constants tutorial.

  • A variable is a label that references a value.
  • Use the let keyword to declare a variable.
  • An undefined variable is a variable that has been declared but not initialized while an undeclared variable is a variable that has not been declared.
  • Use the const keyword to define a readonly reference to a value.
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Cheat Sheet
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JS Web Technology

Related Articles

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

JavaScript Variables

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

JavaScript Identifiers

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

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

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

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

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

Note: In JavaScript, variables can be declared automatically.

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

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

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

To learn more about JavaScript let check this article JavaScript Let

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

variable assignment javascript

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.

variable assignment javascript

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

When to Use var, let, or const

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

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

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

Please Login to comment...

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

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

variable assignment javascript

Multiple Variable Assignment in JavaScript

  • JavaScript Howtos
  • Multiple Variable Assignment in …

Use the = Operator to Assign Multiple Variable in JavaScript

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

Multiple Variable Assignment in JavaScript

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Mehvish Ashiq avatar

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

Related Article - JavaScript Variable

  • How to Access the Session Variable in JavaScript
  • How to Check Undefined and Null Variable in JavaScript
  • How to Mask Variable Value in JavaScript
  • Why Global Variables Give Undefined Values in JavaScript
  • How to Declare Multiple Variables in a Single Line in JavaScript
  • How to Declare Multiple Variables in JavaScript
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Logical OR assignment (||=)

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

Description

Logical OR assignment short-circuits , meaning that x ||= y is equivalent to x || (x = y) , except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

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

Setting default content

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

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

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

Specifications

Browser compatibility.

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

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

variable assignment javascript

Announcing TypeScript 5.4 RC

variable assignment javascript

Daniel Rosenwasser

February 22nd, 2024 2 0

Today we’re excited to announce our Release Candidate of TypeScript 5.4! Between now and the stable release of TypeScript 5.4, we expect no further changes apart from critical bug fixes.

To get started using the RC, you can get it through NuGet , or through npm with the following command:

Here’s a quick list of what’s new in TypeScript 5.4!

Preserved Narrowing in Closures Following Last Assignments

The noinfer utility type, object.groupby and map.groupby, support for require() calls in --moduleresolution bundler and --module preserve, checked import attributes and assertions, quick fix for adding missing parameters.

  • Upcoming 5.5 Deprecations

Notable Behavioral Changes

What’s new since the beta.

Since the beta, we’ve updated the release notes to document new notable behavioral changes , including restrictions around enum compatibility, restrictions on enum member naming, and improvements in mapped type behavior.

TypeScript can usually figure out a more specific type for a variable based on checks that you might perform. This process is called narrowing.

One common pain-point was that these narrowed types weren’t always preserved within function closures.

Here, TypeScript decided that it wasn’t "safe" to assume that url was actually a URL object in our callback function because it was mutated elsewhere; however, in this instance, that arrow function is always created after that assignment to url , and it’s also the last assignment to url .

TypeScript 5.4 takes advantage of this to make narrowing a little smarter. When parameters and let variables are used in non- hoisted functions, the type-checker will look for a last assignment point. If one is found, TypeScript can safely narrow from outside the containing function. What that means is the above example just works now.

Note that narrowing analysis doesn’t kick in if the variable is assigned anywhere in a nested function. This is because there’s no way to know for sure whether the function will be called later.

This should make lots of typical JavaScript code easier to express. You can read more about the change on GitHub .

When calling generic functions, TypeScript is able to infer type arguments from whatever you pass in.

One challenge, however, is that it is not always clear what the "best" type is to infer. This might lead to TypeScript rejecting valid calls, accepting questionable calls, or just reporting worse error messages when it catches a bug.

For example, let’s imagine a createStreetLight function that takes a list of color names, along with an optional default color.

What happens when we pass in a defaultColor that wasn’t in the original colors array? In this function, colors is supposed to be the "source of truth" and describe what can be passed to defaultColor .

In this call, type inference decided that "blue" was just as valid of a type as "red" or "yellow" or "green" . So instead of rejecting the call, TypeScript infers the type of C as "red" | "yellow" | "green" | "blue" . You might say that inference just blue up in our faces!

One way people currently deal with this is to add a separate type parameter that’s bounded by the existing type parameter.

This works, but is a little bit awkward because D probably won’t be used anywhere else in the signature for createStreetLight . While not bad in this case , using a type parameter only once in a signature is often a code smell.

That’s why TypeScript 5.4 introduces a new NoInfer<T> utility type. Surrounding a type in NoInfer<...> gives a signal to TypeScript not to dig in and match against the inner types to find candidates for type inference.

Using NoInfer , we can rewrite createStreetLight as something like this:

Excluding the type of defaultColor from being explored for inference means that "blue" never ends up as an inference candidate, and the type-checker can reject it.

You can see the specific changes in the implementing pull request , along with the initial implementation provided thanks to Mateusz Burzyński !

TypeScript 5.4 adds declarations for JavaScript’s new Object.groupBy and Map.groupBy static methods.

Object.groupBy takes an iterable, and a function that decides which "group" each element should be placed in. The function needs to make a "key" for each distinct group, and Object.groupBy uses that key to make an object where every key maps to an array with the original element in it.

So the following JavaScript:

is basically equivalent to writing this:

Map.groupBy is similar, but produces a Map instead of a plain object. This might be more desirable if you need the guarantees of Map s, you’re dealing with APIs that expect Map s, or you need to use any kind of key for grouping – not just keys that can be used as property names in JavaScript.

and just as before, you could have created myObj in an equivalent way:

Note that in the above example of Object.groupBy , the object produced uses all optional properties.

This is because there’s no way to guarantee in a general way that all the keys were produced by groupBy .

Note also that these methods are only accessible by configuring your target to esnext or adjusting your lib settings. We expect they will eventually be available under a stable es2024 target.

We’d like to extend a thanks to Kevin Gibbons for adding the declarations to these groupBy methods .

TypeScript has a moduleResolution option called bundler that is meant to model the way modern bundlers figure out which file an import path refers to. One of the limitations of the option is that it had to be paired with --module esnext , making it impossible to use the import ... = require(...) syntax.

That might not seem like a big deal if you’re planning on just writing standard ECMAScript import s, but there’s a difference when using a package with conditional exports .

In TypeScript 5.4, require() can now be used when setting the module setting to a new option called preserve .

Between --module preserve and --moduleResolution bundler , the two more accurately model what bundlers and runtimes like Bun will allow, and how they’ll perform module lookups. In fact, when using --module preserve , the bundler option will be implicitly set for --moduleResolution (along with --esModuleInterop and --resolveJsonModule )

Under --module preserve , an ECMAScript import will always be emitted as-is, and import ... = require(...) will be emitted as a require() call (though in practice you may not even use TypeScript for emit, since it’s likely you’ll be using a bundler for your code). This holds true regardless of the file extension of the containing file. So the output of this code:

should look something like this:

What this also means is that the syntax you choose directs how conditional exports are matched. So in the above example, if the package.json of some-package looks like this:

TypeScript will resolve these paths to [...]/some-package/esm/foo-from-import.mjs and [...]/some-package/cjs/bar-from-require.cjs .

For more information, you can read up on these new settings here .

Import attributes and assertions are now checked against the global ImportAttributes type. This means that runtimes can now more accurately describe the import attributes

This change was provided thanks to Oleksandr Tarasiuk .

TypeScript now has a quick fix to add a new parameter to functions that are called with too many arguments.

A quick fix being offered when someFunction calls someHelperFunction with 2 more arguments than are expected.

This can be useful when threading a new argument through several existing functions, which can be cumbersome today.

This quick fix was provided courtsey of Oleksandr Tarasiuk .

Upcoming Changes from TypeScript 5.0 Deprecations

TypeScript 5.0 deprecated the following options and behaviors:

  • target: ES3
  • importsNotUsedAsValues
  • noImplicitUseStrict
  • noStrictGenericChecks
  • keyofStringsOnly
  • suppressExcessPropertyErrors
  • suppressImplicitAnyIndexErrors
  • preserveValueImports
  • prepend in project references
  • implicitly OS-specific newLine

To continue using them, developers using TypeScript 5.0 and other more recent versions have had to specify a new option called ignoreDeprecations with the value "5.0" .

However, TypScript 5.4 will be the last version in which these will continue to function as normal. By TypeScript 5.5 (likely June 2024), these will become hard errors, and code using them will need to be migrated away.

For more information, you can read up on this plan on GitHub , which contains suggestions in how to best adapt your codebase.

This section highlights a set of noteworthy changes that should be acknowledged and understood as part of any upgrade. Sometimes it will highlight deprecations, removals, and new restrictions. It can also contain bug fixes that are functionally improvements, but which can also affect an existing build by introducing new errors.

lib.d.ts Changes

Types generated for the DOM may have an impact on type-checking your codebase. For more information, see the DOM updates for TypeScript 5.4 .

More Accurate Conditional Type Constraints

The following code no longer allows the second variable declaration in the function foo .

Previously, when TypeScript checked the initializer for second , it needed to determine whether IsArray<U> was assignable to the unit type false . While IsArray<U> isn’t compatible any obvious way, TypeScript looks at the constraint of that type as well. In a conditional type like T extends Foo ? TrueBranch : FalseBranch , where T is generic, the type system would look at the constraint of T , substitute it in for T itself, and decide on either the true or false branch.

But this behavior was inaccurate because it was overly-eager. Even if the constraint of T isn’t assignable to Foo , that doesn’t mean that it won’t be instantiated with something that is. And so the more correct behavior is to produce a union type for the constraint of the conditional type in cases where it can’t be proven that T never or always extends Foo.

TypeScript 5.4 adopts this more accuratre behavior. What this means in practice is that you may begin to find that some conditional type instances are no longer compatible with their branches.

You can read about the specific changes here .

More Aggressive Reduction of Intersections Between Type Variables and Primitive Types

TypeScript now reduces intersections with type variables and primitives more aggressively, depending on how the type variable’s constraint overlaps with those primitives.

For more information, see the change here .

Improved Checking Against Template Strings with Interpolations

TypeScript now more accurately checks whether or not strings are assignable to the placeholder slots of a template string type.

This behavior is more desirable, but may cause breaks in code using constructs like conditional types, where these rule changes are easy to witness.

See this change for more details.

Errors When Type-Only Imports Conflict with Local Values

Previously, TypeScript would permit the following code under isolatedModules if the import to Something only referred to a type.

However, it’s not safe for a single-file compilers to assume whether it’s "safe" to drop the import , even if the code is guaranteed to fail at runtime. In TypeScript 5.4, this code will trigger an error like the following:

The fix should be to either make a local rename, or, as the error states, add the type modifier to the import:

See more information on the change itself .

New Enum Assignability Restrictions

When two enums have the same declared names and enum member names, they were previously always considered compatible; however, when the values were known, TypeScript would silently allow them to have differing values.

TypeScript 5.4 tightens this restriction by requiring the values to be identical when they are known.

Additionally, there are new restrictions for when one of the enum members does not have a statically-known value. In these cases, the other enum must at least be implicitly numeric (e.g. it has no statically resolved initializer), or it is explicitly numeric (meaning TypeScript could resolve the value to something numeric). Practically speaking, what this means is that string enum members are only ever compatible with other string enums of the same value.

For more information, see the pull request that introduced this change .

Name Restrictions on Enum Members

TypeScript no longer allows enum members to use the names Infinity , -Infinity , or NaN .

See more details here .

Better Mapped Type Preservation Over Tuples with any Rest Elements

Previously, applying a mapped type with any into a tuple would create an any element type. This is undesirable and is now fixed.

For more information, see the fix along with the follow-on discussion around behavioral changes and further tweaks .

Emit Changes

While not a breaking change per-se, developers may have implicitly taken dependencies on TypeScript’s JavaScript or declaration emit outputs. The following are notable changes.

  • Preserve type parameter names more often when shadowed
  • Move complex parameter lists of async function into downlevel generator body
  • Do not remove binding alias in function declarations
  • ImportAttributes should go through the same emit phases when in an ImportTypeNode

What’s Next?

At this point, we anticipate very few changes to TypeScript 5.4 apart from critical bug fixes to the compiler and minor bug fixes to the language service. In the next few weeks, we’ll be releasing the first stable version of TypeScript 5.4. Keep an eye on our iteration plan for target release dates and more if you need to plan around that.

Otherwise, our main focus is on developing TypeScript 5.5, and we’ve just made the TypeScript 5.5 Iteration Plan public as well. Similarly, that iteration plan describes our planned focus areas and work items, and target release dates which you can use to for your own plans. On top of that, we make it easy to use nightly builds of TypeScript on npm , and there is an extension to use those nightly releases in Visual Studio Code .

So give the RC or our nightlies a try, and let us know how it goes!

Happy Hacking!

– Daniel Rosenwasser and the TypeScript Team

variable assignment javascript

Daniel Rosenwasser Senior Program Manager, TypeScript

variable assignment javascript

Leave a comment Cancel reply

Log in to join the discussion.

' data-src=

I think the list of deprecated options is missing `importsNotUsedAsValues` and `preserveValueImports`.

variable assignment javascript

Fixed, thanks Ashley!

light-theme-icon

Insert/edit link

Enter the destination URL

Or link to existing content

IMAGES

  1. Quick Tip: How to Declare Variables in JavaScript

    variable assignment javascript

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

    variable assignment javascript

  3. What is operator in javascript with example?

    variable assignment javascript

  4. JavaScript Variables

    variable assignment javascript

  5. JavaScript Variables and Data Types (with Examples)

    variable assignment javascript

  6. JavaScript Operators.

    variable assignment javascript

VIDEO

  1. 06

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

  3. Assignments

  4. JS class

  5. JavaScript: Variable and DataTypes

  6. JavaScript for Beginners

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. This allows multiple assignments to be chained in order to assign a single value to multiple variables. Try it Syntax js x = y Parameters x

  2. JavaScript Variables

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

  3. JavaScript Assignment

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

  4. JavaScript OR (||) variable assignment explanation

    JavaScript OR (||) variable assignment explanation Ask Question Asked 14 years ago Modified 5 years, 7 months ago Viewed 414k times 412 Given this snippet of JavaScript... var a; var b = null; var c = undefined; var d = 4; var e = 'five'; var f = a || b || c || d || e; alert (f); // 4

  5. A Guide to Variable Assignment and Mutation in JavaScript

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

  6. Storing the information you need

    A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence. Variable example Let's look at a simple example: html <button id="button_A">Press me</button> <h3 id="heading_A"></h3> js

  7. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value.

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

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

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

  11. Variables and assignment • JavaScript for impatient programmers (ES2022

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

    In JavaScript, it's possible to declare variables in a single statement. let x = 5, y = 6, z = 7; If you use a variable without initializing it, it will have an undefined value. let x; // x is the name of the variable console.log (x); // undefined. Here x is the variable name and since it does not contain any value, it will be undefined.

  13. JavaScript Variables

    JavaScript allows you to declare two or more variables using a single statement. To separate two variable declarations, you use a comma (,) like this: let message = "Hello" , counter = 100; Code language: JavaScript (javascript) Since JavaScript is a dynamically typed language, you can assign a value of a different type to a variable.

  14. JavaScript Variables

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

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

  16. Multiple Variable Assignment in JavaScript

    Use the = Operator to Assign Multiple Variable in JavaScript Assume we have variable1, variable2, and variable3 and want all three variables to have a value of 1.

  17. Destructuring assignment

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

  18. Logical OR assignment (||=)

    Syntax js x ||= y Description Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator.

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

    10 Answers Sorted by: 167 Using Javascript's es6 or node, you can do the following: var [a,b,c,d] = [0,1,2,3] And if you want to easily print multiple variables in a single line, just do this: console.log (a, b, c, d)

  20. Announcing TypeScript 5.4 RC

    TypeScript 5.4 takes advantage of this to make narrowing a little smarter. When parameters and let variables are used in non-hoisted functions, the type-checker will look for a last assignment point. If one is found, TypeScript can safely narrow from outside the containing function.

  21. variables

    variable-assignment Share Improve this question Follow asked Nov 18, 2009 at 19:48 David Calhoun 8,433 5 31 24 10 ASSIGNMENT HAPPENS RIGHT TO LEFT javascript operator precedence - neaumusic Dec 2, 2015 at 23:45 1 is this also applicable if I use this.var1 = this.var2 = this.var3 = 1 ? - Gangadhar Jannu Oct 29, 2018 at 13:07

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

    20 Answers Sorted by: 764 This is a one-line shorthand for an if-else statement. It's called the conditional operator. 1 Here is an example of code that could be shortened with the conditional operator: var userType; if (userIsYoungerThan18) { userType = "Minor"; } else {