• View all errors
  • JSLint errors
  • JSHint errors
  • ESLint errors
  • View all options
  • JSLint options
  • JSHint options
  • ESLint options

Bad assignment

This warning has existed in two forms across the three main linters. It was introduced in the original version of JSLint and has remained in all three tools ever since.

In JSLint and JSHint the warning given has always been "Bad assignment"

In ESLint the warning has always been "Invalid left-hand side in assignment"

The situations that produce the warning have not changed despite changes to the text of the warning itself.

When do I get this error?

The "Bad assignment" error (and the alternative "Invalid left-hand side in assignment" error) are thrown when JSLint, JSHint or ESLint encounters an assignment expression in which the left-hand side is a call expression . In the following example we have an if statement with an assignment expression where you would normally expect a conditional:

JSLint also raises this warning when it encounters an assignment to a property of the arguments object . In this example we attempt to define an x property:

Why do I get this error?

In the case of assignment to a function call this error is raised to highlight a fatal reference error . Your code will throw an error in all environments if you do not resolve this issue. It makes no sense to assign a value to a call expression. The return value will be a literal value (such as a string or number) or an object reference, neither of which can be directly assigned to. Imagine it as if you're trying to do 123 = 234 .

If you're receiving the warning in this situation the chances are you were actually trying to perform a comparison rather than an assignment. If that's the case just ensure you're using a comparison operator such as === instead of the assignment operator = :

In the case of assignment to a property of an arguments object this error is raised to highlight a bad practice . The arguments object is notoriously difficult to work with and has behaviour that differs significantly between "normal" and "strict" mode. JSLint has numerous warnings related to abuse of the arguments object but if you're receiving the "Bad assignment" error the chances are you can use a normal variable instead:

In JSHint 1.0.0 and above you have the ability to ignore any warning with a special option syntax . Since this message relates to a fatal reference error you cannot disable it.

In ESLint this error is generated by the Esprima parser and can therefore not be disabled.

About the author

This article was written by James Allardice, Software engineer at Tesco and orangejellyfish in London. Passionate about React, Node and writing clean and maintainable JavaScript. Uses linters (currently ESLint) every day to help achieve this.

Follow me on Twitter  or  Google+

This project is supported by orangejellyfish , a London-based consultancy with a passion for JavaScript. All article content is available on GitHub under the Creative Commons Attribution-ShareAlike 3.0 Unported licence.

Have you found this site useful?

Please consider donating to help us continue writing and improving these articles.

  • 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

JS Tutorial

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

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

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

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

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

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

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

Right Shift Assignment Example

The >>>= operator.

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

Unsigned Right Shift Assignment Example

The &= operator.

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

Bitwise AND Assignment Example

The |= operator.

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

Bitwise OR Assignment Example

The ^= operator.

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

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

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

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

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

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

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

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

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

[email protected]

Top Tutorials

Top references, top examples, get certified.

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

DEV Community

DEV Community

Emmanuel Fordjour  Kumah

Posted on Feb 6, 2022

What you should know about the Logical Assignment Operators in JavaScript

Hello World, every year, new features get added to the JavaScript language.This enables developers write better code which translates into awesome products.

In 2021, the Logical assignment operators were added to the language. Its main objective is to assign values to variables. In this post, we will learn how to effectively utilize the logical assignment operators. Let's get started.

The Logical assignment operators

ES2021 introduced three logical assignment operators:

  • Logical OR assignment operator ( ||= )
  • Logical AND assignment operator ( &&= )
  • Nullish coalesing assignment operator ( ??= )

The Logical assignment operators combine the logical operators and assignment expression. If you have forgotten what Logical operators are, here is my post on Logical Operators to help refresh your mind.

Alright, now let's discuss the Logical OR assignment operator ( ||= )

What is the logical OR assignment operator

