Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

Summary : in this tutorial, you will learn how to use JavaScript assignment operators to assign a value to a variable.

Introduction to JavaScript assignment operators

An assignment operator ( = ) assigns a value to a variable. The syntax of the assignment operator is as follows:

In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a .

The following example declares the counter variable and initializes its value to zero:

The following example increases the counter variable by one and assigns the result to the counter variable:

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the second assignment, the counter variable is 1 .

To make the code more concise, you can use the += operator like this:

In this syntax, you don’t have to repeat the counter variable twice in the assignment.

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

OperatorMeaningDescription
Assigns the value of to .
Assigns the result of plus to .
Assigns the result of minus to .
Assigns the result of times to .
Assigns the result of divided by to .
Assigns the result of modulo to .
Assigns the result of AND to .
Assigns the result of OR to .
Assigns the result of XOR to .
Assigns the result of shifted left by to .
Assigns the result of shifted right (sign preserved) by to .
Assigns the result of shifted right by to .

Chaining JavaScript assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.
  • Skip to main content
  • Select language
  • Skip to search
  • Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

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 Meaning

Simple assignment operator which assigns a value to a variable. The assignment operation evaluates to the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. See the example.

Addition assignment

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

Subtraction assignment

The subtraction assignment operator subtracts the value of the right operand from a variable and assigns the result to the variable. See the subtraction operator for more details.

Multiplication assignment

The multiplication assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable. See the multiplication operator for more details.

Division assignment

The division assignment operator divides a variable by the value of the right operand and assigns the result to the variable. See the division operator for more details.

Remainder assignment

The remainder assignment operator divides a variable by the value of the right operand and assigns the remainder to the variable. See the remainder operator for more details.

Exponentiation assignment

This is an experimental technology, part of the ECMAScript 2016 (ES7) proposal. Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future version of browsers as the spec changes.

The exponentiation assignment operator evaluates to the result of raising first operand to the power second operand. See the exponentiation operator for more details.

Left shift assignment

The left shift assignment operator moves the specified amount of bits to the left and assigns the result to the variable. See the left shift operator for more details.

Right shift assignment

The right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the right shift operator for more details.

Unsigned right shift assignment

The unsigned right shift assignment operator moves the specified amount of bits to the right and assigns the result to the variable. See the unsigned right shift operator for more details.

Bitwise AND assignment

The bitwise AND assignment operator uses the binary representation of both operands, does a bitwise AND operation on them and assigns the result to the variable. See the bitwise AND operator for more details.

Bitwise XOR assignment

The bitwise XOR assignment operator uses the binary representation of both operands, does a bitwise XOR operation on them and assigns the result to the variable. See the bitwise XOR operator for more details.

Bitwise OR assignment

The bitwise OR assignment operator uses the binary representation of both operands, does a bitwise OR operation on them and assigns the result to the variable. See the bitwise OR operator for more details.

Left operand with another assignment operator

In unusual situations, the assignment operator (e.g. x += y ) is not identical to the meaning expression (here x = x + y ). When the left operand of an assignment operator itself contains an assignment operator, the left operand is evaluated only once. For example:

Specifications

Specification Status Comment
Draft  
Standard  
Standard  
Standard Initial definition.

Browser compatibility

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
Feature Android Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
  • Arithmetic operators

Document Tags and Contributors

  • 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()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • 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 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

Ben Marshall

Ben Marshall

  • LinkedIn profile
  • GitHub profile
  • WordPress profile

What is ?= in JavaScript? Safe Assignment Operator Explained

Think of ?= as that safety net you didn’t know you needed—until now!

JavaScript never ceases to amaze, right? Just when you think you’ve mastered its quirks and features, a new operator pops up. This time, it’s the ?= operator—a little symbol with the potential to make our coding lives a bit easier.

The ?= operator is like an unexpected safety net in your code. It’s especially useful when handling tricky assignments or working with async functions. Let’s dive into what the ?= operator is and how it works.

The ?= operator is also known as the safe assignment operator . It assigns values only if the variable on the left side is defined. This is useful for async/await, destructuring, and complex assignments.

In this example, error and response get values only if the fetch operation returns something defined. This helps prevent errors and keeps your code clean.

The ?= operator, or safe assignment operator, assigns a value only if the variable on the left side is already defined. If the variable is undefined, the assignment doesn’t happen.

While = assigns values unconditionally, and ??= assigns only if the left-hand side is null or undefined, ?= assigns values only when the variable is already defined. It’s more selective in how it assigns values.

Use ?= when you want to assign values safely, particularly in complex assignments or when working with async/await syntax. It’s useful in situations where you want to avoid overriding defined variables accidentally.

Yes, ?= works well with async/await. It can help manage asynchronous operations by ensuring that assignments happen only when the returned values are defined.

?= is rolling out in modern JavaScript engines. Check browser compatibility before using it in production.

Understanding the ?= Operator

What is the = operator.

The ?= operator, also known as the safe assignment operator , simplifies conditional assignments. It only assigns a value if the variable on the left-hand side is already defined. This helps avoid overwriting existing values or causing errors with undefined variables.

A Simple Explanation

Imagine you have a door that only opens if someone is already inside. If the room (variable) is empty, the door stays closed (no assignment). But if someone is there, the door opens, allowing you to make changes (assign a value). This keeps things safe and prevents unwanted changes.

Here’s a basic example of the ?= operator in action:

In this example, the first assignment doesn’t happen because value is undefined. Once value is defined, the ?= operator prevents it from being overwritten.

Why Use the ?= Operator?

The ?= operator adds an extra layer of safety to your code. It’s useful in situations where assignments depend on existing values. By using ?= , you can stop unintended changes and keep your code running smoothly.

The Difference Between ?= , = , and ??=

Comparing = and =.

The = operator assigns a value to a variable, no matter what. If the variable already has a value, = will replace it.

With = , you can end up overwriting values you want to keep. This is where ?= comes in. Unlike = , ?= only assigns a value if the variable already has something in it. If the variable is empty or undefined, ?= does nothing, leaving the original value alone.

Comparing ?= and ??=

The ??= operator works differently. It assigns a value only if the variable is null or undefined. This is useful when you want a fallback value, but it won’t protect against overwriting other values.

In contrast, ?= only assigns when the variable already has a value. It’s a small difference, but it makes a big impact in the right situations.

Where Should You Use ?= ?

The ?= operator is useful when you need to keep your code safe from unintended changes. It works well in complex applications where assignments rely on existing values. Here are a few situations where ?= shines:

  • Asynchronous Code: When working with async/await , you often deal with values that aren’t always defined. The ?= operator assigns values only if the variables are already set, which helps avoid errors.
  • Fallback Logic: If you have fallback logic, ?= keeps the original value intact if it’s already there. This prevents overwriting data you want to keep.
  • Form Handling: When dealing with form inputs, ?= preserves user data unless you want to change it.

