no-useless-assignment

Disallow variable assignments when the value is not used

Wikipedia describes a “dead store” as follows:

In computer programming, a local variable that is assigned a value but is not read by any subsequent instruction is referred to as a dead store .

“Dead stores” waste processing and memory, so it is better to remove unnecessary assignments to variables.

Also, if the author intended the variable to be used, there is likely a mistake around the dead store. For example,

  • you should have used a stored value but forgot to do so.
  • you made a mistake in the name of the variable to be stored.

Rule Details

This rule aims to report variable assignments when the value is not used.

Examples of incorrect code for this rule:

Examples of correct code for this rule:

This rule will not report variables that are never read. Because it’s clearly an unused variable. If you want it reported, please enable the no-unused-vars rule.

When Not To Use It

If you don’t want to be notified about values that are never read, you can safely disable this rule.

Related Rules

  • no-unused-vars

This rule was introduced in ESLint v9.0.0-alpha.1.

Further Reading

Avatar image for en.wikipedia.org

  • Rule source
  • Tests source

S1854 Remove this useless assignment to a local variable, when used in range operator

A false positive is generated when the variable is only used in a range operator.

versions used :

  • Sonarlint 4.23.0.19399
  • Visual Studio 2019 Community Edition 16.6.4

minimal code sample to reproduce:

The following code does NOT generate the same warning:

Hello @pvk ,

Thank you for reporting this issue. I can confirm it’s a False Positive.

We already have issue on GitHub with similar case to track it.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

SonarQube displaying to 'remove this useless assignment to local variable'

Why is SonarQube giving this error? How should I fix it? Their rule page does not specify the solution,

Remove this useless assignment to local variable validateAddressRequest.

enter

 Answers

This site says that the error occurs when:

A value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.

On the first line of the if block, you assign to validateAddressRequest , but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

Declare validateAddressRequest only when calling convertToValidateRequest instead.

Note that you almost certainly don't need the type annotation - if Typescript knows that convertToValidateRequest returns a ValidateAddressRequest already, there's no need to do so again with the new variable. You can do so if you think it's unclear otherwise, or if you don't have type Intellisense, but it may just be noise.

If you were declaring the variable with let so as to enable assignment to it in the future, keep in mind that it's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest , give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going to be reassigned.

caylasarinag

freddiejarretk

Darren Jones

A Guide to Variable Assignment and Mutation in JavaScript

Share this article

A Guide to Variable Assignment and Mutation in JavaScript

Variable Assignment

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

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

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

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

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

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

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

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

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

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

variables like a box

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

variables like a reference

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

variables referencing the same value

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

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

Some gotchas when working with objects

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

This assignment means that the variable ghostbusters references an object:

variables referencing different objects

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

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

variables referencing different objects

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

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

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

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

Variable reassignment using let

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

variables referencing different values

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

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

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

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

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

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

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

variables cannot reference another variable

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

variables referencing values

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

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

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

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

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

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

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

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

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

Mutability and objects in JavaScript

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

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

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

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

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

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

variables referencing the same object

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

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

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

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

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

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

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

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

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

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

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

variables referencing different objects

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

Changes don't affect the other object

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

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

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

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

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

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

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

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

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

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

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

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

What is the difference between variable assignment and mutation in JavaScript?

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

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

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

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

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

How can I prevent mutation in JavaScript?

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

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

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

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

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

What is the MutationObserver API in JavaScript?

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

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

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

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

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

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

In JavaScript, asynchronous programming allows multiple things to happen at the same time. When a variable is assigned or mutated in an asynchronous function, it can lead to unexpected results if other parts of the code are relying on the value of the variable. This is because the variable assignment or mutation may not have completed before the other parts of the code run. To handle this, JavaScript provides several features, such as promises and async/await, to help manage asynchronous code.

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

SitePoint Premium

  • Skip to main content
  • Select language
  • Skip to search
  • Destructuring assignment

Unpacking values from a regular expression match

Es2015 version, invalid javascript identifier as a property name.

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 on the left-hand side of the assignment to define what values to unpack from the sourced variable.

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

Array destructuring

Basic variable assignment, assignment separate from declaration.

A variable can be assigned its value via destructuring separate from the variable's declaration.

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is 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:

Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

Note that a SyntaxError will be thrown if a trailing comma is used on the left-hand side with a rest element:

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.

Object destructuring

Basic assignment, assignment without declaration.

A variable can be assigned its value with destructuring separate from its declaration.