The logical OR assignment operator (||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy

The syntax is as below

In the syntax, the ||= will only assign the value of y to x if x is falsy.

Let's take a look at the || operator first. The Logical OR operator || returns the * first * truthy value in an expression.

Consider an example below

The output will be Guest .

  • In the example above, the firstName variable is an empty string "" , and the noName variable is a string ( a string stores a sequence of characters).
  • Empty strings "" are considered falsy values while non-empty strings(eg. "emma" ) are truthy values.
  • Because the || operator returns the first truthy value , the value stored in the noName variable (ie. Guest ) will logged to the console.

Note that : 0 , null , undefined , NaN and "" are classified as falsy values.

Assigning a value to a variable using the ||= operator.

Consider a situation where you want to assign a truthy value to a variable storing a falsy value

Let's see how you can achieve that using the logical OR assignment operator ( ||= )

You can do this (long method)

Let's understand the code above

  • The expression on the right : firstName || noName is evaluated first.
  • Since the || operator returns the first truthy value, it will return the value Guest
  • Using the = (assignment operator), the value Guest is then assigned to the firstName variable which has a falsy value
  • Now, anytime we console.log(firstName) , we get the value Guest

The example above can be simplified using the logical OR assignment operator ( ||= ).

The output will be

-The truthy value of 28 will be assigned to the age variable which has a falsy value

  • The age now has a value of 28

You can also assign a truthy value to a property in an object if the property is falsy . Take a look at the code below

In the example above

  • The || operator evaluates the expression and returns the firsty truthy value ( "emma" )
  • The truthy value is now assigned to the userDetails.username property since userDetails.username is falsy

If the first operand is a truthy value, the logical OR assignment operator ( ||= ) will** not assign the value of the second operand to the first. **

Consider the code below

  • Because the userDetails.userName property is truthy , the second operand was not evaluated

In summary, the x ||= y will assign the value of y to x if x is falsy .

Using the Logical AND assignment operator ( &&= )

Sometimes you may want to assign a value to a variable even if the initial variable has a value. This is where the logical AND assignment operator ( &&= ) comes in.

What is the logical AND assignment operator ?

The logical AND assignment operator only assigns y to x if x is truthy

* The syntax is as below *

  • if the operand on the left side is truthy , the value of y is then assigned to x

Let's see how this was done previously

The output will be efk .

  • The if evaluates the condition in the parenthesis ()
  • If the condition is true then the expression inside the curly braces {} gets evaluated
  • Because the firstName is truthy , we assign the value of userName to firstName .

Using &&= in the same example as above

  • Because firstName is a truthy value, the value of userName is now assigned to firstName

The &&= operator is very useful for changing values. Consider the example below

  • userDetails.lastName is a truthy value hence the right operand Fordjour is assigned to it.

In the code below, we given an object, and our task is to change the id to a random number between 1 and 10.

Let's see how that can be done using the &&=

The output will vary depending on the random number returned, here is an example.

In summary, the &&= operator assigns the value of the right operand to the left operand if the left operand is truthy

The nullish coalescing assignment operator ( ??= )

The nullish coalescing assignment operator only assigns y to x if x is null or undefined .

Let's see how to use the nullish coalescing assignment operator

  • The firstName variable is undefined
  • We now assign the value of the right operand to firstName
  • firstName now has the value of Emmanuel .

Adding a missing property to an object

  • The userDetails.userName is undefined hence nullish
  • The nullish coalescing assignment operator ??= then assigns the string Guest to the userDetails.userName
  • Now the userDetails object has property userName .
  • The logical OR assignment (x ||= y) operator only assigns y to x if x is falsy .
  • The logical AND assignment (x &&=y) operator will assign y to x if x is truthy
  • The nullish coalescing assignment operator will assign y to x if x is undefined or null .

I trust you have learnt something valuable to add to your coding repository. Is there anything that wasn't clear to you ? I would love to read your feedback on the article.

Writing with love from Ghana. Me daa se (Thank you)

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ganeshyadav3142 profile image

GraphQl with Apollo Server and usage of Query, Aliases,Arguments, Fragments (Part 2)

Ganesh Yadav - Dec 24 '23

mkobimbo profile image

How to create email templates in django

Martin Kobimbo - Dec 27 '23

gervg profile image

Newbie Anew

Gervin Guevarra - Dec 27 '23

tankala profile image

This week pip Trends newsletter

Tankala Ashok - Dec 23 '23

Once suspended, efkumah will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, efkumah will be able to comment and publish posts again.

Once unpublished, all posts by efkumah will become hidden and only accessible to themselves.

If efkumah is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Emmanuel Fordjour Kumah.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag efkumah:

efkumah consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging efkumah will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

The Real Bad Parts

By @johnkpaul, johnkpaul.com/empirejs, what's bad but not so bad.

from Bad Parts: Appendix B - JavaScript: The Good Parts

  • type coersion
  • continue/switch

How often do these issues come up?

how many with bugs have you wrangled?

The real bad parts

  • difficult concepts to grasp in the javascript language
  • high blog post to understanding ratio
  • what we might understand, but can't easily explain to others
  • How does this work?

How does prototypal inheritance work?

  • How does scope and hoisting work?

5 different ways to set this

"method" call, baseless function call, using apply, constructor with new.

  • => fat arrow

Fat Arrow =>

What on earth is prototypal inheritance.

What is inheritance...really?

Is it classes ?

Is it blueprints ?

Is it super ?

No, none of these

This is what we really care about

Write code once, use in multiple situations

prototypal inheritance makes this easy

don't think about new , super , and extends

don't even think about javascript's prototype property

Prototypal inheritance is about fallbacks

Not all js environments have Object.create

But we have a solution for < IE9

prototype is double speak

  • prototype #1 - property on a function
  • fallbackOfObjectsCreatedWithNew would be better
  • prototype #2 - internal reference of every object
  • ES6 now calls this dunderproto (__proto__)

What does new do?

  • not necessary

Scoping: breaking the principle of least surprise

Only functions can create scope.

  • Coffeescript has do keyword

ES6 adds let

One of these is not like the other, how does hoisting work.

Only easy rule - if there's no name, it's a expression

If there is a name, it depends on context

  • this can be set in 5 6 different ways
  • prototypal inheritance is based on fallbacks
  • only a function can define a new scope (until let)
  • hoisting moves source code around before interpretation
  • depending on who you ask

johnkpaul.com

Home

5 JavaScript Bad Coding Habits to Unlearn Right Now

When reading JavaScript code, have you ever had the feeling:

  • that you barely understand what the code does?
  • the code uses lots of JavaScript tricks?
  • the naming and coding style are rather random?

These are the signs of bad coding habits.

In this post, I describe 5 common bad coding habits in JavaScript. And importantly I will present my actionable recommendations on how to get rid of these habits.

Before I go on, let me recommend something to you.

The path to becoming good at JavaScript isn't easy... but fortunately with a good teacher you can shortcut.

Take "Modern JavaScript From The Beginning 2.0" course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount!

1. Don't use implicit type conversion

JavaScript is a loosely typed language. If used correctly, this is a benefit because of the flexibility it gives you.

Most of the operators + - * / == (but not === ) when working with operands of different types use implicit conversion of types.

The statements if (condition) {...} , while(condition) {...} implicitly transform the condition to a boolean.

The following examples rely on the implicit conversion of types. I bet you feel the confusion:

Relying excessively on the implicit type conversion is a bad habit. First of all, it makes your code less stable in edge cases. Secondly, you increase the chance to introduce a bug that is difficult to reproduce and fix.

Let's implement a function that gets the property of an object. If the property does not exist, the function returns a default value:

getProp() reads the value of the name property, which is 'Batman' .

What about trying to access isVillian property:

That's an error. Even if the hero 's property isVillian is false , the function getProp() returns the incorrect true .

It happens because the verification of property existence relies on implicit conversion to a boolean by the if (!object[propertyName]) {...} .

These kind of errors are difficult to spot. To fix the function, verify explicitely the type of the value:

object[propertyName] === undefined verifies exactly if the property accessor evaluates to undefined .

Do you know other ways to verify the property existence in an object? If so, leave a comment below!

Side note: the section 4. suggests to avoid using directly undefined . So the above solution can be improved in favor of in operator:

Here's my advice: whenever possible, do not use implicit type conversion. Instead, make sure that variables and function parameters always have the same type. Use explicit type conversion when necessary.

A list of best practices:

  • Always use strict equality operator === to perform comparisons
  • Don't use loose equality operator ==
  • Addition operator operand1 + operand2 : both operands should be numbers or both strings
  • Arithmetic operators - * / % ** : both operands should be numbers
  • if (condition) {...} , while (condition) {...} , etc statements: condition should be a boolean

You might say that this approach requires writing more code... You're right! But with an explicit approach, you control the behavior of your code. Plus, the explicitness increases readability.

2. Don't use old JavaScript tricks

What's interesting about JavaScript is its creators weren't expecting the language to become so popular.

The complexity of the applications built on JavaScript was increasing faster than the language evolution. This situation forced developers to use JavaScript hacks and workarounds, just to make things work.

A classic example is searching whether an array contains an item. I've never liked to use array.indexOf(item) !== -1 to check the presence of an item.

ECMAScript 2015 and beyond are way more powerful. You can safely refactor a lot of tricks by using new language features.

Refactor array.indexOf(item) !== -1 in favor of the new ES2015 method array.includes(item) .

Follow my compiled list of refactorings to remove old hacks from your JavaScript code.

3. Don't pollute the function scope

Before ES2015, JavaScript variables where function scoped. Because of that, you might developed a bad habit of declaring all the variables as function scoped.

Let's look at an example:

The variables index , item and length are function scoped. But these variables pollute the function scope because they are necessary only inside the for() block scope.

With the introduction of block scope variables let and const , you should limit the life of your variables as much as possible.

Let's clean up the function scope:

index and item variables are limited to for() cycle block scope. length was moved near the place of its usage.

The refactored code is easier to understand because the variables are not spread across the entire function scope. They exist near the place of usage.

Define the variables in the block scope they are used:

if block scope

For block scope, 4. try to avoid undefined and null.

A variable not yet assigned with value is evaluated to undefined . For example:

count variable is defined, but not yet initialized with a value. JavaScript implicitly assigns to it undefined . When accessing a non-existing property hero.city , undefined is returned also.

Why is using directly undefined a bad habit? Because when you start comparing against undefined , you're working with variables in an uninitialized state.

Variables, object properties, arrays must be initialized with values before using them!

JavaScript offers a lot of possibilities to avoid comparing with undefined .

Property existence

Object's default properties, default function parameter.

null is an indicator of a missing object.

You should strive to avoid returning null from functions, and more importantly, call functions with null as an argument.

As soon as null appears in your call stack, you have to check for its existence in every function that potentially can access null . It's error-prone.

Try to write code that does not involve null . Possible alternatives are try/catch mechanism, the usage of default objects.

Tony Hoare, the inventor of ALGOL, once stated:

I call it my billion-dollar mistake... [...] I was designing the first comprehensive type system for references in an object-oriented language. [...] But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

The post "The worst mistake of computer science" goes in-depth why null is damaging the quality of your code.

5. Don't use a casual coding style. Enforce a standard

What could be more daunting than reading code that has a random coding style? You never know what to expect!

What if the codebase contains different coding styles of many developers? An assorted character graffiti wall.

The same coding style across the entire team and the application codebase is a requirement. It's a boost for the code readability.

Examples of useful coding styles:

  • Airbnb JavaScript Style Guide
  • Google JavaScript Style Guide

But I'll be honest with you. I'm lazy. When I'm on a deadline, or I'm about to commit before going home - I might "forget" about styling my code.

“Myself lazy” says: leave the code as is, update it later. But later means never.

I recommend to automate the process of coding style verification:

  • Install eslint
  • Configure eslint with a coding style that's best for you
  • Set a pre-commit hook that runs eslint verification before committing.

Start with eslint-prettier-husky-boilerplate .

6. Conclusion

Writing quality and clean code requires discipline, overcome bad coding habits.

JavaScript is a permissive language, with a lot of flexibility. But you have to pay attention to what features you use. My recommendation is to avoid implicit type conversions and reduce the usage of undefined and null .

The language is evolving quite fast these days. Identify tricky code, and refactor it to use the latest JavaScript features.

A consistent coding style across the codebase benefits readability.

Good coding skills are always a win solution.

What other bad coding habits in JavaScript do you know?

Like the post? Please share!

Dmitri Pavlutin

About Dmitri Pavlutin

Popular posts.

IMAGES

  1. Use Destructuring Assignment In Javascript

    bad assignment javascript

  2. JavaScript ReferenceError

    bad assignment javascript

  3. The Destructuring Assignment in JavaScript with practical examples

    bad assignment javascript

  4. Invalid Left Hand Side In Assignment

    bad assignment javascript

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

    bad assignment javascript

  6. 15 Bad Things About JavaScript That None Tells You

    bad assignment javascript

VIDEO

  1. Design a responsive user sign-in and sign-up page using HTML, CSS, JavaScript, and Bootstrap

  2. Fixing JavaScript Date

  3. JavaScript Exponentiation Assignment #coding #javascript #tutorial #shorts

  4. Bad audience TikTok

  5. bad news assignment 315

  6. 3 More Signs of Bad Software Engineers

COMMENTS

  1. Bad Assignment (JavaScript)

    1 Answer Sorted by: 0 You can only assign values to variables and properties of objects. const foo = 1; const bar = {}; bar.baz = 2; You can't assign a value to the result of calling a function: alert ("Hello, world!") = 3; // Nonsense! … because it isn't designed to be something you can store data in.

  2. SyntaxError: invalid assignment left-hand side

    This might be due to a mismatch of an assignment operator and an equality operator, for example. While a single = sign assigns a value to a variable, the == or === operators compare a value. Examples Typical invalid assignments js if (Math.PI + 1 = 3 || Math.PI + 1 = 4) { console.log("no way!");

  3. javascript

    1 = is an assignment operator. == is a comparison operator. Even better, use !foodHere instead of foodHere == false. Up to you to figure out what ! means. - Evan Trimboli Feb 12, 2014 at 10:08 they say nothing about a console.log ;-) - Philipp Sander Feb 12, 2014 at 10:20 Add a comment 4 Answers Sorted by: 3

  4. JSLint Error Explanations

    The "Bad assignment" error (and the alternative "Invalid left-hand side in assignment" error) are thrown when JSLint, JSHint or ESLint encounters an assignment expression in which the left-hand side is a call expression. In the following example we have an if statement with an assignment expression where you would normally expect a conditional:

  5. Nullish coalescing assignment (??=)

    Description Nullish coalescing assignment short-circuits, meaning that x ??= y is equivalent to x ?? (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator.

  6. Assignment (=)

    Syntax js x = y Parameters x A valid assignment target, including an identifier or a property accessor. It can also be a destructuring assignment pattern. y An expression specifying the value to be assigned to x. Return value The value of y. Exceptions ReferenceError

  7. ReferenceError: invalid assignment left-hand side

    What went wrong? There was an unexpected assignment somewhere. This might be due to a mismatch of a assignment operator and a comparison operator, for example. While a single " = " sign assigns a value to a variable, the " == " or " === " operators compare a value.

  8. What went wrong? Troubleshooting JavaScript

    Go to the tab that you've got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines: The first line of the error message is: Uncaught TypeError: guessSubmit.addeventListener is not a function number-game-errors.html:86:15

  9. Assignment operators

    The basic assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the following definitions and examples. Name. Shorthand operator.

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

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

  12. Articles in need of attention

    bad-assignment.md - Bad assignment \n; Expected a small integer or 'false' and instead saw '{a}' \n; Expected an operator and instead saw '{a}' \n; get-set-es5.md - get/set are ES5 features \n; Missing property name \n; Expected to see a statement and instead saw a block \n; invoked-declaration.md - Function declarations are not invocable \n

  13. What you should know about the Logical Assignment Operators in JavaScript

    The output will be Guest.. In the example above, the firstName variable is an empty string "", and the noName variable is a string ( a string stores a sequence of characters).; Empty strings "" are considered falsy values while non-empty strings(eg."emma") are truthy values. Because the || operator returns the first truthy value, the value stored in the noName variable (ie.

  14. 7 Tips to Handle undefined in JavaScript

    Fortunately, JavaScript offers a bunch of ways to determine if the object has a specific property: obj.prop !== undefined: compare against undefined directly. typeof obj.prop !== 'undefined': verify the property value type. obj.hasOwnProperty ('prop'): verify whether the object has its own property.

  15. Javascript: The Real Bad Parts

    The real bad parts. difficult concepts to grasp in the javascript language; high blog post to understanding ratio; what we might understand, but can't easily explain to others; The real bad parts. How does this work? How does prototypal inheritance work? How does scope and hoisting work? 5 different ways to set this "method" call; baseless ...

  16. 5 JavaScript Bad Coding Habits to Unlearn Right Now

    In this post, I describe 5 common bad coding habits in JavaScript. And importantly I will present my actionable recommendations on how to get rid of these habits. Before I go on, let me recommend something to you. The path to becoming good at JavaScript isn't easy... but fortunately with a good teacher you can shortcut.

  17. TypeError: invalid assignment to const "x"

    There are multiple options to fix this error. Check what was intended to be achieved with the constant in question. Rename If you meant to declare another constant, pick another name and re-name. This constant name is already taken in this scope. js const COLUMNS = 80; const WIDE_COLUMNS = 120; const, let or var?

  18. Unsigned right shift (>>>)

    Description Unlike other arithmetic and bitwise operators, the unsigned right shift operator does not accept BigInt values. This is because it fills the leftmost bits with zeroes, but conceptually, BigInts have an infinite number of leading sign bits, so there's no "leftmost bit" to fill with zeroes.

  19. JavaScript error reference

    English (US) JavaScript error reference Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors.