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

How to declare multiple Variables in JavaScript?

  • How to Declare a Variable in JavaScript ?
  • How to declare Global Variables in JavaScript ?
  • How to create Static Variables in JavaScript ?
  • How to Declare a Constant Variable in JavaScript ?
  • How to Concatenate Two Variables in JavaScript ?
  • How to create a private variable in JavaScript ?
  • How to declare namespace in JavaScript ?
  • How to Decrement a Variable by 1 in JavaScript ?
  • How to Access EJS Variable in Javascript Logic ?
  • How to declare variables in different ways in JavaScript?
  • How to use dynamic variable names in JavaScript ?
  • How to Declare Variables in TypeScript ?
  • How to pass value to execute multiple conditions in JavaScript ?
  • How to return the data type of variable in JavaScript ?
  • How to Create a While Loop in JavaScript ?
  • JavaScript Course Variables in JavaScript
  • JavaScript Return multiple values from function
  • How to unset JavaScript variables?
  • Global and Local variables in JavaScript

In this article, we will see how to declare multiple Variables in JavaScript. The variables can be declared using var , let , and const keywords. Variables are containers that store some value and they can be of any type.

These are the following ways to declare multiple variables:

Table of Content

Declaring Variables Individually

Declaring variables in a single line, using destructuring assignment.

In this case, we will declare each variable using the var, let, or const keywords.

Example: In this example, we are declaring three different variables.

You can declare multiple variables in a single line using the var, let, or const keyword followed by a comma-separated list of variable names.

Example: In this example, we are defining the three variables at once.

You can also use de-structuring assignments to declare multiple variables in one line and assign values to them.

Example: In this example, we are declaring three different variable by destructuring them at once.

Please Login to comment...

Similar reads.

  • JavaScript-Questions
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

JavaScript declare multiple variables tutorial

by Nathan Sebhastian

Posted on May 02, 2021

Reading time: 2 minutes

multiple variable assignment javascript

The most common way to declare and initialize JavaScript variables is by writing each variable in its own line as follows:

But there are actually shorter ways to declare multiple variables using JavaScript. First, you can use only one variable keyword (var, let, or const) and declare the variable names and values separated by commas.

Take a look at the following example:

The declaration above just use one line, but it’s a bit harder to read than separated declarations. Furthermore, all the variables are declared using the same keyword let . You can’t use other variable keywords like const and var .

You can also make a multi-line declaration using comma-separated declaration as shown below:

Finally, you can also use destructuring assignment to declare and initialize multiple variables in one line as follows:

The destructuring assignment from the code above extracts the array elements and assigns them to the variables declared on the left side of the = assignment operator.

The code examples above are some tricks you can use to declare multiple variables in one line with JavaScript. Still, the most common way to declare variables is to declare them one by one, because it decouples the declaration into its own line:

The code above will be the easiest to change later as your project grows.

You can only use one variable keyword when using comma-separated declaration and destructuring assignment, so you can’t change the variables from const to let without changing them all.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

How to Declare Multiple Variables at Once in JavaScript

  • #javascript

How to Declare Multiple Variables at Once in JavaScript

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

How to Declare Multiple Variables in JavaScript

  • JavaScript Howtos
  • How to Declare Multiple Variables in …

How to Declare Multiple Variables in JavaScript

Variables are containers in JavaScript that hold reusable data. They’re like cups filled with stuff that can be used repeatedly depending on how we want to use it.

Here are some JavaScript tips for declaring multiple variables.

Declare Multiple Variables in JavaScript

The most common method for declaring and initializing JavaScript variables is to write each variable on its line.

Example Code:

However, there are shorter ways to declare multiple variables in JavaScript. First, you can only use one variable keyword ( var , let , or const ) and declare variable names and values separated by commas.

The declaration above is only one line long, but it is more challenging to read than separated declarations. In addition, all variables are declared with the same keyword, let .

Other variable keywords, such as const and var, are not permitted. You can also use comma-separated declarations to create a multi-line declaration.

Finally, the de-structuring assignment can be used to reveal and preprocess multiple variables in a single line.

The array elements are extracted and assigned to the variables declared on the = operator’s left side in the code above.

The code examples above demonstrate how to declare multiple variables in a single line of JavaScript. Still, declaring variables one by one is the most common method because it separates the declaration into its line, like the following example below.

As your project grows, the code above will be the easiest to change.

When using comma-separated declaration and de-structuring assignment, you can only use one variable keyword, so you can’t change the variables from const to let without changing them all. In their own way, these variable types are distinct and help speed up code development.

However, it is recommended to use let whenever possible. You can use const whenever the variable’s value must remain constant.

Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

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

multiple variable assignment javascript

How to declare multiple variables in JavaScript self.__wrap_n=self.__wrap_n||(self.CSS&&CSS.supports("text-wrap","balance")?1:2);self.__wrap_b=(r,n,e)=>{e=e||document.querySelector(`[data-br="${r}"]`);let o=e.parentElement,l=u=>e.style.maxWidth=u+"px";e.style.maxWidth="";let s,i=o.clientWidth,p=o.clientHeight,a=i/2-.25,d=i+.5;if(i){for(l(a),a=Math.max(e.scrollWidth,a);a+1 {self.__wrap_b(0,+e.dataset.brr,e)})).observe(o)};self.__wrap_n!=1&&self.__wrap_b(":R4p4sm:",1)

multiple variable assignment javascript

Kris Lachance

Head of Growth

What is Basedash?

Sign up ->

October 30, 2023

JavaScript lets you declare multiple variables in a single statement, streamlining the process of setting up your variables. This guide dives into the syntax and strategies for declaring multiple variables efficiently in JavaScript.

Declaring multiple variables with one var keyword

The var keyword can be used to declare multiple variables at once, separated by commas. This method was commonly used in ES5 and earlier versions:

However, it's worth noting that var has function scope and is hoisted, which can lead to unexpected behaviors in certain situations.

Using let for block-scoped variables

ES6 introduced let , which allows for block-scoped variable declarations. Like var , you can declare multiple variables in one line:

Since let has block scope, it reduces the risk of errors related to variable hoisting and scope leakage.

Declaring with const for constants

When you need to declare variables whose values should not change, use const . Similar to let , you can declare multiple constants in a single line:

Remember that each constant must be initialized at the time of declaration, as their values cannot be reassigned later.

Grouping declarations and assignments

You can group variable declarations without initialization and then assign values later:

This can improve readability, especially when variable names are related or when initializing with values derived from complex expressions.

One-liner with destructuring assignment

Destructuring allows you to declare multiple variables by extracting values from arrays or objects:

For objects:

Destructuring can be especially handy for functions that return multiple values.

Default values with destructuring

When destructuring, you can also set default values for your variables in case the value extracted is undefined :

In the example above, j will default to 10 and k will be set to 21 .

Nested destructuring

For more complex data structures, nested destructuring can declare multiple variables at various levels of the structure:

This will declare n , o , and p with values 11 , 12 , and 13 respectively.

For loops and variable declarations

Within for loops, it's common to declare a loop variable, but you can declare additional variables as well:

Here, q and r are loop variables with different iteration logic.

Imagine the time you'd save if you never had to build another internal tool, write a SQL report, or manage another admin panel again. Basedash is built by internal tool builders, for internal tool builders. Our mission is to change the way developers work, so you can focus on building your product.

Learn more about Basedash

Book a demo

multiple variable assignment javascript

Temporal dead zone and let / const

It's important to remember that let and const declarations are subject to the Temporal Dead Zone (TDZ), meaning they cannot be accessed before declaration:

Tips for clean code

When declaring multiple variables, aim for clarity:

  • Use one let or const per variable for easier debugging and readability.
  • Group related declarations together.
  • Initialize variables with values as close to the declaration as possible.

By following these practices, you ensure that your variable declarations enhance, rather than obfuscate, the readability and maintainability of your JavaScript code.

Additional contexts for declaring variables

Using variables in different scopes.

Discuss the nuances of variable scope:

var hoisting peculiarities

Explain the behavior of var regarding hoisting:

Advanced variable declaration patterns

Chained variable assignments.

Chain variable assignments carefully:

Variables in try-catch blocks

Handle try-catch with variable scopes:

Use in modern JavaScript frameworks

Demonstrate variable declarations in frameworks:

Additional good practices

Minimizing global variables.

Limit global variables as much as possible.

Naming conventions

Adopt clear naming conventions:

Performance considerations

Consider performance in declarations:

Debugging and variable declarations

Factor in the implications on debugging when declaring variables.

Cleaning up unused variables

Regularly remove unused variables to clean up your codebase.

Click to keep reading

Ship faster, worry less with Basedash

You're busy enough with product work to be weighed down building, maintaining, scoping and developing internal apps and admin panels. Forget all of that, and give your team the admin panel that you don't have to build. Launch in less time than it takes to run a standup.

Sign up for free

multiple variable assignment javascript

Dashboards and charts

Edit data, create records, oversee how your product is running without the need to build or manage custom software.

ADMIN PANEL

Sql composer with ai.

Screenshot of a users table in a database. The interface is very data-dense with information.

Related posts

multiple variable assignment javascript

How to Remove Characters from a String in JavaScript

Jeremy Sarchet

multiple variable assignment javascript

How to Sort Strings in JavaScript

multiple variable assignment javascript

How to Remove Spaces from a String in JavaScript

Detecting Prime Numbers in JavaScript

Robert Cooper

multiple variable assignment javascript

How to Parse Boolean Values in JavaScript

multiple variable assignment javascript

How to Remove a Substring from a String in JavaScript

All JavaScript guides

multiple variable assignment javascript

Get high quality AI code reviews

  • 90+ point analyses every run
  • AI that understands your code

Javascript Assign Multiple Variables: Javascript Explained

Table of contents.

Javascript is a programming language that is widely used for website development, building web applications, and in general web programming. Javascript is also a powerful language for assigning multiple variables at once. This article will explain how to assign multiple variables in Javascript, along with best practices, common pitfalls, and the benefits of doing so.

What is Javascript?

Javascript is a client-side scripting language commonly used for web development. It is an interpreted programming language that is used to make websites interactive. JavaScript code is typically executed by a web browser, though it can also be used with a Node.js server or even Apache web servers. It is one of the three core web technologies that make up web development – the others being HTML and CSS. As a client-side language, it runs on the user’s computer or device, and not on the server.

Javascript is a powerful language that can be used to create dynamic webpages, interactive web applications, and even mobile applications. It is also used to create games, and is often used in combination with HTML and CSS to create visually appealing websites. Javascript is a versatile language that can be used to create a wide variety of applications, and is an essential part of modern web development.

Basics of Assigning Variables in Javascript

Variables are an important concept in programming. A variable is a name that stores a value. Variable names can be defined when you need to refer to that same value multiple times. Variables can store all kinds of data types in Javascript – including strings, numbers, boolean values, objects, and others. In Javascript, variables are declared using the let, const, or var keywords.

When declaring a variable, it is important to choose a name that is descriptive and easy to remember. This will help you to easily identify the purpose of the variable when you come back to your code later. Additionally, it is important to remember that variables are case sensitive, so be sure to use the same capitalization when referring to the same variable.

What is Variable Assignment?

Variable assignment is a concept in programming where you assign a value to a variable name. This creates a link between the variable and its value that can be reused throughout your program. Variable assignment can be done in a few different ways in Javascript: you can use the let and const keywords to define variables with an initial value, or you can use the variable assignment operator (the equal sign) to assign a value to an existing variable.

It is important to note that variables can be reassigned at any time. This means that you can change the value of a variable by simply assigning a new value to it. This is a useful feature of programming languages, as it allows you to easily update the values of variables as your program runs.

