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

multiple assignment javascript

Answered on: Monday 11 December, 2023 / Duration: 15 min read

Programming Language: JavaScript , Popularity : 4/10

JavaScript Programming on www.codeease.net

Solution 1:

Multiple assignment in JavaScript

In JavaScript, you can assign multiple values to multiple variables in a single statement. This is called *multiple assignment*.

To perform multiple assignment, you use the following syntax:

This code will assign the values 1 , 2 , and 3 to the variables x , y , and z , respectively.

You can also use multiple assignment to swap the values of two variables. For example, the following code will swap the values of the variables a and b :

Multiple assignment can be a very useful shorthand for assigning multiple values to multiple variables. However, it is important to use it carefully, as it can be easy to make mistakes.

Code examples

The following code examples demonstrate how to use multiple assignment in JavaScript:

* Assigning multiple values to multiple variables:

* Swapping the values of two variables:

The following are the outputs of the code examples above:

Solution 2:

In JavaScript, multiple assignment refers to the ability to assign values to multiple variables in a single statement. This feature is particularly useful when you want to assign values from an array, object, or another iterable to multiple variables at once. Here are examples of multiple assignment in JavaScript:

### 1. Array Destructuring:

### 2. Object Destructuring:

### 3. Swapping Values:

### 4. Function Returning Multiple Values:

### 5. Rest Parameter in Array Destructuring:

These examples showcase different scenarios where multiple assignment can be employed in JavaScript, offering concise and readable code.

Solution 3:

In JavaScript, it is possible to assign multiple values to a single variable using the comma operator. This is known as a "multiple assignment" or "tuple assignment."

Here's an example of how you can use multiple assignment in JavaScript:

In this example, we declare three variables x , y , and z and then assign them all the value 10 using the comma operator. When we log each variable to the console, they all output 10 .

It's important to note that when using multiple assignment, the right-most expression is evaluated first, and its result is assigned to the left-hand side variables from right to left. So in the example above, z gets the value 10 first, then y , and finally x .

Multiple assignment can also be used with function returns, like so:

In this example, the function foo() returns an array of three values, which are then assigned to the variables x , y , and z from right to left.

Another way to do multiple assignment is by using destructuring, which allows you to extract values from arrays or objects and assign them to separate variables. Here's an example:

In this example, we define an object obj with two properties, a and b . We then use destructuring to extract those values and assign them to separate variables a and b .

It's worth noting that while multiple assignment is a powerful feature in JavaScript, it can sometimes make code harder to read and understand, especially for other developers who may not be familiar with the syntax. As such, it's generally considered best practice to avoid using multiple assignment in favor of more explicit and readable code.

More Articles :

How to set element readonly in jquery.

Answered on: Monday 11 December, 2023 / Duration: 5-10 min read

Programming Language : JavaScript , Popularity : 6/10

jquery add input placeholder

Programming Language : JavaScript , Popularity : 9/10

js loop array backwards

Refresh window js.

Programming Language : JavaScript , Popularity : 10/10

dimensions react native

Jquery visibility hidden show.

Programming Language : JavaScript , Popularity : 4/10

disable textbox jquery

Js console log with color, jquery ajax cors.

Programming Language : JavaScript , Popularity : 7/10

getthe array length of jsonb object postgres

Programming Language : JavaScript , Popularity : 5/10

check react version terminal windows

How to check if div is display none jquery, jquery hasclass, macos chrome disable web security, javascript change meta tag, export 'default' (imported as 'firebase') was not found in 'firebase/app', delay in javascript, nginx: [emerg] bind() to 0.0.0.0:80 failed (98: address already in use), add site url validation regex, cannot find module 'react', get current domain javascript.

Programming Language : JavaScript , Popularity : 8/10

Invalid Host header vue

Jquery 1 second after page load, rebuild node sass.

Programming Language : JavaScript , Popularity : 3/10

electron remove default menu

Javascript get previous element sibling, javascript redirect after 5 secinds, more than 2x speed on youtube, this is probably not a problem with npm. there is likely additional logging output above., how to link javascript to html and css, adding jquery from console.

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.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Shift Assignment Operators

Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

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

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.

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

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.

  • Web Technologies
  • JavaScript-Questions
  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

livingwithcode logo

  • Python Tutorial

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.

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

Example

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.

javascript multiple assignment

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

Object.assign()

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

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

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