Let’s look at a real-world example where ?= is used in an async function:

In this example, ?= makes sure that error and response only get values if await fetch() returns something defined. This keeps the original values safe and avoids unexpected behavior.

Quick Use Cases for ?=

  • Handling asynchronous API calls without overwriting existing data.
  • Protecting user inputs in forms from being accidentally replaced.
  • Safeguarding fallback values in complex conditional logic.

A Deeper Dive: Working with Async/Await

How = works with async/await.

In modern JavaScript, async/await is the go-to for handling asynchronous tasks. The ?= operator is a good match for this pattern. It safely assigns values from promises, without worrying about undefined variables.

Simplifying Error Handling

One of the powerful benefits of ?= is its ability to reduce the need for try-catch blocks. Instead of wrapping your asynchronous code in try-catch, you can handle potential errors more cleanly by using ?= to check for values before assignment.

Using ?= Instead of Try-Catch

Consider the typical try-catch block used to handle errors in asynchronous code:

With ?= , you can simplify this to:

By using ?= , your code becomes cleaner and more readable, reducing the need for extensive error handling while keeping your application stable.

Preventing Errors with API Calls

In this example, ?= makes sure that userData only updates if the API call works. If there’s an error, the original userData stays the same. This keeps your app stable and prevents unwanted changes.

Why Use ?= with Async/Await?

Using ?= with async/await helps you handle data safely. It updates variables only when valid data comes in. This is important when dealing with critical data, like user information. You don’t want to overwrite good data with something undefined.

Want to learn more about async/await? Check out this guide .

Browser Support and Compatibility

Can you use = everywhere.

The ?= operator is new in JavaScript. It’s available in modern browsers, but not everywhere. Before using it in production, check browser compatibility to avoid issues.

Current Browser Compatibility

Right now, ?= works in the latest versions of Chrome, Firefox, and Edge. It’s not supported in older browsers or some less updated ones. If your project needs to work across many browsers, you’ll need a polyfill or another way to handle safe assignments.

  • Supported: Chrome (latest), Firefox (latest), Edge (latest)
  • Not Supported: Internet Explorer, Safari (older versions)
  • Check Compatibility: Use tools like Can I Use to verify support for your target browsers.

The ?= operator is a useful tool in modern JavaScript. It helps you handle assignments safely, avoiding unexpected overwrites and keeping your code stable. Whether you’re working with async/await, handling user data, or managing complex logic, ?= adds an extra layer of protection to your code.

As JavaScript evolves, staying on top of new features helps you write cleaner, more efficient code. Try using ?= in your next project and see how it simplifies your assignments.

  • Share on Facebook
  • Email this Page
  • Share on LinkedIn

Share your thoughts Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

Latest Articles

Delete .env files in github, gone without a trace.

Delete .env files in GitHub and remove all traces. Protect your project by erasing sensitive data and securing your repo.

SOLID React Best Practices for Scalable Apps

Apply SOLID principles to your React apps for cleaner, scalable code. Learn best practices with simple examples.

Learn how the new ?= operator in JavaScript simplifies code and prevents errors. Discover its benefits for async/await handling.

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

JavaScript Assignment Operators

A ssignment operators.

Assignment operators are used to assign values to variables in JavaScript.

Assignment Operators List

There are so many assignment operators as shown in the table with the description.

OPERATOR NAMESHORTHAND OPERATORMEANING
a+=ba=a+b
a-=ba=a-b
a*=ba=a*b
a/=ba=a/b
a%=ba=a%b
a**=ba=a**b
a<<=ba=a<<b
a>>=ba=a>>b
a&=ba=a&b
a|=ba=a | b
a^=ba=a^b

a&&=b

x && (x = y)

||=

x || (x = y)

??=

x ?? (x = y)

Below we have described each operator with an example code:

Addition assignment operator(+=).

The Addition assignment operator adds the value to the right operand to a variable and assigns the result to the variable. Addition or concatenation is possible. In case of concatenation then we use the string as an operand.

Subtraction Assignment Operator(-=)

The Substraction Assignment Operator subtracts the value of the right operand from a variable and assigns the result to the variable.

Multiplication Assignment Operator(*=)

The Multiplication Assignment operator multiplies a variable by the value of the right operand and assigns the result to the variable.

Division Assignment Operator(/=)

The Division Assignment operator divides a variable by the value of the right operand and assigns the result to the variable.

Remainder Assignment Operator(%=)

The Remainder Assignment Operator divides a variable by the value of the right operand and assigns the remainder to the variable.

Exponentiation Assignment Operator

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

Left Shift Assignment Operator(<<=)

This Left Shift Assignment O perator moves the specified amount of bits to the left and assigns the result to the variable.

Right Shift Assignment O perator(>>=)

The Right Shift Assignment Operator moves the specified amount of bits to the right and assigns the result to the variable.

Bitwise AND Assignment Operator(&=)

The Bitwise AND Assignment Operator uses the binary representation of both operands, does a bitwise AND operation on them, and assigns the result to the variable.

Btwise OR Assignment Operator(|=)

The Btwise OR Assignment Operator uses the binary representation of both operands, does a bitwise OR operation on them, and assigns the result to the variable.

Bitwise XOR Assignment Operator(^=)

The Bitwise XOR Assignment Operator uses the binary representation of both operands, does a bitwise XOR operation on them, and assigns the result to the variable.

Logical AND Assignment Operator(&&=)

The Logical AND Assignment assigns the value of  y  into  x  only if  x  is a  truthy  value.

Logical OR Assignment Operator( ||= )

The Logical OR Assignment Operator is used to assign the value of y to x if the value of x is falsy.

Nullish coalescing Assignment Operator(??=)

The Nullish coalescing Assignment Operator assigns the value of y to x if the value of x is null.

Supported Browsers: The browsers supported by all JavaScript Assignment operators are listed below:

  • Google Chrome
  • Microsoft Edge

JavaScript Assignment Operators – FAQs

What are assignment operators in javascript.

Assignment operators in JavaScript are used to assign values to variables. The most common assignment operator is the equals sign (=), but there are several other assignment operators that perform an operation and assign the result to a variable in a single step.

What is the basic assignment operator?

The basic assignment operator is =. It assigns the value on the right to the variable on the left.

What are compound assignment operators?

Compound assignment operators combine a basic arithmetic or bitwise operation with assignment. For example, += combines addition and assignment.

What does the += operator do?

The += operator adds the value on the right to the variable on the left and then assigns the result to the variable.

How does the *= operator work?

The *= operator multiplies the variable by the value on the right and assigns the result to the variable.

Can you use assignment operators with strings?