The ( .. ) around the assignment statement is required syntax 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.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ..) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

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.

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .

Setting a function parameter's default value

Es5 version, nested object and array destructuring, for of iteration and destructuring, unpacking fields from objects passed as function parameter.

This unpacks the id , displayName and firstName from the user object and prints them.

Computed object property names and destructuring

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

Rest in Object Destructuring

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

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

Specifications

Browser compatibility.

[1] Requires "Enable experimental Javascript features" to be enabled under `about:flags`

Firefox-specific notes

  • Firefox provided a non-standard language extension in JS1.7 for destructuring. This extension has been removed in Gecko 40 (Firefox 40 / Thunderbird 40 / SeaMonkey 2.37). See bug 1083498 .
  • Starting with Gecko 41 (Firefox 41 / Thunderbird 41 / SeaMonkey 2.38) and to comply with the ES2015 specification, parenthesized destructuring patterns, like ([a, b]) = [1, 2] or ({a, b}) = { a: 1, b: 2 } , are now considered invalid and will throw a SyntaxError . See Jeff Walden's blog post and bug 1146136 for more details.
  • Assignment operators
  • "ES6 in Depth: Destructuring" on hacks.mozilla.org

Document Tags and Contributors

  • Destructuring
  • ECMAScript 2015
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Sonar's Useless Assignment Error in Swift

Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in Swift

Abstract: Learn how to resolve SonarQube's 'Remove Useless Assignment of Local Variable' error in Swift by understanding its cause and using different workarounds.

Solving Sonar's "Remove Useless Assignment to Local Variable" Error in Swift

Sonar is a popular tool used for code analysis and review. It helps developers identify and fix issues in their code, making it more readable, maintainable, and secure. One common issue that Sonar flags is the "Remove Useless Assignment to Local Variable" error in Swift. This error occurs when a local variable is assigned a value that is not used in the code. In this article, we will discuss how to solve this error in Swift.

Understanding the Error

To understand the error, let's consider an example:

In this example, we declare two local variables, x and y. We assign the value 5 to x and then calculate the value of y by multiplying x by 2. However, we never use the value of x again in the code. Therefore, Sonar flags the assignment of x as a useless assignment.

Solving the Error

To solve the error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. In the above example, we can remove the declaration of x, as it is not used in the code:

Alternatively, we can use the value of x in the code:

In this example, we print the value of x to the console, ensuring that it is used in the code.

Using Sonar to Identify Useless Assignments

Sonar can help us identify useless assignments in our code. To do this, we need to configure Sonar to analyze our Swift code. We can do this by installing the SonarSwift plugin and configuring it to analyze our project. Once we have done this, Sonar will flag any useless assignments in our code, allowing us to fix them.

The "Remove Useless Assignment to Local Variable" error in Swift is a common issue that Sonar flags. To solve this error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. Sonar can help us identify useless assignments in our code, allowing us to fix them and improve the quality of our code.

Remove Useless Assignment to Local Variable

Supported Languages

Tags: :  Swift SonarQube Software Development

Latest news

  • ROS Service Not Called: Troubleshooting Service Availability
  • Empty Arguments Causing Segfault in C++: A Common Issue in main.cpp
  • Making Debit Card Payments with Stripe in Python: No Selenium Required
  • Creating DIVs: Does fit-content allow growth?
  • Understanding Next.js: Behavior of request.nextUrl.pathname
  • Developing a Cell Phone Non-Interact App with React and Astro: Current Progress
  • Error in Implementing GameActivity Update with google-services-ads:19.820
  • Sharing Featured Images from WordPress Websites: Internal Image RSS
  • Accidentally Locked Samsung S21 FE: Bypass 4-Hour Wait and Unlock Early
  • Incorrect Map Population in Mongoose: A Common Issue and Solutions
  • Opencv Crashing Randomly After Certain Seconds in Visual Studio C++
  • Py 'not recognized yet' in Visual Studio: Python vs. Powershell
  • Arduino: Splitting Serial String with delimiters
  • Memory Leak in C Function using NumPy and C-API: A Possible Solution
  • Flutter: Firebase Android Project Setup Fails - Expected Firebase Version 1.7.1, but 1.9.0 Installed
  • Understanding Clone/Duplicate ReadStream Behavior in Node.js
  • Protecting Wordpress Plugin Code: An Option for Download Concerns
  • Binding Vue Model (v-model) to Different Attributes of an Object: One Works, the Other Doesn't
  • Multiplying Corresponding Values from Multiple MySQL Tables into One Table
  • Unity UniWebView: Handling Webview Closure on Android when Pressing Home Button
  • MySQL: Removing Duplicate Purchase Records with Counter
  • Customizing Markdown Formatted QLabel List Indent
  • Understanding Default Value Prop Overriding in React/MobX
  • Troubleshooting <audio> Tags: Non-Autoplay and Refresh Page Issues
  • Why SED's Append Command Empties a File When Appending Text Inside Blocks/Sections
  • GitHub Pages: Empty Site Despite config.yml
  • Resolving 'deadcode' errors in Flutter: The Case of Disabled Button Opacity
  • Debugging Kotlin iOS Main Code using Xcode (Xcode 15.4)
  • Resizing Images for Confusion Training in Keras: Tree Segmentation
  • Controlling Time: HTML Page Inclusion Rendering in WebView2 for WinApp SDK
  • Next.js: Favicon not showing up in Chrome
  • A Newbie's Journey to Create a Private DnD Session App with Android Studio
  • Try Showing Array DataTable using HTML in Laravel Project
  • Unable to Alter RoomDB without Restarting Activity: A Solution
  • Estimating Reliability Distributions with Kumaraswamy Inverse Weibull: An OptimConvergence Approach
  • United States
  • United Kingdom