Assigning Multiple Variables in Javascript

In addition to assigning single variables, you can assign multiple variables with a single statement in Javascript. This allows you to reduce lines of code while still passing all the necessary information. To assign multiple variables in Javascript, use the following syntax: let [var1],[var2],... = [value1],[value2],...; .

When assigning multiple variables, the number of variables and values must match. If there are more variables than values, the remaining variables will be assigned the value of ‘undefined’. Additionally, the variables must be declared before they can be assigned a value. This means that the let keyword must be used before the variable names.

How to Create a Variable Assignment Statement

Creating a variable assignment statement follows the same structure as creating any other statement in Javascript. Start with the keyword (let or const) and a list of variables separated by commas. Next, add the equals sign followed by a list of values separated by commas. Make sure to end your statement with a semicolon ( ; ) to denote the end of your statement.

It is important to note that the values assigned to the variables must match the data type of the variable. For example, if you are assigning a string to a variable, the value must be enclosed in quotation marks. Similarly, if you are assigning a number to a variable, the value must not be enclosed in quotation marks.

Best Practices for Variable Assignment in Javascript

When assigning multiple variables in Javascript, it is important to consider best practices to ensure that your code is readable, efficient, and secure. First, it is recommended to break up large assignments into multiple lines to increase readability and make debugging easier. Second, it is important to avoid assigning many variables at once as this can make your code more difficult to debug. Finally, it is important to ensure that your variables are not assigned with unexpected values – for example, global variables should only be declared with const.

It is also important to use descriptive variable names to make your code easier to read and understand. Additionally, it is recommended to use the let keyword when declaring variables that will be reassigned, and the const keyword when declaring variables that will not be reassigned. Finally, it is important to use strict equality (===) when comparing values, as this will ensure that the comparison is accurate and secure.

Common Mistakes When Assigning Multiple Variables in Javascript

When assigning multiple variables in Javascript, there are several common mistakes that you should avoid. First, make sure you are using the right assignment operator – if you use the equal sign (=) instead of let or const you will end up with an error. Second, make sure you have listed all of your variables and values correctly – if you miss one your program will fail. Finally, be careful if/when assigning global variables as they may affect other parts of your program.

It is also important to remember that variables are case sensitive, so make sure you are using the same case when assigning and referencing variables. Additionally, make sure you are using the correct syntax when assigning multiple variables. For example, if you are using let, you should separate each variable with a comma, and if you are using const, you should separate each variable with a semicolon. Finally, make sure you are using the correct data type for each variable – if you assign a string to a number variable, you will end up with an error.

Benefits of JavaScript for Multi-Variable Assignment

Javascript provides developers with various benefits when it comes to multi-variable assignment. First, it allows for more readable and organized code by enabling the assignment of multiple variables at once instead of individually. Second, it reduces coding time as it eliminates the need for typing each variable assignment statement separately. Last but not least, it makes debugging easier as changes made in one part of the code are propagated across all associated variables.

Assigning multiple variables in Javascript can be a great way to reduce complexity and improve readability when writing code. However, it is important to understand both the basics of variable assignment as well as the best practices in order to ensure that your code is secure and working correctly. By understanding how to assign multiple variables and avoiding common pitfalls, you will be able to maximize the benefits of variable assignment in your projects.

Nisha Kumari

Nisha Kumari

Nisha Kumari, a Founding Engineer at Bito, brings a comprehensive background in software engineering, specializing in Java/J2EE, PHP, HTML, CSS, JavaScript, and web development. Her career highlights include significant roles at Accenture, where she led end-to-end project deliveries and application maintenance, and at PubMatic, where she honed her skills in online advertising and optimization. Nisha's expertise spans across SAP HANA development, project management, and technical specification, making her a versatile and skilled contributor to the tech industry.

Written by developers for developers

Latest posts, mastering python’s writelines() function for efficient file writing | a comprehensive guide, understanding the difference between == and === in javascript – a comprehensive guide, compare two strings in javascript: a detailed guide for efficient string comparison, exploring the distinctions: == vs equals() in java programming, understanding matplotlib inline in python: a comprehensive guide for visualizations, related articles.

multiple variable assignment javascript

Cut review time by 50%

  • Join us on Slack
  • Twitter / X
  • AI Code Review Agent
  • AI Chat in your IDE
  • AI Chat in your CLI
  • AI Code Completions
  • AI Prompt Templates
  • AI Automations
  • Documentation Agent
  • Unit Test Agent
  • Documentation
  • 2023 State of AI in Software Report
  • 2023 How Devs use AI Report
  • Dev Resources
  • Terms of Use
  • Privacy Statement
  • © 2023 Bito. All rights reserved.

multiple variable assignment javascript

Install on IDEs like IntelliJ, WebStorm etc.

multiple variable assignment javascript

livingwithcode logo

  • Python Guide

Assign Multiple Variables to the Same Value in JavaScript

By James L.

Sometimes you may need to assign the same value to multiple variables. In this article, I will show you exactly how to assign the same value to multiple variables using different methods.

Method 1: Using the equal sign (=) consecutively

You can set multiple variables to the same value in JavaScript by using the equal sign (=) consecutively between the variable names and assigning a single value at the end when declaring the variables.

For example:

The above code is equivalent to

You can also declare the variables first and assign the value later.

You can also use the ‘let’ or ‘const’ keyword instead of ‘var’ to create variables.

You can also create an undeclared variable without using any keywords.

If you want to assign different values to different variables, you can also do that using the syntax below.

We can also assign different values to different variables in the same line of code.

After assigning the same value to multiple variables, if we update any of the variables, it will not affect others.

In the example below, variables a, b, and c are assigned to 10 initially and then b is changed to 20.

As you can see from the above example, only the value of variable b is changed to 20. Variables a and c are not affected when we update the value of variable b because all variables a, b, and c are assigned with a primitive value.

Variables assigned with primitive values like a number, string, boolean, bigint, undefined, symbol, and null get replaced when a new value is assigned to the same variable because primitive values are immutable. i.e. the value itself cannot be altered but the variable can be replaced. Same is not the case for non-primitive values.

You need to be very careful when assigning the same non-primitive value like array, function, and objects to multiple variables because non-primitive values are mutable. i.e. the value itself can be altered. So the value itself will be changed instead of the variable getting replaced.

If you use the equal sign (=) consecutively to create multiple variables with the same non-primitive value. If you update the value of one variable, the value of all the variables will be updated too.

As you can see from the above example that if we update the value of variable a, the value of both variables will be updated. This happens because both variables a and b points to the same array object. And if we update the value of one variable the others get affected too.

So if you want to handle them separately then you need to assign them separately.

Method 2: Using the destructuring assignment syntax

Destructuring assignment syntax is a javascript expression that helps us to unpack values from arrays or objects into different variables.

We can also assign multiple values to the same value using destructuring assignment syntax combined with the fill function.

Related Posts

Latest posts.

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript variables, variables are containers for storing data.

JavaScript Variables can be declared in 4 ways:

  • Automatically
  • Using const

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

They are automatically declared when first used:

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

From the examples you can guess:

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

Example using var

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

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

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

Example using let

Example using const, mixed example.

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

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

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

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

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

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

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

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

Variables are containers for storing values.

Advertisement

JavaScript Identifiers

All JavaScript variables must be identified with unique names .

These unique names are called identifiers .

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

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

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

JavaScript identifiers are case-sensitive.

The Assignment Operator

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

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

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

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

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

JavaScript Data Types

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

In programming, text values are called text strings.

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

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

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

Declaring a JavaScript Variable

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

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

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

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

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

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

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

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

One Statement, Many Variables

You can declare many variables in one statement.

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

A declaration can span multiple lines:

Value = undefined

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

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

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

Re-Declaring JavaScript Variables

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

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

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

This will not work:

JavaScript Arithmetic

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

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

Also try this:

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

Now try this:

JavaScript Dollar Sign $

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

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

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

JavaScript Underscore (_)

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

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

Test Yourself With Exercises

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

OneBite.Dev - Coding blog in a bite size

assign multiple variables in Javascript

Code snippet on how to assign multiple variables in Javascript

This code assigns three variables: name, age, and job. The variable “name” is assigned the value “John”, the variable “age” is assigned the value 25, and the variable “job” is assigned the value “programmer”. This code uses the keyword “var” to declare each variable and assign them the given value with the “=” operator. The code also uses a single line to declare multiple variables and assign all of the required values.

The Electric Toolbox Blog

Multiple variable assignment with Javascript

About a month ago I posted how it is possible to assign multiple variables with the same value in PHP and have since learned that this is also possible to do with Javascript. This can be useful if initializing multiple variables with the same initial value or if needing to make multiple copies of a value and then manipulate each separately.

Assigning multiple variables

Using the same set sort of examples as in the PHP post, but this time with Javascript, multiple variables can be assigned by using = multiple times on the same line of code like so:

The above is a more compact equivilent of this:

Here’s an example where all three variables are assigned initially with the string "AAA" and then the values of each are written out to the current page using document.write:

The resulting output on the page would look like this:

Any subsequent updates to any of the variables will not affect the other assigned variables. In the next example a, b and c are again initialised with "AAA" and then b is changed to "BBB".

The output from this example would be:

Check Out These Related posts:

  • Trimming strings with Javascript
  • Setting default values for missing parameters in a Javascript function
  • Using SELECT REPLACE with MySQL
  • PHP Error Class ‘SoapClient’ not found
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

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.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

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

  • Assignment operators
  • ES6 in Depth: Destructuring on hacks.mozilla.org (2015)

IMAGES

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

    multiple variable assignment javascript

  2. Two Ways To Declare Variables In JavaScript

    multiple variable assignment javascript

  3. Multiple Variable Assignment in JavaScript

    multiple variable assignment javascript

  4. How To Pass Multiple Variables Into A Javascript Function

    multiple variable assignment javascript

  5. Javascript variable in method

    multiple variable assignment javascript

  6. 36 Declare Multiple Const Javascript

    multiple variable assignment javascript

VIDEO

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

  2. Lecture 14: JavaScript Variable Basics: let, const, and var

  3. Javascript Variables

  4. 1st Assignment JavaScript/ Type script in a governor house onsite class

  5. References, Mutations and Re-assignment

  6. JavaScript variable assignment const variable