Yes, you can use the += operator to concatenate strings.

What is the difference between = and ==?

The = operator is the assignment operator, used to assign a value to a variable. The == operator is the equality operator, used to compare two values for equality, performing type conversion if necessary.

What does the **= operator do?

The **= operator performs exponentiation (raising to a power) and assigns the result to the variable.

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators
  • How to Strikethrough on Discord
  • Discord Launches End-To-End Encryption For Audio & Video Chats
  • iPadOS 18 is Now Available: Complete Features and How to Install
  • Microsoft’s Latest 365 Copilot Updates: Enhanced AI Tools for Excel, PowerPoint, and Teams
  • 10 Best PrimeWire Alternatives (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

TutorialsTonight Logo

JAVASCRIPT ASSIGNMENT OPERATORS

In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript.

Assignment Operators

In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

The assignment operators are used to assign value based on the right operand to its left operand.

The left operand must be a variable while the right operand may be a variable, number, boolean, string, expression, object, or combination of any other.

One of the most basic assignment operators is equal = , which is used to directly assign a value.

javascript assignment operator

Assignment Operators List

Here is the list of all assignment operators in JavaScript:

In the following table if variable a is not defined then assume it to be 10.

Operator Description Example Equivalent to
= a = 10 a = 10
+= a += 10 a = a + 10
-= a -= 10 a = a - 10
*= a *= 10 a = a * 10
/= a /= 10 a = a / 10
%= a %= 10 a = a % 10
**= a **= 2 a = a ** 2
<<= a <<= 1 a = a << 1
>>= a >>= 2 a = a >> 2
>>>= a >>>= 1 a = a >>> 1
&= a &= 4 a = a & 4
|= a |= 2 a = a | 2
^= a ^= 5 a = a ^ 5
&&= a &&= 3 a = a && 3
||= a ||= 4 a = a || 4
??= a ??= 2 a = a ?? 2

Assignment operator

The assignment operator = is the simplest value assigning operator which assigns a given value to a variable.

The assignment operators support chaining, which means you can assign a single value in multiple variables in a single line.

Addition assignment operator

The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand.

On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

Subtraction assignment operator

The subtraction assignment operator -= subtracts the value of the right operand from the value of the left operand and assigns the result to the left operand.

If the value can not be subtracted then it results in a NaN .

Multiplication assignment operator

The multiplication assignment operator *= assigns the result to the left operand after multiplying values of the left and right operand.

Division assignment operator

The division assignment operator /= divides the value of the left operand by the value of the right operand and assigns the result to the left operand.

Remainder assignment operator

The remainder assignment operator %= assigns the remainder to the left operand after dividing the value of the left operand by the value of the right operand.

Exponentiation assignment operator

The exponential assignment operator **= assigns the result of exponentiation to the left operand after exponentiating the value of the left operand by the value of the right operand.

Left shift assignment

The left shift assignment operator <<= assigns the result of the left shift to the left operand after shifting the value of the left operand by the value of the right operand.

Right shift assignment

The right shift assignment operator >>= assigns the result of the right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Unsigned right shift assignment

The unsigned right shift assignment operator >>>= assigns the result of the unsigned right shift to the left operand after shifting the value of the left operand by the value of the right operand.

Bitwise AND assignment

The bitwise AND assignment operator &= assigns the result of bitwise AND to the left operand after ANDing the value of the left operand by the value of the right operand.

Bitwise OR assignment

The bitwise OR assignment operator |= assigns the result of bitwise OR to the left operand after ORing the value of left operand by the value of the right operand.

Bitwise XOR assignment

The bitwise XOR assignment operator ^= assigns the result of bitwise XOR to the left operand after XORing the value of the left operand by the value of the right operand.

Logical AND assignment

The logical AND assignment operator &&= assigns value to left operand only when it is truthy .

Note : A truthy value is a value that is considered true when encountered in a boolean context.

Logical OR assignment

The logical OR assignment operator ||= assigns value to left operand only when it is falsy .

Note : A falsy value is a value that is considered false when encountered in a boolean context.

Logical nullish assignment

The logical nullish assignment operator ??= assigns value to left operand only when it is nullish ( null or undefined ).

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

What is the benefit of having the assignment operator return a value?

I'm developing a language which I intend to replace both Javascript and PHP. (I can't see any problem with this. It's not like either of these languages have a large install base.)

One of the things I wanted to change was to turn the assignment operator into an assignment command, removing the ability to make use of the returned value.

I know that this would mean that those one-line functions that C people love so much would no longer work. I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation.

Or is it? Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? (For any language that has such a concept.)

  • language-agnostic

billpg's user avatar

  • 12 JS and PHP do not have a large "install base"? –  mhr Commented Feb 13, 2014 at 12:33
  • 47 @mri I suspect sarcasm. –  Andy Hunt Commented Feb 13, 2014 at 12:41
  • 12 The only useful case I can remember is while((x = getValue()) != null) {} . Replacements will be uglier since you'll need to either use break or repeat the x = getValue assignment. –  CodesInChaos Commented Feb 13, 2014 at 13:04
  • 12 @mri Ooh no, I hear those two languages are just trivial things without any significant investment at all. Once the few people who insist on using JS see my language, they will switch over to mine and never have to write === again. I'm equally sure the browser makers will immediately roll out an update that includes my language alongside JS. :) –  billpg Commented Feb 13, 2014 at 14:58
  • 4 I would suggest to you that if your intention is to enhance an existing language and you intend it to be adopted widely then 100% backwards compatibility with the existing language is good. See TypeScript as an exemplar. If your intention is to provide a better alternative to an existing language then you have a much harder problem. A new language has to solve an existing realistic problem much much better than the existing language in order to pay for the cost of switching. Learning a language is an investment and it needs to pay off. –  Eric Lippert Commented Feb 13, 2014 at 18:57

9 Answers 9

Technically, some syntactic sugar can be worth keeping even if it can trivially be replaced, if it improves readability of some common operation. But assignment-as-expression does not fall under that. The danger of typo-ing it in place of a comparison means it's rarely used (sometimes even prohibited by style guides) and provokes a double take whenever it is used. In other words, the readability benefits are small in number and magnitude.

A look at existing languages that do this may be worthwhile.

  • Java and C# keep assignment an expression but remove the pitfall you mention by requiring conditions to evaluate to booleans. This mostly seems to work well, though people occasionally complain that this disallows conditions like if (x) in place of if (x != null) or if (x != 0) depending on the type of x .
  • Python makes assignment a proper statement instead of an expression. Proposals for changing this occasionally reach the python-ideas mailing list, but my subjective impression is that this happens more rarely and generates less noise each time compared to other "missing" features like do-while loops, switch statements, multi-line lambdas, etc.

However, Python allows one special case, assigning to multiple names at once: a = b = c . This is considered a statement equivalent to b = c; a = b , and it's occasionally used, so it may be worth adding to your language as well (but I wouldn't sweat it, since this addition should be backwards-compatible).

  • 5 +1 for bringing up a = b = c which the other answers do not really bring up. –  Leo Commented Feb 13, 2014 at 15:53
  • 6 A third resolution is to use a different symbol for assignment. Pascal uses := for assignment. –  Brian Commented Feb 13, 2014 at 19:08
  • 6 @Brian: Indeed, as does C#. = is assignment, == is comparison. –  Marjan Venema Commented Feb 13, 2014 at 19:47
  • 3 In C#, something like if (a = true) will throw a C4706 warning ( The test value in a conditional expression was the result of an assignment. ). GCC with C will likewise throw a warning: suggest parentheses around assignment used as truth value [-Wparentheses] . Those warnings can be silenced with an extra set of parentheses, but they are there to encourage explicitly indicating the assignment was intentional. –  Bob Commented Feb 13, 2014 at 22:27
  • 2 @delnan Just a somewhat generic comment, but it was sparked by "remove the pitfall you mention by requiring conditions to evaluate to booleans" - a = true does evaluate to a Boolean and is therefore not an error, but it also raises a related warning in C#. –  Bob Commented Feb 13, 2014 at 23:48