User-defined variables in JavaScript

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

Matthew Tyson

Contributor, |

User-defined variables in JavaScript

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

All about JavaScript variables

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

What is a user-defined variable in JavaScript?

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

  • How to work with string variables

What you need to know about variable scope

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

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

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

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

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

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

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

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

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

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

Storing numbers in JavaScript variables

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

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

Storing strings in JavaScript variables

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

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

Storing Boolean values in JavaScript variables

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

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

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

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

Storing objects in JavaScript variables

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

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

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

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

Or, you could use an object literal:

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

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

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

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

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

Assigning variables with let and const

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

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

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

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

Working with string variable limits

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

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

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

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

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

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

Next read this:

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

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

Copyright © 2024 IDG Communications, Inc.

remove this useless assignment to variable javascript

More than 1 year has passed since last update.

remove this useless assignment to variable javascript

Rubocopエラー「Useless assignment to variable」の解決例

上記エラーを調べると、「使っていないローカル変数の定義がある」というエラーのようで 削除すれば解決するとの事でした。

しかし、今回はちゃんと使っている内容で、書き方の問題のようでした。 以下のように、if文などの後に 明示的に使用している記載が必要 とのことでした。

Register as a new user and use Qiita more conveniently

  • You get articles that match your needs
  • You can efficiently read back useful information
  • You can use dark theme

IMAGES

  1. javascript

    remove this useless assignment to variable javascript

  2. Remove this useless assignment to local variable Sonarqube

    remove this useless assignment to variable javascript

  3. Solutions For The Error "TypeError: Assignment To Constant Variable" In

    remove this useless assignment to variable javascript

  4. javascript

    remove this useless assignment to variable javascript

  5. javascript

    remove this useless assignment to variable javascript

  6. Remove this useless assignment to local variable Sonarqube

    remove this useless assignment to variable javascript

VIDEO

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

  2. Serious Sam Fusion 2017

  3. how to remove useless part from a book

  4. You are useless for this world

  5. Simplification of CFG

  6. Selenium IDE: Part III