Return value

The target object.

Description

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

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

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

Both String and Symbol properties are copied.

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

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

Cloning an object

Warning for deep clone.

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

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

Merging objects

Merging objects with same properties.

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

Copying symbol-typed properties

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

Specification

Browser compatibility

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

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

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:

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

Check Out These Related posts:

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Switch statement for multiple cases in JavaScript

I need multiple cases in switch statement in JavaScript, Something like:

How can I do that? If there's no way to do something like that in JavaScript, I want to know an alternative solution that also follows the DRY concept .

  • switch-statement

Archulan R's user avatar

  • 1 Sad that this syntax is not working :( –  Lars Flieger Commented Aug 26, 2021 at 11:46
  • the syntax is valid but it will only check on the last case, javascript should throw an error in such a case –  Isaac Weingarten Commented Mar 22, 2023 at 21:24

26 Answers 26

Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found, so you could write it like:

user229044's user avatar

  • 22 See: developer.mozilla.org/en-US/docs/JavaScript/Reference/… –  Xitalogy Commented Nov 3, 2012 at 9:52
  • 2 Somehow it works for me in Chrome, in the javascript console: switch('10') { case 1, '10': console.log('ok') } prints ok –  nafg Commented Sep 3, 2013 at 4:18
  • 9 @nafg: Try switch(1) . The label here is just a comma expression. –  kennytm Commented Sep 3, 2013 at 7:10
  • 4 @Barney No, without the break you can fall through to the next case. –  Seiyria Commented Apr 24, 2015 at 17:21
  • 1 @Seiyira by definition, there is no next case after the last. Besides, it's a default. –  Barney Commented Apr 24, 2015 at 17:22

This works in regular JavaScript:

Peter Mortensen's user avatar

  • 31 @believesInSanta it's literally just normal case fallthrough with weird formatting (spaces instead of newlines) –  Mihail Malostanidis Commented Feb 2, 2019 at 14:12
  • 4 You also can use case (1||2||3): instead of case 1: case 2: case 3: –  Kasun Hasanga Commented Nov 16, 2020 at 8:54
  • 2 case 1: case 2: case 3: worked for me and thanks, but @kasun Your solution does'nt work. –  Atmiya Kolsawala Commented May 3, 2021 at 9:37
  • 2 just an fyi, I tried @Kasun's method in TS, and it didn't work for me (I'm aware that OP wanted the solution in JS) –  George. Commented Jun 7, 2021 at 21:35
  • 3 The reason why @KasunHasanga's suggested solution doesn't work is because case (1||2||3): is equivalent to case 1: (since 1||2||3 evaluates to 1 ). –  Simon Alling Commented Aug 10, 2021 at 12:00

Here's different approach avoiding the switch statement altogether:

elclanrs's user avatar

  • 8 I definitely prefer this version. Fall through is a bug-prone feature of switch ... case . It's too easy to forget a break statement, and if you use fall through intentionally, those forgotten break statements can be very hard to spot. This method lookup version also has lots of great features that switch ... case lacks, such as dynamic extensibility, or the ability to completely replace the object to accomplish mode switching. It's also easier to keep cleanly organized, and can lead to more maintainable code. See ericleads.com/2012/12/switch-case-considered-harmful –  Eric Elliott Commented Sep 22, 2013 at 11:28
  • 43 I always add a comment //fallthrough in place of break whenever I intentionally omit the break . That helps to identify when it's a mistake and when it's intentional. –  Mnebuerquo Commented Jul 24, 2014 at 13:58
  • 26 Intuitive approach. However, for readability, I'd recommend to use the native switch statement. –  contactmatt Commented Nov 12, 2014 at 15:01
  • 55 One can always scratch the left ear passing its right hand through the back of the neck... (sorry for my english, I mean: "one can always complicate things as much as possible...in this case, avoiding the switch statement in favor of this complicated solution doesn't seem to be the right thing to do...) –  Clint Eastwood Commented Nov 17, 2014 at 13:53
  • 43 I'm truly amazed how this has gotten 34 up votes. In terms of readability and maintainability, this is absolutely horrific. If I want to see what conditions will trigger something, a case statement is incredibly simple and easy to see by looking at the labels. On the other hand, your version would require someone read pretty much every single line and see what you assigned where. This also gets even worse the more cases you want to match. –  michael Commented May 7, 2016 at 18:51

In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween like given below:

Please see example click on link

Geo's user avatar

  • 5 It's a common technique in a pletora of languages, not bound to JS –  drAlberT Commented Dec 12, 2013 at 15:06

I like this for clarity and a DRY syntax.

Kyle Dudley's user avatar

  • This is just an over-complicated if-condition –  N1ark Commented Mar 29, 2023 at 15:10
  • instead of if (true) you're saying if ("true" == "true") –  Vagif VALIYEV Commented Jan 20 at 17:54

If you're using ES6, you can do this:

Or for earlier versions of JavaScript, you can do this:

Note that includes won't work in some browser including older IE versions, but you could patch things up fairly easily. See the question determine if string is in list in javascript for more information.

ErikE's user avatar

  • What is the benefit of this over a switch? –  SNYDERHAUS Commented Jul 18, 2019 at 15:19
  • 5 @BryceSnyder the difference between an expression and a statement? Less typing? Fewer vertical lines consumed? Greater expressive power through succinctness and density of representation? Better semantics through the includes word? Take your pick. –  ErikE Commented Jul 18, 2019 at 15:21
  • 3 The benefit for me is, i can use the array from an external config source and after the array is changed externally the code still works. –  vindom Commented Jan 11, 2021 at 9:25
  • This is my preferred option, these blocks of case options seem crazy, includes can use the original array instead of extracting elements individually. –  Jeremy Commented May 16, 2021 at 9:08
  • 1 This is a pretty reliable option, the only drawback is that it isn't as readable as a switch statement. –  Andrew Knackstedt Commented May 16, 2021 at 17:04

My situation was something akin to:

The default case always entered. If you're running into a similar multi-case switch statement issue, you're looking for this:

Mike K's user avatar

Adding and clarifying Stefano's answer , you can use expressions to dynamically set the values for the conditions in switch, e.g.:

So in your problem, you could do something like:

Although it is so much DRY ...

Bernardo Dal Corno's user avatar

  • not yet tested but it would be interesting to modify varName inside the case expression, expect that varName is cached thou. –  Valen Commented Jan 27, 2018 at 3:22

In Node.js it appears that you are allowed to do this:

This makes for much more compact code in some cases.

Automatico's user avatar

  • 3 I think the syntax is the same as other JS environments. –  Afshin Mehrabani Commented Sep 1, 2015 at 11:02
  • 1 @AfshinMehrabani It might be, I have only tested it in nodejs context. –  Automatico Commented Sep 1, 2015 at 12:09
  • Yes. I like save vertical space! –  Channel Commented Mar 26, 2020 at 16:42

Here is one more easy-to-use switch case statement. which can fulfill your requirement. We can use the find method in the switch statement to get the desire output.

Shoaib Arif's user avatar

I use it like this:

Sergey Volkov's user avatar

  • You don't need to use the g flag, since you're only using the regexes once and throwing them away. In fact, if you were keeping them outside the function, the g flag would harm you by trying to match from a non-0 index on subsequent .test( s. I also fixed a typo where the switch case was on sensor variable and not true constant for matching boolean expressions. See the edit. –  Mihail Malostanidis Commented Feb 3, 2019 at 1:42
  • I used this format to test against file types. Ex: case /officedocument/.test(type) && /presentation/.test(type): iconClass = "far fa-file-powerpoint red"; break; –  tbone849 Commented Feb 20, 2020 at 1:32
  • This is probably the best method of checking the input. See next comment for suggested edit. –  Andrew Knackstedt Commented May 16, 2021 at 17:56
  • typescriptlang.org/play?#code/… –  Andrew Knackstedt Commented May 16, 2021 at 17:56

Some interesting methods. For me the best way to solve is using .find .

You can give an indication of what the multiple cases are by using a suitable name inside your find function.

Other answers are more suitable for the given example but if you have multiple cases to me this is the best way.

Scott O'Dea's user avatar

  • I like this approach. It also play's nicely with ESlint and other code formatters –  Clifford Fajardo Commented Nov 18, 2021 at 21:29

It depends. Switch evaluates once and only once. Upon a match, all subsequent case statements until 'break' fire no matter what the case says.

var onlyMen = true; var onlyWomen = false; var onlyAdults = false; (function(){ switch (true){ case onlyMen: console.log ('onlymen'); case onlyWomen: console.log ('onlyWomen'); case onlyAdults: console.log ('onlyAdults'); break; default: console.log('default'); } })(); // returns onlymen onlywomen onlyadults <script src="https://getfirebug.com/firebug-lite-debug.js"></script>

Ronnie Smith's user avatar

  • Historically, switch is a variation of the (in)famous goto statement. The idea is that you go to one of these labels, and then continue. That is, the labels represent entry points; if you want to exit, you have to do it yourself, with either the break statement or possibly a return statement if you’re inside a function. –  Manngo Commented Sep 16, 2021 at 2:37

You can use the ' in ' operator... It relies on the object/hash invocation, so it's as fast as JavaScript can be.

ZEE's user avatar

  • how does this relate to switch? can you clarify it? –  Bernardo Dal Corno Commented Dec 6, 2017 at 14:52
  • why would you want to make your code "hard to read". The first thing I was told as a programmer was to write code with the mindset that the next person reading your code is an axe wielding serial killer and he hates not being able to understand code. –  MattE Commented Apr 15, 2018 at 15:17
  • Hi Matt... I'm presenting it here as a proof of concept... anyway this form provides you more funcionality and flexibility... and you only use it if you want... or if you find a constrain in your usual form of doing things... consider ir as one more tool in your programmer toolbox... –  ZEE Commented Apr 16, 2018 at 16:12

You can do this:

or just a single line of code:

a little improvement from ErikE's answer

Dedy Abdillah's user avatar

I can see there are lots of good answers here, but what happens if we need to check more than 10 cases? Here is my own approach:

Aravinda Meewalaarachchi's user avatar

  • 5 This is abuse of the switch statement. Just if (accessDenied.includes(varName)) return 'Access Denied!'; return 'Access Allowed.' is more than enough. –  Mihail Malostanidis Commented Feb 2, 2019 at 13:55

The problem with the above approaches, is that you have to repeat the several case s every time you call the function which has the switch . A more robust solution is to have a map or a dictionary .

Here is an example:

// The Map, divided by concepts var dictionary = { timePeriod: { 'month': [1, 'monthly', 'mensal', 'mês'], 'twoMonths': [2, 'two months', '2 months', 'bimestral', 'bimestre'], 'trimester': [3, 'trimesterly', 'quarterly', 'trimestral'], 'semester': [4, 'semesterly', 'semestral', 'halfyearly'], 'year': [5, 'yearly', 'annual', 'ano'] }, distance: { 'km': [1, 'kms', 'kilometre', 'kilometers', 'kilometres'], 'mile': [2, 'mi', 'miles'], 'nordicMile': [3, 'Nordic mile', 'mil (10 km)', 'Scandinavian mile'] }, fuelAmount: { 'ltr': [1, 'l', 'litre', 'Litre', 'liter', 'Liter'], 'gal (imp)': [2, 'imp gallon', 'imperial gal', 'gal (UK)'], 'gal (US)': [3, 'US gallon', 'US gal'], 'kWh': [4, 'KWH'] } }; // This function maps every input to a certain defined value function mapUnit (concept, value) { for (var key in dictionary[concept]) { if (key === value || dictionary[concept][key].indexOf(value) !== -1) { return key } } throw Error('Uknown "'+value+'" for "'+concept+'"') } // You would use it simply like this mapUnit("fuelAmount", "ltr") // => ltr mapUnit("fuelAmount", "US gal") // => gal (US) mapUnit("fuelAmount", 3) // => gal (US) mapUnit("distance", "kilometre") // => km // Now you can use the switch statement safely without the need // to repeat the combinations every time you call the switch var foo = 'monthly' switch (mapUnit ('timePeriod', foo)) { case 'month': console.log('month') break case 'twoMonths': console.log('twoMonths') break case 'trimester': console.log('trimester') break case 'semester': console.log('semester') break case 'year': console.log('year') break default: throw Error('error') }

João Pimentel Ferreira's user avatar

One of the possible solutions is:

Jackkobec's user avatar

  • Q pls which #ecma is this? –  Bruno Commented Jul 30, 2019 at 13:08
  • Hi there. This is ES6 –  Jackkobec Commented Jul 30, 2019 at 19:15

Cleaner way to handle that

You can do that for multiple values with the same result

Abraham's user avatar

If your case conditions are complex, many case value matches, or dynamic value match required, then it may be best to move that case matching logic to handler child functions.

In your case, if say you had thousands of usernames to match against for a security permissions check for example, this method is cleaner option, more extensible, exposing the high level multi-way branch logic without getting swamped in a long list of case statements.

Peter O Brien's user avatar

Another way of doing multiple cases in a switch statement, when inside a function:

function name(varName){ switch (varName) { case 'afshin': case 'saeed': case 'larry': return 'Hey'; default: return 'Default case'; } } console.log(name('afshin')); // Hey

Morris S's user avatar

Just change the switch condition approach:

Stefano Favero's user avatar

  • 2 If you put true as the switch expression, in the "case" statement(s) you can evaluate whatever you want provided you return a boolean –  Stefano Favero Commented Feb 2, 2017 at 8:24
  • 1 I think what he meant is that you can put an expression inside the function, who will evaluate and return a dynamic value for the case, thus allowing all sorts of complex conditions –  Bernardo Dal Corno Commented Dec 6, 2017 at 14:57
  • For this @StefanoFavero note you dont actually need a function, just (expression) in parenthesis, and the return value must be the input. See my answer –  Bernardo Dal Corno Commented Dec 6, 2017 at 15:01
  • why you minused it?? I advocate this solution because it provides a flexibility for complex conditions. Even if you dont like funcs as conditions, you may replace them with you multiple conditions such as switch(true) { case (var1 === 0 && var2 === true): {} } –  Oleksiy Nikonov Commented Jun 16, 2019 at 8:11

The switch statement is used to select one of many code blocks to execute based on a condition

  • the value in the switch expression is compared to the different values provided
  • if there is a match the code block related to it will be executed
  • if there is no match the default block is executed

NOTE: It must be noted that if the break statement is omitted then the next block will be executed as well even if they does not match with switch expression. So don't forget to add the break statement at the end of each code block if you don't want to get the specified behaviour

A practical example: the following code returns the current day of the week in strings based on an integer (provided by 'new Date().getDay()')

the code samples were taken from W3Schools

Yeshwin Verma's user avatar

  • this doesn't answer the specific question the user posted. –  bioin4 Commented Jun 2, 2023 at 1:17

Kirandeep Singh's user avatar

  • 4 classic jquery inclusion :) –  ptim Commented Jul 8, 2016 at 0:02
  • 4 This is not how the switch statement is supposed to work. It’s just case "1": , not case (num = "1"): . –  Sebastian Simon Commented Feb 1, 2017 at 21:11
  • Why not put day value inside case and document.getElementById("result").innerHTML = .... outside the switch and add the day value result at the end? –  Steffo Dimfelt Commented Aug 22, 2018 at 9:00
  • @Xufox I love how he literally overwrites num but it still works because the switch has already been evaluated and the assignment yields the value. This is programming by mutation/machine learning at its finest. –  Mihail Malostanidis Commented Feb 2, 2019 at 14:15

You could write it like this:

Felipe Skinner's user avatar

  • 8 This is the same answer as everyone else, i will fix the " that you forgot, but think about deleting this. –  Gaunt Commented Mar 11, 2016 at 15:16

For me this is the simplest way:

José Pérez Bautista's user avatar

  • How is this the “simplest” way? Just replace this with an if statement. –  Sebastian Simon Commented Mar 5, 2021 at 23:55
  • If yo uhave in the array 20 elements you'd need 20 if's. This way is good for many elements. –  José Pérez Bautista Commented Mar 7, 2021 at 12:04
  • Not at all.. Look, you already have 3 elements in your array. All you'd need is populate that array with the extra values. What Sebastian is saying here is that your switch acts exactly like an if statement so you are totally wrong, plus you did not even consider the case "2", you just assumed default is your "else". –  ZyDucksLover Commented Mar 23, 2021 at 14:52

Not the answer you're looking for? Browse other questions tagged javascript switch-statement or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Looking under the hood at the tech stack that powers multimodal AI
  • Featured on Meta
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
  • User activation: Learnings and opportunities
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Are these colored sets closed under multiplication?
  • Rich Mental Images
  • Convert base-10 to base-0.1
  • What makes amplifiers so expensive?
  • Coloring a function based on its monotonicity
  • How to prove this problem about ternary quadratic form?
  • Symbolic integral over real functions with interger parametres evaluates to complex numbers
  • Would a scientific theory of everything be falsifiable?
  • How to win a teaching award?
  • Reparing a failed joint under tension
  • QGIS Atlas: Export attribute table of atlas features as a CSV
  • Copyright on song first performed in public
  • Driving low power LEDs from pre-biased digital transistors
  • If someone threatens force to prevent another person from leaving, are they holding them hostage?
  • What's the strongest material known to humanity that we could use to make Powered Armor Plates?
  • crontab schedule on Alpine Linux runs on days it's not supposed to run on
  • How to make a soundless world
  • Cutting a curve through a thick timber without waste
  • Fantasy novel where a brother and sister go to a fantasy and travel with a one-armed warrior
  • Can I use a machine washing to clean neoprene wetsuits/socks/hoods/gloves if I use cold water, no spinning, no bleach and a gentle detergent?
  • Does the city of Springfield have a possible claim against the Trump/Vance campaign?
  • Would Dicyanoacetylene Make a Good Flamethrower Fuel?
  • Stretched space in math mode
  • How to see material properties (colors) in main view

javascript multiple assignment

IMAGES

  1. Multiple Variable Assignment in JavaScript

    javascript multiple assignment

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

    javascript multiple assignment

  3. Mastering JavaScript Assignment: A Comprehensive Guide

    javascript multiple assignment

  4. Review Our JavaScript Assignment Template

    javascript multiple assignment

  5. JavaScript interview question on Multiple Assignment

    javascript multiple assignment

  6. Assignment Operators in JavaScript

    javascript multiple assignment

VIDEO

  1. Includes VS Some In JavaScript #javascript #javascripttutorial #javascriptlearning #webdevelopment

  2. JavaScript Assignment Operators #basicsforbeginners #javascript #coding

  3. 4. Comment in javascript

  4. JavaScript: Multiple Imports With Same Name ❓ #javascript #javascriptdeveloper #javascriptlearning

  5. #JavaScript : Multiple Catch Block

  6. JavaScript Recap: Assignment Operators

COMMENTS

  1. Multiple left-hand assignment with JavaScript

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

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

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

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

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

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

  6. JavaScript multiple assignment

    Learn how a = b = 2 works in JavaScript. Then test what you learned with interview questions. coderanx. articles. Artur Carvalho. 2021-03-25. 5 questions. JavaScript multiple assignment. In JavaScript, you can assign multiple variables in the same line of code: // prettier-ignore var a = 1, b = 2; console.log(a, b); // 1 2.

  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. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  8. multiple assignment javascript

    In JavaScript, multiple assignment refers to the ability to assign values to multiple variables in a single statement. This feature is particularly useful when you want to assign values from an array, object, or another iterable to multiple variables at once. Here are examples of multiple assignment in JavaScript: ### 1. Array Destructuring ...

  9. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

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

  11. How to declare multiple Variables in JavaScript?

    Using Destructuring Assignment. You can also use de-structuring assignments to declare multiple variables in one line and assign values to them. Syntax: const [var1, var2, var3] = [val1, val2, val3]; Example: In this example, we are declaring three different variable by destructuring them at once.

  12. Assign Multiple Variables to the Same Value in JavaScript

    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. ... Destructuring assignment syntax is a javascript expression that helps us to unpack values from arrays or objects into different variables. For example ...

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

    Right. In the example posted, it's creating a worthless array, only to use destructuring, to assign local variables. It's 100% worthless. Just assign the variables as variables are normally assigned. In React, we call a function (this is important) that returns an array of 2 values.

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

  15. Expressions and operators

    Primary expressions. Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.

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

  17. Multiplication assignment (*=)

    Multiplication assignment (*=) The multiplication assignment (*=) operator performs multiplication on the two operands and assigns the result to the left operand. Try it. Syntax. js. x *= y. Description. x *= y is equivalent to x = x * y, except that the expression x is only evaluated once. Examples.

  18. Object.assign()

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

  19. Multiple variable assignment with Javascript

    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; Here's an example where all three variables are assigned initially with the ...

  20. Switch statement for multiple cases in JavaScript

    I definitely prefer this version. Fall through is a bug-prone feature of switch ... case.It's too easy to forget a break statement, and if you use fall through intentionally, those forgotten break statements can be very hard to spot. This method lookup version also has lots of great features that switch ... case lacks, such as dynamic extensibility, or the ability to completely replace the ...