Are there any practical uses of the assignment operator's return value that could not be trivially rewritten?

Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value , and that is considered by many to be confusing.

Common usages are typically to make expressions compact:

has the semantics in C# of "convert z to the type of y, assign the converted value to y, the converted value is the value of the expression, convert that to the type of x, assign to x".

But we are already in the realm of impertative side effects in a statement context, so there's really very little compelling benefit to that over

Similarly with

being a shorthand for

Again, in the original code we are using an expression both for its side effects and its value, and we are making a statement that has two side effects instead of one. Both are smelly; try to have one side effect per statement, and use expressions for their values, not for their side effects.

I'm developing a language which I intend to replace both Javascript and PHP.

If you really want to be bold and emphasize that assignment is a statement and not an equality, then my advice is: make it clearly an assignment statement .

There, done. Or

or even better:

Or even better still

There's absolutely no way that any of those are going to be confused with x == 1 .

Eric Lippert's user avatar

  • 1 Is the world ready for non-ASCII Unicode symbols in programming languages? –  billpg Commented Feb 14, 2014 at 11:25
  • As much as I would love what you suggest, one of my goals is that most "well written" JavaScript can be ported over with little or no modification. –  billpg Commented Feb 14, 2014 at 11:44
  • 2 @billpg: Is the world ready ? I don't know -- was the world ready for APL in 1964, decades before the invention of Unicode? Here's a program in APL that picks a random permutation of six numbers out of the first 40: x[⍋x←6?40] APL required its own special keyboard, but it was a pretty successful language. –  Eric Lippert Commented Feb 14, 2014 at 15:17
  • @billpg: Macintosh Programmer's Workshop used non-ASCII symbols for things like regex tags or redirection of stderr. On the other hand, MPW had the advantage that the Macintosh made it easy to type non-ASCII characters. I must confess some puzzlement as to why the US keyboard driver doesn't provide any decent means of typing any non-ASCII characters. Not only does Alt-number entry require looking up character codes--in many applications it doesn't even work. –  supercat Commented Feb 14, 2014 at 18:20
  • Hm, why would one prefer to assign "to the right" like a+b*c --> x ? This looks strange to me. –  Ruslan Commented Aug 21, 2015 at 10:49

Many languages do choose the route of making assignment a statement rather than an expression, including Python:

and Golang:

Other languages don't have assignment, but rather scoped bindings, e.g. OCaml:

However, let is an expression itself.

The advantage of allowing assignment is that we can directly check the return value of a function inside the conditional, e.g. in this Perl snippet:

Perl additionally scopes the declaration to that conditional only, which makes it very useful. It will also warn if you assign inside a conditional without declaring a new variable there – if ($foo = $bar) will warn, if (my $foo = $bar) will not.

Making the assignment in another statement is usually sufficient, but can bring scoping problems:

Golang heavily relies on return values for error checking. It therefore allows a conditional to take an initialization statement:

Other languages use a type system to disallow non-boolean expressions inside a conditional:

Of course that fails when using a function that returns a boolean.

We now have seen different mechanisms to defend against accidental assignment:

  • Disallow assignment as an expression
  • Use static type checking
  • Assignment doesn't exist, we only have let bindings
  • Allow an initialization statement, disallow assignment otherwise
  • Disallow assignment inside a conditional without declaration

I've ranked them in order of ascending preference – assignments inside expressions can be useful (and it's simple to circumvent Python's problems by having an explicit declaration syntax, and a different named argument syntax). But it's ok to disallow them, as there are many other options to the same effect.

Bug-free code is more important than terse code.

amon's user avatar

  • +1 for "Disallow assignment as an expression". The use-cases for assignment-as-an-expression don't justify the potential for bugs and readability issues. –  poke Commented Feb 14, 2014 at 17:00

You said "I figured (with little evidence beyond my personal experience) that the vast majority of times this happened, it was really intended to be comparison operation."

Why not FIX THE PROBLEM?

Instead of = for assignment and == for equality test, why not use := for assignment and = (or even ==) for equality?

If you want to make it harder for the programmer to mistake assignment for equality, then make it harder.

At the same time, if you REALLY wanted to fix the problem, you would remove the C crock that claimed booleans were just integers with predefined symbolic sugar names. Make them a different type altogether. Then, instead of saying

you force the programmer to write:

The fact is that assignment-as-an-operator is a very useful construct. We didn't eliminate razor blades because some people cut themselves. Instead, King Gillette invented the safety razor.

John R. Strohm's user avatar

  • 2 (1) := for assignment and = for equality might fix this problem, but at the cost of alienating every programmer who didn't grow up using a small set of non-mainstream languages. (2) Types other than bools being allows in conditions isn't always due to mixing up bools and integers, it's sufficient to give a true/false interpretation to other types. Newer language that aren't afraid to deviate from C have done so for many types other than integers (e.g. Python considers empty collections false). –  user7043 Commented Feb 13, 2014 at 13:38
  • 1 And regarding razor blades: Those serve a use case that necessitates sharpness. On the other hand, I'm not convinced programming well requires assigning to variables in the middle of an expression evaluation. If there was a simple, low-tech, safe and cost efficient way to make body hair disappear without sharp edges, I'm sure razor blades would have been displaced or at least made much more rare. –  user7043 Commented Feb 13, 2014 at 13:40
  • 1 @delnan: A wise man once said "Make it as simple as possible, but no simpler." If your objective is to eliminate the vast majority of a=b vs. a==b errors, restricting the domain of conditional tests to booleans and eliminating the default type conversion rules for <other>->boolean gets you just about all the way there. At that point, if(a=b){} is only syntactically legal if a and b are both boolean and a is a legal lvalue. –  John R. Strohm Commented Feb 13, 2014 at 15:07
  • Making assignment a statement is at least as simple as -- arguably even simpler than -- the changes you propose, and achieves at least as much -- arguably even more (doesn't even permit if (a = b) for lvalue a, boolean a, b). In a language without static typing, it also gives much better error messages (at parse time vs. run time). In addition, preventing "a=b vs. a==b errors" may not be the only relevant objective. For example, I'd also like to permit code like if items: to mean if len(items) != 0 , and that I'd have to give up to restrict conditions to booleans. –  user7043 Commented Feb 13, 2014 at 15:14
  • 1 @delnan Pascal is a non-mainstream language? Millions of people learned programming using Pascal (and/or Modula, which derives from Pascal). And Delphi is still commonly used in many countries (maybe not so much in yours). –  jwenting Commented Feb 14, 2014 at 9:39

To actually answer the question, yes there are numerous uses of this although they are slightly niche.

For example in Java:

The alternative without using the embedded assignment requires the ob defined outside the scope of the loop and two separate code locations that call x.next().

It's already been mentioned that you can assign multiple variables in one step.

This sort of thing is the most common use, but creative programmers will always come up with more.

Tim B's user avatar

  • Would that while loop condition deallocate and create a new ob object with every loop? –  user3932000 Commented May 3, 2017 at 22:33
  • @user3932000 In that case probably not, usually x.next() is iterating over something. It is certainly possible that it could though. –  Tim B Commented May 4, 2017 at 8:18
  • I can't get the above to compile unless I declare the variable beforehand and remove the declaration from inside. It says Object cannot be resolved to a variable. –  William Jarvis Commented Apr 15, 2021 at 16:42

Since you get to make up all the rules, why now allow assignment to turn a value, and simply not allow assignments inside conditional steps? This gives you the syntactic sugar to make initializations easy, while still preventing a common coding mistake.

In other words, make this legal:

But make this illegal:

Bryan Oakley's user avatar

  • 2 That seems like a rather ad-hoc rule. Making assignment a statement and extending it to allow a = b = c seems more orthogonal, and easier to implement too. These two approach disagree about assignment in expressions ( a + (b = c) ), but you haven't taken sides on those so I assume they don't matter. –  user7043 Commented Feb 13, 2014 at 13:01
  • "easy to implement" shouldn't be much of a consideration. You are defining a user interface -- put the needs of the users first. You simply need to ask yourself whether this behavior helps or hinders the user. –  Bryan Oakley Commented Feb 13, 2014 at 13:05
  • if you disallow implicit conversion to bool then you don't have to worry about assignment in conditions –  ratchet freak Commented Feb 13, 2014 at 13:08
  • Easier to implement was only one of my arguments. What about the rest? From the UI angle, I might add that IMHO incoherent design and ad-hoc exceptions generally hinders the user in grokking and internalising the rules. –  user7043 Commented Feb 13, 2014 at 13:10
  • @ratchetfreak you could still have an issue with assigning actual bools –  jk. Commented Feb 13, 2014 at 13:25

By the sounds of it, you are on the path of creating a fairly strict language.

With that in mind, forcing people to write:

instead of:

might seem an improvement to prevent people from doing:

when they meant to do:

but in the end, this kind of errors are easy to detect and warn about whether or not they are legal code.

However, there are situations where doing:

does not mean that

will be true.

If c is actually a function c() then it could return different results each time it is called. (it might also be computationally expensive too...)

Likewise if c is a pointer to memory mapped hardware, then

are both likely to be different, and also may also have electronic effects on the hardware on each read.

There are plenty of other permutations with hardware where you need to be precise about what memory addresses are read from, written to and under specific timing constraints, where doing multiple assignments on the same line is quick, simple and obvious, without the timing risks that temporary variables introduce

Michael Shaw's user avatar

  • 4 The equivalent to a = b = c isn't a = c; b = c , it's b = c; a = b . This avoids duplication of side effects and also keeps the modification of a and b in the same order. Also, all these hardware-related arguments are kind of stupid: Most languages are not system languages and are neither designed to solve these problems nor are they being used in situations where these problems occur. This goes doubly for a language that attempts to displace JavaScript and/or PHP. –  user7043 Commented Feb 13, 2014 at 13:04
  • delnan, the issue wasn't are these contrived examples, they are. The point still stands that they show the kinds of places where writing a=b=c is common, and in the hardware case, considered good practice, as the OP asked for. I'm sure they will be able to consider their relevance to their expected environment –  Michael Shaw Commented Feb 13, 2014 at 13:51
  • Looking back, my problem with this answer is not primarily that it focuses on system programming use cases (though that would be bad enough, the way it's written), but that it rests on assuming an incorrect rewriting. The examples aren't examples of places where a=b=c is common/useful, they are examples of places where order and number of side effects must be taken care of. That is entirely independent. Rewrite the chained assignment correctly and both variants are equally correct. –  user7043 Commented Feb 13, 2014 at 13:58
  • @delnan: The rvalue is converted to the type of b in one temp, and that is converted to the type of a in another temp. The relative timing of when those values are actually stored is unspecified. From a language-design perspective, I would think it reasonable to require that all lvalues in a multiple-assignment statement have matching type, and possibly to require as well that none of them be volatile. –  supercat Commented Feb 13, 2014 at 19:17

The greatest benefit to my mind of having assignment be an expression is that it allows your grammar to be simpler if one of your goals is that "everything is an expression"--a goal of LISP in particular.

Python does not have this; it has expressions and statements, assignment being a statement. But because Python defines a lambda form as being a single parameterized expression , that means you can't assign variables inside a lambda. This is inconvenient at times, but not a critical issue, and it's about the only downside in my experience to having assignment be a statement in Python.

One way to allow assignment, or rather the effect of assignment, to be an expression without introducing the potential for if(x=1) accidents that C has is to use a LISP-like let construct, such as (let ((x 2) (y 3)) (+ x y)) which might in your language evaluate as 5 . Using let this way need not technically be assignment at all in your language, if you define let as creating a lexical scope. Defined that way, a let construct could be compiled the same way as constructing and calling a nested closure function with arguments.

On the other hand, if you are simply concerned with the if(x=1) case, but want assignment to be an expression as in C, maybe just choosing different tokens will suffice. Assignment: x := 1 or x <- 1 . Comparison: x == 1 . Syntax error: x = 1 .

wberry's user avatar

  • 1 let differs from assignment in more ways than technically introducing a new variable in a new scope. For starters, it has no effect on code outside the let 's body, and therefore requires nesting all code (what should use the variable) further, a significant downside in assignment-heavy code. If one was to go down that route, set! would be the better Lisp analogue - completely unlike comparison, yet not requiring nesting or a new scope. –  user7043 Commented Feb 13, 2014 at 21:36
  • @delnan: I'd like to see a combination declare-and-assign syntax which would prohibit reassignment but would allow redeclaration, subject to the rules that (1) redeclaration would only be legal for declare-and-assign identifiers, and (2) redeclaration would "undeclare" a variable in all enclosing scopes. Thus, the value of any valid identifier would be whatever was assigned in the previous declaration of that name. That would seem a little nicer than having to add scoping blocks for variables that are only used for a few lines, or having to formulate new names for each temp variable. –  supercat Commented Feb 14, 2014 at 3:08

Indeed. This is nothing new, all the safe subsets of the C language have already made this conclusion.

MISRA-C, CERT-C and so on all ban assignment inside conditions, simply because it is dangerous.

There exists no case where code relying on assignment inside conditions cannot be rewritten.

Furthermore, such standards also warns against writing code that relies on the order of evaluation. Multiple assignments on one single row x=y=z; is such a case. If a row with multiple assignments contains side effects (calling functions, accessing volatile variables etc), you cannot know which side effect that will occur first.

There are no sequence points between the evaluation of the operands. So we cannot know whether the subexpression y gets evaluated before or after z : it is unspecified behavior in C. Thus such code is potentially unreliable, non-portable and non-conformant to the mentioned safe subsets of C.

The solution would have been to replace the code with y=z; x=y; . This adds a sequence point and guarantees the order of evaluation.

So based on all the problems this caused in C, any modern language would do well to both ban assignment inside conditions, as well as multiple assignments on one single row.

Not the answer you're looking for? Browse other questions tagged language-agnostic syntax operators or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network

Hot Network Questions

  • Ubuntu 24.04.1 not booting up - is it disk damage?
  • Threshold percentage for power ratings of resistors?
  • Why does lottery write "in trust" on winner's cheque?
  • Why is thermal conductivity of thermal interface materials so low?
  • What effect will a planet’s narcotic atmosphere have on sound of music at rave parties?
  • Can there exists a model of ZFC with permutation that sends successor infinite stages to their predecessors?
  • Why is the "scan backwards" method of parsing right-associative operators considered to be anti-pattern? What alternatives are recommended?
  • Buying property in Switzerland
  • How does NASA calculate trajectory at planetary atmosphere entry
  • How is Miles’s glitching related to his limited understanding of his place in the Spider-Society?
  • Red dwarfs and red giants
  • Where does the argument included below to "Prove the fundamental group of a Topological Group is abelian" fail for non-group topological spaces?
  • Relational-join Excel tables
  • Why can't I modify/repair Enclave Hellfire Power Armour Pieces with the AWKCR mod installed?
  • Will running a dehumidifier in a basement impact room temperature?
  • Can Ubuntu 24.04 be compromised?
  • BSS138 level shifter - blocking current flow when high-side supply is not connected?
  • Change style of True/False everywhere
  • What to consider as reviewer before dooming a paper
  • Tomatoes measured in quarts
  • CDF of a discrete random variable piecewise-constant?
  • How do cafes prepare matcha in a foodsafe way, if a bamboo whisk/chasen cannot be sanitized in a dishwasher?
  • How can I connect heavy-gauge wire to a 20A breaker?
  • Why doesn't reductio ad absurdum mean everything follows?

javascript assignment operator return value

JS Reference

Html events, html objects, other references, javascript operators reference, javascript operators.

Operators are used to assign values, compare values, perform arithmetic operations, and more.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators

Comparison Operators

Logical operators.

  • Conditional Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5 , the table below explains the arithmetic operators:

Oper Name Example Results Try it
+ Addition x = y + 2 y=5, x=7
- Subtraction x=y-2 y=5, x=3
* Multiplication x=y*2 y=5, x=10
** Exponentiation
x=y**2 y=5, x=25
/ Division x = y / 2 y=5, x=2.5
% Remainder x = y % 2 y=5, x=1
++ Pre increment x = ++y y=6, x=6
++ Post increment x = y++ y=6, x=5
-- Pre decrement x = --y y=4, x=4
-- Post decrement x = y-- y=4, x=5

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5 , the table below explains the assignment operators:

Oper Example Same As Result Try it
= x = y x = y x = 5
+= x += y x = x + y x = 15
-= x -= y x = x - y x = 5
*= x *= y x = x * y x = 50
/= x /= y x = x / y x = 2
%= x %= y x = x % y x = 0
: x: 45 size.x = 45 x = 45

Advertisement

JavaScript String Operators

The + operator, and the += operator can also be used to concatenate (add) strings.

Given that t1 = "Good " , t2 = "Morning" , and t3 = "" , the table below explains the operators:

Oper Example t1 t2 t3 Try it
+ t3 = t1 + t2 "Good " "Morning"  "Good Morning"
+= t1 += t2 "Good Morning" "Morning"

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x = 5 , the table below explains the comparison operators:

Oper Name Comparing Returns Try it
== equal to x == 8 false
== equal to x == 5 true
=== equal value and type x === "5" false
=== equal value and type x === 5 true
!= not equal x != 8 true
!== not equal value or type x !== "5" true
!== not equal value or type x !== 5 false
> greater than x > 8 false
< less than x < 8 true
>= greater or equal to x >= 8 false
<= less or equal to x <= 8

Conditional (Ternary) Operator

The conditional operator assigns a value to a variable based on a condition.

Syntax Example Try it
(condition) ? x : y (z < 18) ? x : y

Logical operators are used to determine the logic between variables or values.

Given that x = 6 and y = 3 , the table below explains the logical operators:

Oper Name Example Try it
&& AND (x < 10 && y > 1) is true
|| OR (x === 5 || y === 5) is false
! NOT !(x === y) is true

The Nullish Coalescing Operator (??)

The ?? operator returns the first argument if it is not nullish ( null or undefined ).

Otherwise it returns the second argument.

The nullish operator is supported in all browsers since March 2020:

Chrome 80 Edge 80 Firefox 72 Safari 13.1 Opera 67
Feb 2020 Feb 2020 Jan 2020 Mar 2020 Mar 2020

The Optional Chaining Operator (?.)

The ?. operator returns undefined if an object is undefined or null (instead of throwing an error).

The optional chaining operator is supported in all browsers since March 2020:

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.

Oper Name Example Same as Result Decimal Try it
& AND x = 5 & 1 0101 & 0001 0001 1
| OR x = 5 | 1 0101 | 0001 0101 5
~ NOT x = ~ 5 ~0101 1010 10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4
<< Left shift x = 5 << 1 0101 << 1 1010 10
>> Right shift x = 5 >> 1 0101 >> 1 0010 2
>>> Unsigned right x = 5 >>> 1 0101 >>> 1 0010 2

The table above uses 4 bits unsigned number. Since JavaScript uses 32-bit signed numbers, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 (~5) will return 11111111111111111111111111111010 (-6)

The typeof Operator

The typeof operator returns the type of a variable, object, function or expression:

Please observe:

  • The data type of NaN is number
  • The data type of an array is object
  • The data type of a date is object
  • The data type of null is object
  • The data type of an undefined variable is undefined

You cannot use typeof to define if a JavaScript object is an array or a date.

Both array and date return object as type.

The delete Operator

The delete operator deletes a property from an object:

The delete operator deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or functions.

The delete operator should not be used on the properties of any predefined JavaScript objects (Array, Boolean, Date, Function, Math, Number, RegExp, and String).

This can crash your application.

The Spread (...) Operator

The ... operator can be used to expand an iterable into more arguments for function calls:

The in Operator

The in operator returns true if a property is in an object, otherwise false:

Object Example

You cannot use in to check for array content like ("Volvo" in cars).

Array properties can only be index (0,1,2,3...) and length.

See the examples below.

Predefined Objects

The instanceof operator.

The instanceof operator returns true if an object is an instance of a specified object:

The void Operator

The void operator evaluates an expression and returns undefined . This operator is often used to obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without using the return value).

JavaScript Operator Precedence

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

JavaScript: The Definitive Guide, 6th Edition by David Flanagan

Get full access to JavaScript: The Definitive Guide, 6th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Assignment Expressions

JavaScript uses the = operator to assign a value to a variable or property. For example:

The = operator expects its left-side operand to be an lvalue: a variable or object property (or array element). It expects its right-side operand to be an arbitrary value of any type. The value of an assignment expression is the value of the right-side operand. As a side effect, the = operator assigns the value on the right to the variable or property on the left so that future references to the variable or property evaluate to the value.

Although assignment expressions are usually quite simple, you may sometimes see the value of an assignment expression used as part of a larger expression. For example, you can assign and test a value in the same expression with code like this:

If you do this, be sure you are clear on the difference between the = and == operators! Note that = has very low precedence and parentheses are usually necessary when the value of an assignment is to be used in a larger expression.

The assignment operator has right-to-left associativity, which means that when multiple assignment operators appear in an expression, they are evaluated from right to left. Thus, you can write code like this to assign a single value to multiple variables:

Assignment with Operation

Besides the normal = assignment operator, JavaScript supports a number of other assignment operators that provide shortcuts by combining assignment with some other operation. For example, the += operator performs addition and assignment. The following expression:

is equivalent to this one:

As you might expect, the += operator works for numbers or strings. For numeric operands, it performs addition and assignment; for string operands, it performs concatenation and assignment.

Similar operators include -= , *= , &= , and so on. Table 4-3 lists them all.

Table 4-3. Assignment operators

Example

In most cases, the expression:

where op is an operator, is equivalent to the expression:

In the first line, the expression a is evaluated once. In the second it is evaluated twice. The two cases will differ only if a includes side effects such as a function call or an increment operator. The following two assignments, for example, are not the same:

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

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

javascript assignment operator return value

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Javascript return OR with assignment of value?

I'm working with a simple example in D3, and I've been puzzling over this return statement for a while.

I have a basic understanding of using the || operator in a return statement, but please correct me if I'm wrong. From what I have gathered, if nodesByNames[name] is undefined, then a new object nodesByName[name] is created with a name of name .

What I'm trying to get at is that I don't know how to wrap my mind around returning an assignment like nodesByName[name]={name:name} .

  • or-operator

Null-Username's user avatar

  • 1 An assignment is an expression in JavaScript. The result of the expression is the value that was assigned. –  Felix Kling Commented Aug 19, 2014 at 18:07
  • @Felix I thought that my wording was incorrect. What should I say instead to be more precise? –  Null-Username Commented Aug 19, 2014 at 18:23
  • No it's fine. I just wanted to explain that since an assignment is an expression, in can be used everywhere where expressions are allowed and it has to return a value. –  Felix Kling Commented Aug 19, 2014 at 18:30

4 Answers 4

When you use the || operator to create an expression (i.e. a || b ), JavaScript will return either the first operand that evaluates to something truthy, like 1 or true or any object, or else will return the last value. (So a || b || c will return c if all of the values are false).

In your example, you have this:

Javascript will start by evaluating the left hand side, nodesByName[name] . If this value is something truthy, it will be returned. If it is not, (and undefined is not), the right hand side will be evaluated and returned. The right hand side is an assignment, which will return an object, {name: name} , after assigning it to nodesByName[name] .

The reason for having this chunk of code is to assign a value to nodesByName[name] if it does not already have a value.

Felix Kling's user avatar

  • Also, "The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague." -Edsger Dijkstra –  ckersch Commented Aug 19, 2014 at 18:28
  • I'm a little puzzled. Is the quote meant to indicate that this code is a clever trick that should be avoided? –  Null-Username Commented Aug 19, 2014 at 18:32
  • Yes. Code like this can be tough to read, and can be done in a manner that's easy to read for anyone, using if statements. –  ckersch Commented Aug 19, 2014 at 18:39
  • Thank you, I needed your explanation in order to understand what these statements meant. Now I can go back and rewrite the code in a way that is more appropriate for the size of my skull. –  Null-Username Commented Aug 19, 2014 at 18:43

It's not returning an assignment, it's returning the return value of the assignment. See http://www.quirksmode.org/blog/archives/2008/01/using_the_assig.html for more info on the return value of = . In this case, when nodesByName[name] is undefined, the function will return {name: name} (which evaluates to true because all objects do).

katy lavallee's user avatar

The code above would work only if your nodesByName object is always defined!

Here is the explanation of what you do not understand:

actually creates a new object with property 'name' set to the value of your name variable.

Once this object is created it is assigned to the object nodesByName under the property with name of the passed name parameter.

Georgi Bilyukov's user avatar

In the code you have posted var nodesByName = {}; already declares your object. So you're code is basically to be read like this:

  • Does nodesByName already have an property of name name ? then return it
  • Create an object, only with a property name and set it to the given value in the parameter
  • Assign the object as an property with the name to the nodesByName object
  • Oh, and when you're done with that return the value as well

So return basically only returns the newly created object.

Trying to write the code another way:

Basically does the same thing, just uses more lines of code.

Kevin Sandow's user avatar

  • Not quite right. In the original code, if nodesByName[name] === 0 (or null or false), the || operator will continue on to the second expression. –  ckersch Commented Aug 19, 2014 at 18:19
  • I can agree to that, but is that really the correct expected behavior? Also what about nodesByName('toString') ? Would return a function in the original code. –  Kevin Sandow Commented Aug 19, 2014 at 19:03

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript d3.js return or-operator or ask your own question .

  • The Overflow Blog
  • Looking under the hood at the tech stack that powers multimodal AI
  • Detecting errors in AI-generated code
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • how to make the latex support traditional-Chinese characters
  • He worked in the field during most of the day
  • Writing in first person for fiction novel, how to portray her inner dialogue and drag it out to make a chapter long enough?
  • Does General Relativity predict Mercury's orbital precession without other planets?
  • How to implement a "scanner" effect on Linux to fix documents with varying darkness of background?
  • BSS138 level shifter - blocking current flow when high-side supply is not connected?
  • Change style of True/False everywhere
  • Solve a Differential Equation with a Free Parameter and Integrate for Plotting
  • Can there exists a model of ZFC with permutation that sends successor infinite stages to their predecessors?
  • Ubuntu 24.04.1 not booting up - is it disk damage?
  • Uppercase, lowercase – "in any case"?
  • How can I connect heavy-gauge wire to a 20A breaker?
  • Rigorous expositions of anti-foundationalism?
  • Is Wild Shape affected by Moonbeam?
  • Man who can't tell right from wrong gets experimental surgery
  • Usage of つもりだ with the past verb
  • How can I have my paper reviewed?
  • Why do you even need a heatshield - why not just cool the re-entry surfaces from inside?
  • What to consider as reviewer before dooming a paper
  • Did Microsoft actually release a “Critical Update Notification Tool”?
  • Is there any way to fill the area where multiple lines intersect with black?
  • Confused about this usage of 前半 here
  • Using plural for appendix if more than one
  • What is the contextual interpretation of Psalm 141:3?

javascript assignment operator return value

IMAGES

  1. Return Values from JavaScript Functions

    javascript assignment operator return value

  2. JavaScript

    javascript assignment operator return value

  3. Understanding JavaScript Operators With Types and Examples

    javascript assignment operator return value

  4. JavaScript Operators.

    javascript assignment operator return value

  5. Javascript return value cheat sheet

    javascript assignment operator return value

  6. JavaScript Operators and Expressions

    javascript assignment operator return value

VIDEO

  1. Java Script Logical Operator Lesson # 08

  2. JavaScript Assignment Operators #basicsforbeginners #javascript #coding

  3. Assignment with a Returned Value (Basic JavaScript) freeCodeCamp tutorial

  4. Javascript new operator #coding #programming #javascript #trycatch #errorhandling

  5. Week 3 Javascript Assignment

  6. 9 JavaScript Assignment Operators

COMMENTS

  1. javascript

    Second thing is assigning y to x, and so on. Assigning is not return (it's not a function, and in JS it doesn't have C++ syntax to overload operator's behavior). return is sth more complex then assignment. return construct is not only returning a value, but is closing current context causing it to be destroyed. Also it's closing any parent ...

  2. 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. ... JavaScript. General-purpose scripting language. HTTP. Protocol for transmitting web resources. Web APIs. Interfaces for building web applications. ... Return value. The value of y ...

  3. javascript

    5.Return Result(3). Basically when you make (foo.bar = foo.bar) the actual assignment (Step 4.) has no effect because PutValue will only get the value of the reference and will place it back, with the same base object. The key is that the assignment operator returns (Step 5) the value obtained in the Step 3 and as I said before in the GetValue ...

  4. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  5. JavaScript Assignment

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... The Addition Assignment Operator adds a value to a variable. Addition Assignment Examples. let x = 10;

  6. Assignment with a Returned Value

    If you'll recall from our discussion about Storing Values with the Assignment Operator, everything to the right of the equal sign is resolved before the value is assigned.This means we can take the return value of a function and assign it to a variable. Assume we have defined a function sum which adds two numbers together.. ourSum = sum (5, 12);. Calling the sum function with the arguments of ...

  7. JavaScript Assignment Operators

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

  8. Assignment operators

    An assignment operator assigns a value to its left operand based on the value of its right operand.. Overview. 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.

  9. Logical AND assignment (&&=)

    The logical AND assignment (&&=) operator only evaluates the right operand and assigns to the left if the left operand is truthy. Logical AND 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 truthy, due to ...

  10. What is ?= in JavaScript? Safe Assignment Operator Explained

    Learn how the new ?= operator in JavaScript simplifies code and prevents errors. Discover its benefits for async/await handling.

  11. JavaScript Assignment Operators

    JavaScript Addition assignment operator(+=) adds a value to a variable, The Addition Assignment (+ =) Sums up left and right operand values and then assigns the result to the left operand. The two major operations that can be performed using this operator are the addition of numbers and the concatenation of strings. Syntax: a += b Example 1: In thi

  12. Javascript Assignment Operators (with Examples)

    In this tutorial, you will learn about all the different assignment operators in javascript and how to use them in javascript. Assignment Operators. In javascript, there are 16 different assignment operators that are used to assign value to the variable. It is shorthand of other operators which is recommended to use.

  13. Assignment with a Returned Value.md

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window.

  14. What is the benefit of having the assignment operator return a value?

    Are there any practical uses of the assignment operator's return value that could not be trivially rewritten? Generally speaking, no. The idea of having the value of an assignment expression be the value that was assigned means that we have an expression which may be used for both its side effect and its value , and that is considered by many ...

  15. JavaScript Operators Reference

    For a tutorial about assignment operators, read our JavaScript Assignment Tutorial. JavaScript String Operators. The + operator, and the += operator can also be used to concatenate (add) strings. ... used to obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without using the return value). Example <a ...

  16. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... Destructuring can make working with an array return value more concise. In this example, f() returns the values ... Assignment operators; ES6 in Depth: Destructuring on ...

  17. Assignment Expressions

    Assignment Expressions. JavaScript uses the = operator to assign a value to a variable or property. For example: i = 0 // Set the variable i to 0. o.x = 1 // Set the property x of object o to 1. The = operator expects its left-side operand to be an lvalue: a variable or object property (or array element).

  18. Javascript return OR with assignment of value?

    In your example, you have this: nodesByName[name] || (nodesByName[name] = {name: name}) Javascript will start by evaluating the left hand side, nodesByName[name]. If this value is something truthy, it will be returned. If it is not, (and undefined is not), the right hand side will be evaluated and returned. The right hand side is an assignment ...

  19. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  20. Private properties

    Private properties are counterparts of the regular class properties which are public, including class fields, class methods, etc. Private properties get created by using a hash # prefix and cannot be legally referenced outside of the class. The privacy encapsulation of these class properties is enforced by JavaScript itself. The only way to access a private property is via dot notation, and ...