COMMENTS

  1. javascript

    It's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest, give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going ...

  2. Sonar issue

    Here sonar is saying "Remove this useless assignment to local variable". How can I add to the list without initializing it with new keyword? Sonar comment is "Remove this useless assignment to local variable "listComments". "I went through below links but not getting my answer. Sonar complaining about useless assignment of local variable

  3. Remove this useless assignment to variable

    I am using SimpleDataTables JS Library and their minimal suggested implementation: const dataTable = new DataTable("#myTable"); In SC this throws me an Remove this useless assignment to variable "dataTable". and an Remove the declaration of the unused 'dataTable' variable. If I remove the assignement SC tells me to Either remove this useless object instantiation of "DataTable" or use it. In SC ...

  4. no-useless-assignment

    "Dead stores" waste processing and memory, so it is better to remove unnecessary assignments to variables. Also, if the author intended the variable to be used, there is likely a mistake around the dead store. For example, you should have used a stored value but forgot to do so. you made a mistake in the name of the variable to be stored.

  5. S1854 Remove this useless assignment to a local variable, when used in

    A false positive is generated when the variable is only used in a range operator. versions used : Sonarlint 4.23.0.19399 Visual Studio 2019 Community Edition 16.6.4 c# minimal code sample to reproduce: var prepTexts = "From here"; var test = prepTexts.IndexOf(" ", StringComparison.Ordinal)+1; //hits S1854 Remove this useless assignment to local variable var res= prepTexts[test..9]; //when the ...

  6. SonarQube displaying to 'remove this useless assignment to local variable'

    On the first line of the if block, you assign to validateAddressRequest, but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

  7. Sonar: Remove this useless assignment to variable "locale" #12472

    Delete the line locale = TranslatorContext.context.locale; JHipster Version(s) Current version. JHipster configuration Entity configuration(s) entityName.json files generated in the .jhipster directory Browsers and Operating System. Checking this box is mandatory (this is just to show you read everything)

  8. Unused parameter in array destructing #1019

    Remove the declaration of the unused 'key' variable. (javascript:UnusedVariable) Remove this useless assignment to local variable "key" (avascript:S1854) Expected behavior There shouldn't be an issue as I use the 2nd parameter. The text was updated successfully, but these errors were encountered:

  9. A Guide to Variable Assignment and Mutation in JavaScript

    In JavaScript, variable assignment refers to the process of assigning a value to a variable. For example, let x = 5; Here, we are assigning the value 5 to the variable x. On the other hand ...

  10. S1481 False Positive "Remove this useless assignment to local variable

    carldebilly changed the title S1481 False Positive S1481 False Positive "Remove this useless assignment to local variable 'x'" Feb 28, 2020. andrei-epure-sonarsource added this to background tasks (investigate, clarify) ... Remove this useless assignment to local variable S1854. We have Sonar Version 8.3.1 (build 34397) and C# plugin 8.6.1 ...

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

  12. JavaScript Best Practices— Bad Variable Declarations and ...

    Theoretically, since the JavaScript undefined value is a global variable, we may be able to overwrite it with some other value. However, we can write something like the following: var undefined ...

  13. Destructuring assignment

    The ( ..) around the assignment statement is required syntax 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. However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2} NOTE: Your ( ..) expression needs to be ...

  14. S1854 False Positive useless assignment to local variable #2760

    The warning is raised about the variable ports. public static s... Description The warning S1854 should not be thrown in the case that a variable is set a value, and might be updated in a try/catch block. ... S1854 False Positive useless assignment to local variable #2760. Closed jcurl opened this issue Nov 1, 2019 · 2 comments Closed

  15. Solving Sonar's 'Remove Useless Assignment of Local Variable' Error in

    To solve this error, we need to ensure that every local variable is used in the code. We can do this by either using the variable or removing its declaration. Sonar can help us identify useless assignments in our code, allowing us to fix them and improve the quality of our code. References. Remove Useless Assignment to Local Variable. Supported ...

  16. User-defined variables in JavaScript

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

  17. Useless assignment to local variable

    Precision: very-high. Tags: - maintainability. - external/cwe/cwe-563. Query suites: - csharp-security-and-quality.qls. Click to see the query in the CodeQL repository. A value is assigned to a local variable, but either that variable is never read later on, or its value is always overwritten before being read.

  18. Remove useless assignments to variables #16092

    We needlessly assignment variables in places where they aren't used. These assignments can be removed. == app/models/cloud_tenant.rb (3 issues) == 45: Useless assignment to variable - `created_clou...

  19. Why when I attempt to reassign a variable I receive the error, "remove

    In my program the play method is run multiple times. But since player is a local variable, the assignment has no effect, because it's not persistent across subsequent invocations of the play method. Java rightly complains about this. If you want to cycle between players there are multiple ways of doing so, but the easiest is to change your play method to accept the player as a parameter ...

  20. Rubocopエラー「Useless assignment to variable」の解決例

    Rubocopエラー「Useless assignment to variable」の解決例. 上記エラーを調べると、「使っていないローカル変数の定義がある」というエラーのようで 削除すれば解決するとの事でした。 しかし、今回はちゃんと使っている内容で、書き方の問題のようでした。

  21. remove this useless assignment to local variable c#

    2. The message is pretty straightforward: stopFyon = vehtran.CreateStopFactoryOrderNo(carOnlineData, maintainStopFactoryOrderNo, lastUpdatedBy); stopFyon = vehtran.CreateStopFactoryOrderNo(null, maintainStopFactoryOrderNo, lastUpdatedBy); The first assignment: is useless since another assignment is performed within the if statement right after ...