COMMENTS

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

    Reading documentation online, I'm getting confused how to properly define multiple JavaScript variables on a single line. If I want to condense the following code, what's the proper JavaScript "strict" way to define multiple javascript variables on a single line? var a = 0; var b = 0; Is it: var a = b = 0; or. var a = var b = 0; etc...

  2. variables

    Assignment in javascript works from right to left. var var1 = var2 = var3 = 1;. If the value of any of these variables is 1 after this statement, then logically it must have started from the right, otherwise the value or var1 and var2 would be undefined. You can think of it as equivalent to var var1 = (var2 = (var3 = 1)); where the inner-most ...

  3. Multiple Variable Assignment in JavaScript

    Output: 1, 1, 1, 1. undefined. 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.

  4. How to declare multiple Variables in JavaScript?

    Declaring Variables in a Single Line. You can declare multiple variables in a single line using the var, let, or const keyword followed by a comma-separated list of variable names. Syntax: let x = 20, y = 30, z = 40; Example: In this example, we are defining the three variables at once.

  5. Assignment (=)

    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.

  6. Declare Multiple Variables in a Single Line in JavaScript

    To declare multiple variables in JavaScript, you can use the var, let or const keyword followed by a comma-separated list of variable names, each initialized with corresponding values. For example: var x = 5, y = 10, z = 15; Or. let x = 5, y = 10, z = 15; Or. const x = 5, y = 10, z = 15; Avoid using var unless you absolutely have to, such as ...

  7. JavaScript declare multiple variables tutorial

    The destructuring assignment from the code above extracts the array elements and assigns them to the variables declared on the left side of the = assignment operator. The code examples above are some tricks you can use to declare multiple variables in one line with JavaScript.

  8. How to Declare Multiple Variables in a Single Line in JavaScript

    Declare Multiple Variables in a Single Line Using De-structuring Algorithm in JavaScript With the introduction of ES2015 (also known as ES6), the de-structuring algorithm was added to JavaScript, and it has quickly become one of the most valuable aspects of the language for two reasons:

  9. How to Declare Multiple Variables at Once in JavaScript

    The most common way to declare multiple variables in JavaScript is to use commas to separate the variable names. This is the same as declaring each variable individually. let lastName; let age; You can also initialize them with values: You can improve readability by declaring each variable on a separate line:

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

  11. How to Declare Multiple Variables in JavaScript

    However, there are shorter ways to declare multiple variables in JavaScript. First, you can only use one variable keyword (var, let, ... When using comma-separated declaration and de-structuring assignment, you can only use one variable keyword, so you can't change the variables from const to let without changing them all. In their own way ...

  12. How to declare multiple variables in JavaScript

    Using let for block-scoped variables. ES6 introduced let, which allows for block-scoped variable declarations. Like var, you can declare multiple variables in one line: let a ='Hello', b ='World', c =100; Since let has block scope, it reduces the risk of errors related to variable hoisting and scope leakage.

  13. Javascript Assign Multiple Variables: Javascript Explained

    To assign multiple variables in Javascript, use the following syntax: let [var1],[var2],... = [value1],[value2],...;. When assigning multiple variables, the number of variables and values must match. If there are more variables than values, the remaining variables will be assigned the value of 'undefined'. Additionally, the variables must ...

  14. Assign Multiple Variables to the Same Value in JavaScript

    We can also assign different values to different variables in the same line of code. For example: var a = 2, b = 3; After assigning the same value to multiple variables, if we update any of the variables, it will not affect others. In the example below, variables a, b, and c are assigned to 10 initially and then b is changed to 20.

  15. JavaScript Variables

    All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume). The general rules for constructing names for variables (unique identifiers) are: Names can contain letters, digits, underscores, and dollar signs.

  16. Declare multiple variables in JavaScript

    Please stay away from that assignment pattern, even if you wanted to have all variables pointing to the same object.. In fact, only the first one will be a variable declaration, the rest are just assignments to possibly undeclared identifiers!. Assigning a value to an undeclared identifier (aka undeclared assignment) is strongly discouraged because, if the identifier is not found on the scope ...

  17. assign multiple variables in Javascript

    This code assigns three variables: name, age, and job. The variable "name" is assigned the value "John", the variable "age" is assigned the value 25, and the variable "job" is assigned the value "programmer". This code uses the keyword "var" to declare each variable and assign them the given value with the "=" operator.

  18. Multiple variable assignment with Javascript

    Assigning multiple variables. Using the same set sort of examples as in the PHP post, but this time with Javascript, multiple variables can be assigned by using = multiple times on the same line of code like so: var c = b = a; The above is a more compact equivilent of this: var b = a; var c = b;

  19. Assign multiple variables to the same value in Javascript?

    The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment. let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false); answered Jul 20, 2020 at 2:17.

  20. Destructuring assignment

    The catch binding variable. In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let, or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

  21. Javascript multiple variable assignment

    Javascript multiple variable assignment. Ask Question Asked 10 years ago. Modified 10 years ago. Viewed 2k times 3 This question has a few answers (sort of) already: Javascript: var = var = function, Multiple Variable Assignments in one row, etc. but I would like to ask a different kind of question about it. So, this is quite handy to be able ...