• Choose a Course
  • TEAM TRAINING VOUCHERS
  • Certification
  • Training Options
  • LIVE ONLINE TRAINING
  • Join Our Newsletter
  • Free Skills Assessments
  • Latest News
  • After Effects: Beginner
  • After Effects: Intermediate
  • After Effects: Advanced
  • After Effects: Zero to HERO
  • Captivate: Beginner
  • Captivate: Intermediate
  • Captivate: Zero to HERO
  • E-Learning Master Class
  • InDesign: Beginner
  • InDesign: Intermediate
  • InDesign: Advanced
  • InDesign: Zero to HERO
  • InDesign: Ultimate Mastery
  • InDesign: Adobe Certified Expert
  • Illustrator: Beginner
  • Illustrator: Intermediate
  • Illustrator: Advanced
  • Illustrator: Zero to HERO
  • Illustrator: Designing Infographics
  • Illustrator: Ultimate Mastery
  • Photoshop: Beginner
  • Photoshop: Intermediate
  • Photoshop: Zero to HERO
  • Photoshop: Ultimate Mastery
  • Photoshop: Advanced Bespoke
  • Premiere Pro: Beginner
  • Premiere Pro: Intermediate
  • Premiere Pro: Zero to HERO
  • Adobe User Experience (XD) Bespoke
  • Affinity Designer
  • Affinity Photo
  • Affinity Publisher
  • Adobe Illustrator To Affinity Designer
  • Adobe InDesign To Affinity Publisher
  • Adobe Photoshop To Affinity Photo
  • AutoCAD: Beginner
  • AutoCAD: Intermediate
  • AutoCAD: Advanced – Creating 3D Models
  • AutoCAD: Zero to HERO
  • CAD Visualiser Master Class – Gold
  • 3ds Max: Intermediate Bespoke
  • 3ds Max: Zero to HERO
  • 3d Animator Master Class – Gold
  • Navisworks: Beginner
  • Revit Architecture: Beginner
  • Revit Architecture: Intermediate
  • Revit Architecture: Zero to HERO
  • Inventor: Beginner
  • Inventor: Zero to Hero
  • Maya: Zero to HERO
  • Revit MEP: Beginner
  • Revit Structure: Beginner
  • Revit Architecture: Advanced
  • Cinema 4D: Beginner
  • Cinema 4D: Zero to HERO
  • Cinema 4D: Intermediate
  • Cinema 4D: Advanced
  • Cinema 4D: Ultimate Mastery
  • VRAY for Cinema 4D
  • SketchUp: Beginner
  • SketchUp: Intermediate
  • SketchUp: Zero To HERO
  • Vectorworks 2D: Beginner
  • Corporate Vouchers
  • 7 Day Vouchers
  • Blender 3D: Foundations And 3D Asset Creation
  • Davinci Resolve: Beginner
  • Davinci Resolve: Intermediate
  • Davinci Resolve: Zero to HERO
  • Unity 3d: Zero to HERO
  • Unity 3d for VR: Bespoke
  • Unreal Engine 4: Zero To HERO
  • Unreal Engine 5: Zero To HERO
  • ZBrush: Zero to HERO
  • Ableton Production and Performance: Zero to hero
  • Logic Composing and Producing: Zero to Hero
  • Touchdesigner (TD): Essentials
  • Articulate Storyline
  • ECMAScript 6
  • HTML5/CSS3: Beginner
  • HTML5/CSS3: Zero to HERO
  • HTML Emails
  • Interaction Design Master Class
  • Web Developers Master Class – Silver
  • JavaScript: Beginner
  • JavaScript: Intermediate
  • JavaScript: Zero to HERO
  • Php and MySQL: Beginner
  • UX / UI Design: Zero to HERO
  • User Research (UX)
  • WordPress: Beginner
  • UX / UI DESIGN: ZERO TO HERO
  • USER RESEARCH (UX)
  • Crypto, NTF’s Blockchain & The Metaverse (Full Day)
  • Crypto, NFT’s, Blockchain & The Metaverse (2 Evenings)
  • Go To Campus
  • Campus Login
  • CAD VISUALISER
  • 3D ANIMATOR
  • GRAPHIC DESIGNER
  • INTERACTIVE DESIGNER
  • VISUAL EFFECTS
  • VIDEO PRODUCTION SPECIALIST
  • WEB DESIGNER
  • WEB DEVELOPER

What are compound operators in JavaScript?

In the dynamic landscape of web development, JavaScript stands as a cornerstone, driving interactivity and innovation across the digital realm. As developers strive for more efficient and expressive code, there emerges a powerful tool in their arsenal: compound operators. If you’ve ever found yourself writing repetitive lines of code or seeking ways to enhance your JavaScript proficiency , this blog is your gateway to understanding and harnessing the capabilities of compound operators.

What is a compound operator?

In computer programming, a compound operator is a shorthand notation that combines an arithmetic or bitwise operation with an assignment statement. Instead of writing separate statements for the operation and assignment, a compound operator allows you to perform the operation and assignment in a single step.

What do compound assignment operators do in JavaScript?

Compound assignment operators in JavaScript serve the purpose of combining an assignment operation with another operation, such as arithmetic or bitwise operations. They allow you to perform a calculation and update a variable’s value in a single, concise statement.

What is the additive operator in JavaScript?

In JavaScript, the additive operator refers to the + symbol used for addition. The additive operator can be used for both numerical addition and string concatenation.

Example of using the additive operator in Javascript

compound assignment operators javascript

Example of concentration with strings

compound assignment operators javascript

It’s important to note that when the + operator is used with one or more strings, JavaScript treats it as a concatenation operator. If at least one operand is a string, the other operand(s) will be converted to strings, and the concatenation operation will be performed.

What are the 5 compound assignment operators?

The five compound assignment operators in programming languages, including JavaScript, combine an assignment operation with another operation, such as arithmetic or bitwise operations.

Compound Operators

+= compound addition operator, -= compound subtraction operator, %= compound modulo operator, *= compound multiplication operator, /= compound division operator.

These operators combine an assignment and an arithmetic operator. The operators display similar patterns, but, of course, they use their own respective logic and rhythmic symbols. Scroll down for some examples.

What is an Examples of Compound Operators?

In the below example, we are taking the original value of num, which is 5 and we are adding 10 to it, which is 15.

Compound Addition Operator

We give num2 a value of 10 and then we use the operator with the value of 10, and, since we’re subtracting, we end up with the value of 0.

Compound Subtraction Operator

We have a variable titled num3 and we give it a value of 50 and then we use the operator with a value of 9 and the remainder is 5 and that’s our output.

compound assignment operators javascript

We give num4 a value of 4, use the operator with a value of 9 and this outputs a value of 45.

Compound Modulo Operator

Our operator is num5 with a value of 50, we then use the operator with a value of 25 which outputs 2.

Compound Division Operator

What is the difference between simple and compound assignment operators?

In JavaScript, assignment operators are used to assign values to variables. There are two main types of assignment operators: simple assignment operators and compound assignment operators.

Simple Assignment Operator (=):

The simple assignment operator (=) is used to assign a value to a variable.

It assigns the value on the right-hand side to the variable on the left-hand side.

let x = 10;

let y = “Hello”;

Compound Assignment Operators:

Compound assignment operators combine the assignment (=) with another operation, such as addition, subtraction, multiplication, etc.

They perform the operation and assign the result to the variable on the left-hand side.

a += 3; // Equivalent to: a = a + 3; (Addition)

let b = 10;

b -= 2; // Equivalent to: b = b – 2; (Subtraction)

c *= 4; // Equivalent to: c = c * 4; (Multiplication)

d /= 2; // Equivalent to: d = d / 2; (Division)

Other compound assignment operators include %= (modulus assignment), **= (exponentiation assignment), <<=, >>=, and >>>= (bitwise shift assignments), among others.

The primary difference lies in the combination of an operation with assignment in compound assignment operators. They provide a more concise way to perform an operation and assign the result to a variable, reducing the need for repetitive variable references.

What is the === operator in JavaScript?

The === operator in JavaScript is the strict equality operator. It is used to compare two values for equality without performing type coercion. This means that both the value and the type of the operands must be the same for the === operator to return true.

In conclusion, the world of compound operators in JavaScript opens up new avenues for streamlined and efficient coding. From simplifying arithmetic to mastering bitwise operations, these shorthand notations seamlessly integrate with assignment statements, enhancing your programming prowess. If you’re interested in the different types of other operators in javascript then why not take a look at our blog “ What are the different javascript operators? ” If you’re ready to delve deeper into JavaScript and take your coding skills to the next level, then why not explore our comprehensive JavaScript training courses at Academy Class with hands-on learning, suitable for both beginners and seasoned developers?

Have a look at our video about JavaScript Operators below!

Want to learn more about javascript book a course below.

  • Academy Class
  • September 2, 2020

Reviews from our Awesome Students

Our clients, have questions about the course or need advice from our experts, contact our experts today, book a meeting.

Book a meeting with Sharjil, our expert Learning Paths Advisor. Contact for bulk buy discounts!

Give Us A Call (United Kingdom)

  • +44 800 043 8889

Give Us A Call (United States)

  • +1 332 217 1803

Send Us an Email

General Enquiries: office@academyclass.com

Training Enquires:  training@academyclass.com

Subscribe to our newsletter & receive the best tutorials, videos and offers sent straight to your inbox.

Our classes are all hands-on and led by Certified Adobe, Autodesk, Maxon and Unity instructors who are also designers and developers. You’re in good hands!

Easy Access

  • Team Training Solutions
  • Privacy Policy
  • Terms and Conditions
  • Web Developer Jobs

Get in touch

fbpx

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.

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

Now that we've talked about operators. Let's talk about something called the compound assignment operator and I'm going make one little change here in case you're wondering if you ever want to have your console take up the entire window you come up to the top right-hand side here you can undock it into a separate window and you can see that it takes up the entire window.

large

So just a little bit more room now.

Additionally, I have one other thing I'm going to show you in the show notes. I'm going to give you access to this entire set of assignment operators but we'll go through a few examples here. I'm going to use the entire window just to make it a little bit easier to see.

Let's talk about what assignment is. Now we've been using assignment ever since we started writing javascript code. You're probably pretty used to it. Assignment is saying something like var name and then setting up a name

And that is assignment the equals represents assignment.

Now javascript gives us the ability to have the regular assignment but also to have that assignment perform tasks. So for example say that you want to add items up so say that we want to add up a total set of grades to see the total number of scores. I can say var sum and assign it equal to zero.

And now let's create some grades.

I'm going to say var gradeOne = 100.

and then var gradeTwo = 80.

Now with both of these items in place say that we wanted to add these if you wanted to just add both of them together you definitely could do something like sum = (gradeOne + gradeTwo); and that would work.

However, one thing I want to show you is, there are many times where you don't have gradeOne or gradeTwo in a variable. You may have those stored in a database and then you're going to loop through that full set of records. And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do.

Let's use one of the more basic ones which is to have the addition assignment.

Now you can see that sum is equal to 100.

Then if I do

If we had 100 grades we could simply add them just like that.

Essentially what this is equal to is it's a shorthand for saying something like

sum = sum + whatever the next one is say, that we had a gradeThree, it would be the same as doing that. So it's performing assignment, but it also is performing an operation. That's the reason why it's called a compound assignment operator.

Now in addition to having the ability to sum items up, you could also do the same thing with the other operators. In fact literally, every one of the operators that we just went through you can use those in order to do this compound assignment. Say that you wanted to do multiplication you could do sum astrix equals and then gradeTwo and now you can see it equals fourteen thousand four hundred.

This is that was the exact same as doing sum = whatever the value of sum was times gradeTwo. That gives you the exact same type of process so that is how you can use the compound assignment operators. And if you reference the guide that is included in the show notes. You can see that we have them for each one of these from regular equals all the way through using exponents.

Then for right now don't worry about the bottom items. These are getting into much more advanced kinds of fields like bitwise operators and right and left shift assignments. So everything you need to focus on is actually right at the top for how we're going to be doing this. This is something that you will see in a javascript code. I wanted to include it, so when you see it you're not curious about exactly what's happening.

It's a great shorthand syntax for whenever you want to do assignment but also perform an operation at the same time.

  • Documentation for Compound Assignment Operators
  • Source code

devCamp does not support ancient browsers. Install a modern version for best experience.

This page is Ready to Use

  • compound assignment

compound assignment operators

The following table lists JavaScript compound assignment operators.

Assignment Operators

Other articles.

  • Assignment Operator (=)

Attributions

Microsoft Developer Network: Article

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

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

Browser compatibility.

  • 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

AI Creations

completion percent

Javascript Variables and Operators

Get Unstuck

Compound Assignment With Augmented Addition

In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:

to add 5 to myVar . Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

One such operator is the += operator.

6 would be displayed in the console.

Do - Don't Just Read

Reminder - take action.

Throughout this course, we want you to code while you learn. Don't just read about Javascript - write Javascript!

As a reminder, we have a development environment built for you called GitPod. GitPod is a cloud environment, which means it will work from any computer or phone you might be using. There is no need to download anything fancy.

What's even better? Our GitPod will let you run and test your code.

We recommend having this window open for learning, and then having GitPod open in a second window or tab next to it. You can code along as you learn.

Operators are constructs which behave generally like functions, but which differ syntactically or semantically from usual functions.

Types of operators

Unary operators, binary operators, the ternary operator (conditional operator).

condition ? x : y

Conditional Operator

condition ? expression : expression

The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement.

MDN // Conditional Operator

As an expression:

To declare a variable:

To create a property:

Multiple ternary evaluations

Multiple operations, arithmetic operators.

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

MDN // Arithmetic Operators

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number , if it isn't already.

Note: NaN is a property of the global object. MDN // NaN

The unary negation operator precedes its operand and negates it.
The addition operator produces the sum of numeric operands or string concatenation.

Concatenation

Addition operators are parsed from left to right

Subtraction -

The subtraction operator subtracts the two operands, producing their difference.
The division operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

Note: The global Infinity property is a numeric value representing infinity. MDN | Infinity

Multiplication *

The multiplication operator produces the product of the operands.
The multiplication operator has higher precedence than the addition operator.

Remainder %

Returns the remainder left over when one operand is divided by a second operand.

Exponentiation **

The exponentiation operator returns the result of raising first operand to the power second operand.

Increment ++

x ++ or ++ x

The increment operator increments (adds one to) its operand and returns a value.

Decrement --

x -- or -- x

The decrement operator decrements (subtracts one from) its operand and returns a value.

Assignment operators

The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand.

MDN // Assignment Operators

Simple Assignment

Simple assignment operator which assigns a value to a variable.

Compound assignment

Destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables.

MDN // Destructuring assignment

Array Destructuring

With arrays, destructuring is made by order

With destructuring:

Without destructuring:

Destructuring declares new variables, and follows the same rules as any variable declaration.

Note: as we are declaring new variables y and z and asigning a value, we need to use var , otherwise variables will be declared on global scope.

Direct assignment

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

without destructuring:

with destructuring:

Default values

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

Note: Notice that default values only works with undefined values, not with null or falsey values.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Skipping values

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

Nested array destructuring

Object destructuring.

With objects, destructuring is made by property name, not by order

Renaming properties

Default values or renamed properties, destructuring function parameters, nested object and array destructuring, complex destructuring, comparison operators.

JavaScript has both strict and type–converting comparisons.

MDN // Comparison Operators

Abstract comparison

Converts the operands to the same type before making the comparison.

Abstract equality

Equality of objects.

Two distinct objects are never equal for either strict or abstract comparisons. An expression comparing objects is only true if the operands reference the same object.

Note: The two objects are difference objects, in different allocation. They are not the same object .

Abstract inequality

Type conversion rules, string == number.

The string is converted to a number value.

Boolean == Number

The Boolean operand is converted to 1 if it is true and 0 if it is false.

Object == Number || Object == String

JavaScript attempts to return the default value for the object.

Working with objects

Each of these operators will call the valueOf() function on each operand before a comparison is made. Then, the primitive values are compared

MDN // Object.protrotype.valueOf()

Enforcing valueOf() :

Strict comparison

A strict comparison is only true if the operands are of the same type and the contents match.

Strict equality

Strict inequality, relational operators, logical operators.

expression && expression

expression || expression

! expression

Logical operators are typically used with Boolean (logical) values However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value.

MDN // Logical Operators

Logical AND

The return is not true or false , it's the last evaluated expression

Expression conversion

With non-Boolean values, "falsey" expressions are evaluated to false: undefined , null , NaN , 0 , ""

Note: The return is not true or false , it's the last evaluated expression.

Logical NOT

Short-circuit evaluation.

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation.

Using it for logic

is the same as:

Other unary operators

An unary operation is an operation with only one operand.
The delete operator deletes an object, an object's property, or an element at a specified index in an array.

MDN // Operators > delete

Objects (and arrays) can be deleted only if they are declared implicitly

The typeof operator returns a string indicating the type of the unevaluated operand.

Spread operator

The spread syntax allows an expression to be expanded in places where comma separated variables are expected.

MDN // Spread operator

numbers passed as a single argument to console.log :

numbers spread, as separated arguments:

which is the same as:

Spreading arrays

Array concat, array insertion, array clone.

arr2 becomes 1,2,3,4 , arr stays the same

Spreading objects

Spread with overriding, can't spread an object into an array, spread arguments, spread operator as rest parameter.

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

Getting all arguments of a func

Arguments vs ...args .

arguments is an iterable (array-like), but not an Array

Array of arguments

arguments built-in variable

Selective rest parameter

... is usefull to get "the rest of the arguments"

Spreading arguments

Rest paramater in array destructure

Read the slides again, and we'll start a small quiz on operators.

01. What would be the output of each code?

01. solution, 02. what would be the output of this code, 02. solution, 03. what would be the output of this code, 03. solution, 04. what would be the output of this code, 04. solution, 05. what would be the output of this code, 05. solution, 06. what would be the output of this code, 06. solution.

String is iterable, so you can spread them.

07. What would be the output of this code?

07. solution, 08. what would be the output of this code, 08. solution.

Demystifying JavaScript Operators: What Does That Symbol Mean?

James Hibbard

In this article, we’re going to examine the operators in JavaScript one by one. We’ll explain their function and demonstrate their usage, helping you to grasp their role in building more complex expressions.

What are JavaScript Operators?

JavaScript, a cornerstone of modern web development, is a robust language full of numerous features and constructs. Among these, operators (special symbols such as + , += , && , or ... ) play an essential role, enabling us to perform different types of calculations and manipulations on variables and values.

Despite their importance, operators can sometimes be a source of confusion for new programmers and seasoned coders alike.

Take a moment to examine this code snippet:

Don’t be alarmed if it seems a bit cryptic. By the time we’re finished, you’ll be able to understand exactly what it does.

A Quick Word on Terminology

Before we dive in, let’s clarify a couple of terms that we’ll be using quite a bit:

An operand is the item that operators work on. If we think of an operator as a kind of action, the operand is what the action is applied to. For example, in the expression 5 + 3, + is the operator (the action of addition), and 5 and 3 are the operands — the numbers being added together. In JavaScript, operands can be of various types, such as numbers, strings, variables, or even more complex expressions.

Coercion is the process of converting a value from one primitive type to another. For example, JavaScript might change a number into a string, or a non-Boolean value into a Boolean. The primitive types in JavaScript are String , Number , BigInt , Boolean , undefined , Symbol or null .

NaN stands for Not a Number . It’s a special value of the Number type that represents an invalid or unrepresentable numeric value.

Truthy values are those that evaluate to true in a Boolean context, while falsy values evaluate to false — with falsy values being false , 0 , -0 , '' , null , undefined , NaN and BigInt(0) . You can read more about truthy and falsy values in Truthy and Falsy Values: When All is Not Equal in JavaScript .

As we explore JavaScript operators, we’ll see these concepts in action and get a better understanding of how they influence the results of our operations.

Arithmetic Operators

Arithmetic operators allow us to perform arithmetic operations on values and to transform data. The commonly used arithmetic operators in JavaScript include addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Beyond these, we also have the modulus operator ( % ), which returns the remainder of a division operation, and the increment ( ++ ) and decrement ( -- ) operators that modify a value by one.

Addition: +

The addition operator performs two distinct operations: numeric addition and string concatenation. When evaluating expressions using the + operator, JavaScript first coerces both operands to primitive values. Once this is done, it examines the types of both operands.

If one operand is a string, the other operand is also converted to a string, and then the two strings are concatenated. For example:

If both operands are BigInts , BigInt addition is performed. A BigInt is a special numeric type that can deal with numbers larger than the standard Number type can handle.

But if one operand is a BigInt and the other isn’t, JavaScript throws a TypeError :

For all other cases, both operands are converted to numbers, and numeric addition is performed. For example:

Be aware that JavaScript sometimes has a strange idea of what this looks like:

In this case, JavaScript tried to convert the object { a: 1 } to a primitive value, but the best it could do was to convert it to the string [object Object] , which then got concatenated with the number 1.

Subtraction: -

The subtraction operator in JavaScript is straightforward in its usage: it’s used to subtract one number from another. Like the addition operator, it also works with the BigInt type.

If both operands are numbers or can be converted to numbers, JavaScript performs numeric subtraction:

If both operands are BigInts , JavaScript performs BigInt subtraction:

Like the addition operator, subtraction can also produce unexpected results when used with non-numbers. For example, if we try to subtract a something that can’t be converted to a number, JavaScript will return NaN , which stands for “Not a Number”:

Multiplication: *

The multiplication operator works with numbers and BigInts.

Normally, we’ll be multiplying numbers:

If both operands are BigInts , then it performs BigInt multiplication:

As with other operators, JavaScript attempts to convert non-numeric values into numbers. If it can’t do this, it returns NaN :

Division: /

The division operator ( / ) functions with numbers and BigInts , much the same way as + , - and * . It first converts both operands into numbers.

Standard number division:

When dealing with BigInts , the division operator behaves slightly differently. It performs the division and discards any remainder, effectively truncating the result towards zero:

Dividing a number by zero will produce Infinity , unless it’s a BigInt , in which case it throws a RangeError .

If we attempt to divide a number by a value that can’t be converted into a number, JavaScript will usually return NaN .

Modulus (remainder): %

The modulus operator is used to find the remainder after division of one number by another (known as the dividend and the divisor ). This arithmetic operator works with numbers and BigInts .

When we use the % operator, JavaScript first converts the operands to numbers:

This is because three goes into ten three times (making nine), and what’s left over (the remainder) is one.

A common use case for this operator is to check if a number is odd or even:

This uses an arrow function and the triple equals operator that we’ll meet later on.

The modulus operator has some special cases. For example, if one of the operands is NaN , if the dividend is Infinity , or if the divisor is 0 , the operation returns NaN .

On the other hand, if the divisor is Infinity or if the dividend is 0 , the operation returns the dividend.

Increment: ++

The increment operator is used to increase the value of a variable by 1. It can be applied to operands of type Number or BigInt , and its behavior can differ based on whether it’s used in postfix or prefix form.

Postfix increment

If the operator is placed after the operand ( num++ ), the increment operation is performed after the value is returned. In this case, the original value of the variable is used in the current expression, and the variable’s value is incremented afterward:

Prefix increment

If the operator is placed before the operand ( ++num ), the increment operation is performed before the value is returned. In this case, the variable’s value is incremented first, and then the updated value is used in the current expression:

Decrement: --

The decrement operator is used to decrease the value of a variable by 1. Similar to the increment operator, it can be applied to operands of type Number or BigInt . The behavior of the decrement operator can vary based on whether it’s used in postfix or prefix form.

Postfix decrement

When the operator is placed after the operand ( num-- ), the decrement operation is performed after the value is returned. In this case, the original value of the variable is used in the current expression, and the variable’s value is decremented afterward:

Prefix decrement

When the operator is placed before the operand ( --num ), the decrement operation is performed before the value is returned. In this case, the variable’s value is decremented first, and then the updated value is used in the current expression:

The decrement operator, just like the increment operator, can only be used with variables that can be changed:

Miscellaneous arithmetic operators

In addition to the increment and decrement operators, there are other arithmetic operators in JavaScript that we should be aware of.

The unary negation operator ( - ) is used to negate a numeric value, changing its sign to the opposite. For example, -5 would be the negation of the number 5 .

The unary plus operator ( + ) can be used to explicitly convert a value to a number, which can be useful when dealing with string representations of numbers. For example, +'10' converts the string '10' to the number 10 :

The exponentiation operator ( ** ) is used to raise a number to a power. For example, 2 ** 3 represents 2 raised to the power of 3, which results in 8.

It’s also important to note that JavaScript follows operator precedence rules, which determine the order in which operators are evaluated in an expression. For example, multiplication and division have a higher precedence than addition and subtraction, so they are evaluated first:

We can alter the order of evaluation by using the grouping operator () , which is covered in the “ Grouping operator ” section below.

Assignment Operators

Assignment operators are used to assign values to variables. They also offer a concise and effective way to update the value of a variable based on an expression or other value. In addition to the basic assignment operator ( = ), JavaScript provides compound assignment operators that combine arithmetic or logical operations with assignment.

Assignment: =

This operator is used to assign a value to a variable. It allows us to store a value in a variable so that we can use and reference it later in our code:

The assignment operator assigns the value on the right-hand side of the operator to the variable on the left-hand side.

Additionally, the = operator can be chained to assign the same value to multiple variables in a single line:

Addition assignment: +=

The addition assignment operator is a compound operator that performs an operation and assignment in one step. Specifically, it adds the right operand to the left operand and then assigns the result to the left operand:

This operator isn’t limited to numbers. It can also be used for string concatenation:

When the operands aren’t of the same type, JavaScript applies the same rules of type coercion that we saw previously:

Subtraction assignment: -=

The subtraction assignment operator is another compound operator that performs an operation and assignment in one step. It subtracts the right operand from the left operand and then assigns the result to the left operand:

Like other JavaScript operators, -= performs type coercion when the operands aren’t of the same type. If an operand can be converted to a number, JavaScript will do so:

Otherwise, the result is NaN :

Multiplication assignment: *=

The multiplication assignment operator multiplies the left operand by the right operand and then assigns the result back to the left operand:

When we use operands of different types, JavaScript will try to convert non-numeric string operands to numbers:

If the string operand can’t be converted to a number, the result is NaN .

Division assignment: /=

Like its siblings, the division assignment operator performs an operation on the two operands and then assigns the result back to the left operand:

Otherwise, the rules we discussed for the division operator above apply:

Modulus assignment: %=

The modulus assignment operator performs a modulus operation on the two operands and assigns the result to the left operand:

Otherwise, the rules we discussed for the modulus operator apply:

Exponentiation assignment: **=

The exponentiation assignment operator performs exponentiation, where the left operand is the base and the right operand is the exponent, and assigns the result to the left operand:

Here, num is raised to the power of 3, and the result (8) is assigned back to num .

As before, when the second operand is not a number, JavaScript will attempt to convert it with varying degrees of success:

Bitwise assignment operators

While we’ve been focusing on arithmetic operators so far, JavaScript also supports a set of assignment operators that work at the bit level. These are the bitwise assignment operators . If you’re familiar with binary numbers and bit manipulation, these operators will be right up your alley.

These operators include:

  • Bitwise AND assignment ( &= )
  • Bitwise OR assignment ( |= )
  • Bitwise XOR assignment ( ^= )
  • Left shift assignment ( <<= )
  • Right shift assignment ( >>= )
  • Unsigned right shift assignment ( >>>= )

Each of these JavaScript assignment operators performs a specific bitwise operation on the binary representations of the numbers involved and assigns the result back to the left operand.

We’ll explore bitwise operators in more detail in the “ Bitwise Operators ” section below.

Comparison Operators

Leaving the realm of arithmetic, let’s dive into another significant group of JavaScript operators — the comparison operators. As the name implies, comparison operators are used to compare values and return a Boolean result. Comparison operators are the underpinning of many programming decisions and control structures — from simple condition checks to complex logical operations.

Equality: ==

The equality operator is used to check whether two values are equal to each other. It returns a Boolean result. However, it’s important to note that this comparison operator performs a loose equality check, meaning that if the operands are of different types, JavaScript will try to convert them to a common type before making the comparison:

Things get slightly more complicated dealing with objects and arrays. The == operator checks whether they refer to the same location in memory, not whether their contents are identical:

In this case, JavaScript doesn’t attempt to convert and compare the values within the objects or arrays. Instead, it checks whether they’re the same object (that is, whether they occupy the same memory space).

You can read more about loose equality comparisons here .

Inequality: !=

The inequality operator is used to check whether two values are not equal to each other. Like the == operator, it performs a loose inequality check. This means that, if they’re of different types, it will try to convert the operands to a common type before making the comparison:

Similar to the == operator, when comparing objects and arrays, the != operator checks whether they refer to the same memory location, not whether their content is identical.

Strict equality ( === ) and strict inequality ( !== )

The strict equality and strict inequality comparison operators are similar to their non-strict counterparts ( == and != ), but they don’t perform type coercion. If the operands are of different types, they’re considered different, no matter their values.

Here’s how they work:

For objects and arrays, the strict equality operator behaves the same way as the loose equality operator: it checks whether they refer to the same object, not whether their contents are identical.

NaN is a special case. It’s the only value in JavaScript that isn’t strictly equal to itself:

You can read more about strict equality comparisons here .

Greater than: >

The greater than operator checks if the left operand is greater than the right operand, returning a Boolean result. This comparison is straightforward with numeric values:

When comparing non-numeric values, JavaScript applies a process of conversion to make them comparable. If both values are strings, they’re compared based on their corresponding positions in the Unicode character set:

If one or both of the operands aren’t strings, JavaScript tries to convert them to numeric values for the comparison:

Certain special rules apply for specific values during this conversion. For instance, null is converted to 0 , undefined is converted to NaN , and Boolean values true and false are converted to 1 and 0 respectively. However, if either value is NaN after conversion, the operator will always return false :

Less than: <

The less than operator returns true if the left operand is less than the right operand, and false otherwise. The same rules apply as for the greater than operator; only the order of operands is reversed:

Like the > operator, the < operator uses coercion to convert operands to a common type before making the comparison.

Greater than or equal to ( >= ) and less than or equal to ( <= )

The greater than or equal to ( >= ) and less than or equal to ( <= ) operators function similarly to their < and > counterparts, with the added condition of equality.

For the >= operator, it returns true if the left operand is greater than or equal to the right operand, and false otherwise. Conversely, the <= operator returns true if the left operand is less than or equal to the right operand, and false otherwise. Coercion rules and type conversion, as explained in the sections on < and > directly above, apply here as well:

Logical Operators

Logical operators in JavaScript offer a way to work with multiple conditions simultaneously. They’re an integral part of decision-making constructs in programming, such as if statements, and for loops.

Mastering logical operators is key for controlling the flow of our code.

Logical AND: &&

When used with Boolean values, the logical AND operator returns true if all conditions are true and false otherwise.

However, with non-Boolean values, it gets more interesting:

  • The operator evaluates conditions from left to right.
  • If it encounters a value that can be converted to false (known as a falsy value), it stops and returns that value.
  • If all values are truthy, it returns the last truthy value.

For example:

The && operator’s ability to return the value of the operands makes it a versatile tool for conditional execution and setting default values. For example, we can use the && operator to execute a function or a block of code only if a certain condition is met:

In this case, renderWelcomeMessage will only be executed if userIsLoggedIn is true . If userIsLoggedIn is false , the operation will stop at userIsLoggedIn and renderWelcomeMessage won’t be called. This pattern is often used with React to conditionally render components.

Logical OR: ||

When used with Boolean values, the logical OR operator returns true if at least one condition is true and false otherwise.

It can also return non-Boolean values, performing what’s known as short-circuit evaluation . It evaluates conditions from left to right, stopping and returning the value of the first truthy condition encountered. If all conditions are falsy, it returns the last falsy value:

Logical NOT: !

The logical NOT operator is used to reverse the Boolean value of a condition or expression. Unlike the && and || operators, the ! operator always returns a Boolean value.

If the condition is truthy (that is, it can be converted to true ), the operator returns false . If the condition is falsy (that is, it can be converted to false ), the operator returns true :

We can use the ! operator twice to convert a value to its Boolean equivalent:

Nullish coalescing operator: ??

The nullish coalescing operator checks whether the value on its left is null or undefined , and if so, it returns the value on the right. Otherwise, it returns the value on the left.

Though similar to the || operator in some respects, the ?? operator differs in its handling of falsy values.

Whereas the || operator returns the right-hand operand if the left-hand operand is any falsy value (such as null , undefined , false , 0 , NaN , '' ), the ?? operator only does so when the left-hand operand is null or undefined :

Setting default values with logical operators

The || and ?? logical operators are useful for setting default values in programs. Here’s an example of doing this with the || operator:

Here’s an example with the ?? operator:

The main difference between these logical operators (as highlighted above) is how they treat falsy values:

Bitwise Operators

Bitwise operators in JavaScript offer a way to perform operations at the binary level, directly manipulating bits in a number’s binary representation. While these operators can be instrumental in specific tasks like data encoding, decoding, and processing, they’re not frequently used in day-to-day JavaScript programming.

In this article, we’ll provide an overview of these operators so you can recognize and understand them, but we won’t delve deeply into their usage given their relatively niche application.

Bitwise AND: &

The bitwise AND operator performs a bitwise AND operation on the binary representations of integers. It returns a new number whose bits are set to 1 if the bits in the same position in both operands are 1. Otherwise, it sets them to 0:

Bitwise OR: |

The bitwise OR operator works similarly to the & operator, but it sets a bit to 1 if at least one of the bits in the same position in the operands is 1:

Bitwise XOR: ^

The bitwise XOR operator is a little different. It sets a bit to 1 only if the bits in the same position in the operands are different (one is 1 and the other is 0):

Bitwise NOT: ~

The bitwise NOT operator ( ~ ) inverts the bits of its operand. It switches 1s to 0s and 0s to 1s in the binary representation of a number:

Note: two’s complement is a method for representing negative integers in binary notation.

Bitwise shift operators: <<, >>, >>>

Bitwise shift operators are used to shift the bits of a binary number to the left or right. In JavaScript, there are three types: left shift ( << ), right shift ( >> ), and zero-fill right shift ( >>> ).

The left shift bitwise operator ( << ) moves bits to the left and fills in with zeros on the right. The right shift operator ( >> ) shifts bits to the right, discarding bits shifted off. The zero-fill right shift operator ( >>> ) also shifts bits to the right but fills in zeros on the left.

These operators are less common in everyday JavaScript coding, but they have uses in more specialized areas like low-level programming, binary data manipulation, and some types of mathematical calculations.

Other Operators

Apart from the commonly used arithmetic, comparison, logical, and bitwise operators, JavaScript offers a variety of unique operators for specific purposes. These include operators for handling conditional logic, managing object properties, controlling the order of operations, and more.

Conditional (ternary) operator: ? :

The conditional ternary operator ( ? : ) is a concise way to make decisions in our JavaScript code. It gets its name from being the only operator that takes three operands. The syntax for this conditional operator is as follows:

The operator works by first evaluating the condition. If the condition is true , it executes the expressionIfTrue , and if it’s false , it executes the expressionIfFalse :

In the code above, the ternary operator checks if age is greater than or equal to 18. Since age is 15, the condition evaluates to false , and 'Minor' is assigned to the status variable.

This operator can be a handy way to write concise if–else statements, but it can also make code more difficult to read if overused or used in complex conditions.

Spread operator: ...

The spread operator ( ... ) allows elements of an iterable (such as an array or a string) to be expanded in places where zero or more arguments or elements are expected. It can be used in function calls, array literals, and object literals:

The spread operator can be a handy tool for creating copies of arrays or objects, concatenating arrays, or passing the elements of an array as arguments to a function.

You can read more about the spread operator in Quick Tip: How to Use the Spread Operator in JavaScript .

Comma operator: ,

The comma operator ( , ) allows multiple expressions to be evaluated in a sequence and returns the result of the last expression. The expressions are evaluated from left to right.

It’s particularly useful when we need to include multiple expressions in a location that only allows for one, such as in the initialization or update sections of a for loop:

In the code above, the comma operator is used to declare and update two variables ( i and j ) in the for loop.

Optional chaining operator: ?.

Optional chaining is a relatively recent addition to JavaScript (as of ES2020) that simplifies the process of accessing deeply nested properties of objects. It helps us to write cleaner and safer code by providing a way to attempt to retrieve a property value without having to explicitly check if each reference in its chain exists:

In the above example, user?.address?.city accesses the city property of user.address if user and user.address both exist. Otherwise, it returns undefined . This approach avoids a common pitfall in JavaScript, where trying to access a property of undefined or null leads to a TypeError :

Before optional chaining, JavaScript developers had to use lengthy conditional logic to avoid such errors:

Pipeline operator: |>

The pipeline operator ( |> ) is intended to improve the readability of code that would otherwise be written with nested function calls. Essentially, it allows us to take the result of one expression and feed it into the next. This is particularly useful when we’re applying a series of transformations to a value:

With the pipeline operator, we’re able rewrite this code like so:

Be aware that, at the time of writing, the pipeline operator is at stage 2 of the ECMAScript proposal process , meaning it’s a draft and is undergoing further iteration and refinement.

Grouping operator: ()

The grouping operator ( () ) in JavaScript is used to change the precedence of evaluation in expressions. This operator doesn’t perform any operations on its value, but it controls the order in which calculations are carried out within an expression.

For example, multiplication and division have higher precedence than addition and subtraction. This means that, in an expression such as 2 + 3 * 4 , the multiplication is done first, resulting in 2 + 12 , and then the addition is performed, giving a result of 14 .

If we want to change the order of operations, we can use the grouping operator. For example, if we want the addition to be done before the multiplication in the previous example, we could write (2 + 3) * 4 . In this case, the addition is performed first, resulting in 5 * 4 , and then the multiplication is performed, giving a result of 20.

The grouping operator allows us to ensure that operations are performed in the order we intend, which can be critical in more complex mathematical or logical expressions.

We’ve spent this article delving into the broad and sometimes complex world of JavaScript operators. These operators enable us to manipulate data, control program flow, and carry out complex computations.

Understanding these operators is not a mere academic exercise; it’s a practical skill that can enhance our ability to write and understand JavaScript.

Remember the confusing code snippet we started with? Let’s revisit that and see if it makes more sense now:

In plain English, this code is finding the maximum of three numbers, x , y , and z .

It does this by using a combination of JavaScript’s ternary operator ( ? : ) and comparison operators ( > ).

Here’s how it works:

  • The expression (x > y ? x : y) checks whether x is greater than y .
  • If x is greater than y , it returns x ; otherwise, it returns y . In other words, it’s getting the maximum of x and y .
  • This result (the maximum of x and y ) is then compared to z with the > operator.
  • If the maximum of x and y is greater than z , then second ternary (x > y ? x : y) is evaluated.
  • In this ternary, x and y are compared once again and the greater of the two is returned.
  • Otherwise, if z is greater than the maximum of x and y , then z is the maximum of the three numbers, and it’s returned.

If you found this explanation confusing, that’s because it is. Nesting ternary operators like this isn’t very readable and the calculation could be better expressed using Math.max :

Nonetheless, understanding how JavaScript operators work is like learning the grammar of a new language. It can be challenging at first, but once we’ve grasped the basics, we’ll be constructing complex sentences (or in our case, code) with ease.

Before I go, if you found this guide helpful and are looking to dive deeper into JavaScript, why not check out Learn to Code with JavaScript over on SitePoint Premium. This book is an ideal starting point for beginners, teaching not just JavaScript — the world’s most popular programming language — but also essential coding techniques that can be applied to other programming languages.

It’s a fun and easy-to-follow guide that will turn you from a novice to a confident coder in no time.

Happy coding!

Frequently Asked Questions (FAQs) about JavaScript Operators

What are the different types of javascript operators and how are they used.

JavaScript operators are symbols that are used to perform operations on operands (values or variables). There are several types of operators in JavaScript, including arithmetic, assignment, comparison, logical, bitwise, string, ternary, and special operators. Each type of operator has a specific function. For example, arithmetic operators are used to perform mathematical operations, while assignment operators are used to assign values to variables. Comparison operators are used to compare two values, and logical operators are used to determine the logic between variables or values.

How does the assignment operator work in JavaScript?

The assignment operator in JavaScript is used to assign values to variables. It is represented by the “=” symbol. For example, if you have a variable named “x” and you want to assign the value “10” to it, you would write “x = 10”. This means that “x” now holds the value “10”. There are also compound assignment operators that perform an operation and an assignment in one step. For example, “x += 5” is the same as “x = x + 5”.

What is the difference between “==” and “===” in JavaScript?

In JavaScript, “==” and “===” are comparison operators, but they work slightly differently. The “==” operator compares the values of two operands for equality, after converting both operands to a common type. On the other hand, the “===” operator, also known as the strict equality operator, compares both the value and the type of the operands. This means that “===” will return false if the operands are of different types, even if their values are the same.

How do logical operators work in JavaScript?

Logical operators in JavaScript are used to determine the logic between variables or values. There are three logical operators: AND (&&), OR (||), and NOT (!). The AND operator returns true if both operands are true, the OR operator returns true if at least one of the operands is true, and the NOT operator returns the opposite of the operand.

What is the purpose of the ternary operator in JavaScript?

The ternary operator in JavaScript is a shorthand way of writing an if-else statement. It is called the ternary operator because it takes three operands: a condition, a value to return if the condition is true, and a value to return if the condition is false. The syntax is “condition ? value_if_true : value_if_false”. For example, “x = (y > 5) ? 10 : 20” means that if “y” is greater than 5, “x” will be assigned the value 10; otherwise, “x” will be assigned the value 20.

How are bitwise operators used in JavaScript?

Bitwise operators in JavaScript operate on 32-bit binary representations of the number values. They perform bit-by-bit operations on these binary representations. There are several bitwise operators, including AND (&), OR (|), XOR (^), NOT (~), left shift (<<), right shift (>>), and zero-fill right shift (>>>). These operators can be used for tasks such as manipulating individual bits in a number, which can be useful in certain types of programming, such as graphics or cryptography.

What are string operators in JavaScript?

In JavaScript, the plus (+) operator can be used as a string operator. When used with strings, the + operator concatenates (joins together) the strings. For example, “Hello” + ” World” would result in “Hello World”. There is also a compound assignment string operator (+=) that can be used to add a string to an existing string. For example, “text += ‘ World'” would add ” World” to the end of the existing string stored in the “text” variable.

What are special operators in JavaScript?

Special operators in JavaScript include the conditional (ternary) operator, the comma operator, the delete operator, the typeof operator, the void operator, and the in operator. These operators have specific uses. For example, the typeof operator returns a string indicating the type of a variable or value, and the delete operator deletes a property from an object.

How does operator precedence work in JavaScript?

Operator precedence in JavaScript determines the order in which operations are performed when an expression involves multiple operators. Operators with higher precedence are performed before those with lower precedence. For example, in the expression “2 + 3 * 4”, the multiplication is performed first because it has higher precedence than addition, so the result is 14, not 20.

Can you explain how increment and decrement operators work in JavaScript?

Increment (++) and decrement (–) operators in JavaScript are used to increase or decrease a variable’s value by one, respectively. They can be used in a prefix form (++x or –x) or a postfix form (x++ or x–). In the prefix form, the operation is performed before the value is returned, while in the postfix form, the operation is performed after the value is returned. For example, if x is 5, ++x will return 6, but x++ will return 5 (although x will be 6 the next time it is accessed).

PRDV401: Introduction to JavaScript I

compound assignment operators javascript

More on JavaScript Operators

Read this article to learn more about using operators in JavaScript. We will not use all of them in this introductory course. However, this is a condensed reference that contains tables of all operator categories. JavaScript categorizes operators by the task (such as arithmetic, comparison, or assignment).  Operators execute in a particular order. This is called o perator precedence  and tells JavaScript which part to evaluate first, second, third, and so on. This is an important concept. 

For example, consider how a program calculates a price using arithmetic operators:

Multiplication first the result is: $18 = 4 + 2 * 7 ( 2 * 7 = 14 + 4 ) Calculate left to right the result is: $42 = 4 + 2 * 7 ( 4+ 2 = 6 * 7 )

Assignment operators

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

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Return value and chaining

Like most expressions, assignments like x = y have a return value. It can be retrieved by e.g. assigning the expression or logging it:

The return value matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that (x = y) returns y , (x += y) returns the resulting sum x + y , (x **= y) returns the resulting power x ** y , and so on.

In the case of logical assignments, (x &&= y) , (x ||= y) , and (x ??= y) , the return value is that of the logical operation without the assignment, so x && y , x || y , and

Note that the return values are always based on the operands' values before the operation.

When chaining these expressions, each assignment is evaluated right-to-left . Consider these examples:

  • w = z = x = y is equivalent to w = (z = (x = y)) or x = y; z = y; w = y
  • z += x *= y is equivalent to z += (x *= y) or tmp = x * y; x *= y; z += tmp (except without the tmp ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Chapter 9. Operators

This chapter gives an overview of operators.

Operators and Objects

All operators coerce (as discussed in Type Coercion ) their operands to appropriate types. Most operators only work with primitive values (e.g., arithmetic operators and comparison operators). That means that objects are converted to primitives before anything is done with them. One example where that is unfortunate is the plus operator, which many languages use for array concatenation. That’s not so with JavaScript, however, where this operator converts arrays to strings and appends them:

There is no way to overload or customize operators in JavaScript, not even equality.

Assignment Operators

There are several ways to use the plain assignment operator:

An assignment is an expression that evaluates to the assigned value. That allows you to chain assignments. For example, the following statement assigns 0 to both y and x :

Compound Assignment Operators

A compound assignment operator is written as op= , where op is one of several binary operators and = is the assignment operator. The following two expressions are equivalent:

In other words, a compound assignment operator op= applies op to both operands and assigns the result to the first operand. Let’s look at an example of using the plus operator ( + ) via compound assignment:

The following are all compound assignment operators:

  • Arithmetic operations (see Arithmetic Operators ): *= , /= , %= , += , -=
  • Bitwise operations (see Binary Bitwise Operators ): <<= , >>= , >>>= , &= , ^= , |=
  • String concatenation (see Concatenation: The Plus (+) Operator ): +=

Equality Operators: === Versus ==

JavaScript has two ways of determining whether two values are equal:

  • Strict equality ( === ) and strict inequality ( !== ) consider only values that have the same type to be equal.
  • Normal (or “lenient”) equality ( == ) and inequality ( != ) try to convert values of different types before comparing them as with strict (in)equality.

Lenient equality is problematic in two regards. First, how it performs conversion is confusing. Second, due to the operators being so forgiving, type errors can remain hidden longer.

Always use strict equality and avoid lenient equality. You only need to learn about the latter if you want to know why it should be avoided.

Equality is not customizable. Operators can’t be overloaded in JavaScript, and you can’t customize how equality works. There are some operations where you often need to influence comparison—for example, Array.prototype.sort() (see Sorting and Reversing Elements (Destructive) ). That method optionally accepts a callback that performs all comparisons between array elements.

Strict Equality (===, !==)

Values with different types are never strictly equal. If both values have the same type, then the following assertions hold:

  • undefined === undefined
  • null === null

Two numbers:

  • Two booleans, two strings: obvious results

Two objects (including arrays and functions): x === y if and only if x and y are the same object; that is, if you want to compare different objects, you have to implement your own comparison algorithm:

  • Everything else: not strictly equal.

Pitfall: NaN

The special number value NaN (see NaN ) is not equal to itself:

Thus, you need to use other means to check for it, which are described in Pitfall: checking whether a value is NaN .

Strict inequality (!==)

A strict inequality comparison:

is equivalent to the negation of a strict equality comparison:

Normal (Lenient) Equality (==, !=)

The algorithm for comparing via normal equality works as follows. If both operands have the same type (one of the six specification types—Undefined, Null, Boolean, Number, String, and Object), then compare them via strict equality.

Otherwise, if the operands are:

undefined and null , then they are considered leniently equal:

  • A string and a number, then convert the string to a number and compare both operands via strict equality.
  • A boolean and a nonboolean, then convert the boolean to a number and compare leniently (again).
  • An object and a number or a string, then try to convert the object to a primitive (via the algorithm described in Algorithm: ToPrimitive()—Converting a Value to a Primitive ) and compare leniently (again).

Otherwise—if none of the aforementioned cases apply—the result of the lenient comparison is false .

Lenient inequality (!=)

An inequality comparison:

is equivalent to the negation of an equality comparison:

Pitfall: lenient equality is different from conversion to boolean

Step 3 means that equality and conversion to boolean (see Converting to Boolean ) work differently. If converted to boolean, numbers greater than 1 become true (e.g., in if statements). But those numbers are not leniently equal to true . The comments explain how the results were computed:

Similarly, while the empty string is equal to false , not all nonempty strings are equal to true :

Pitfall: lenient equality and strings

Some of the leniency can be useful, depending on what you want:

Other cases are problematic, due to how JavaScript converts strings to numbers (see Converting to Number ):

Pitfall: lenient equality and objects

If you compare an object to a nonobject, it is converted to a primitive, which leads to strange results:

However, two objects are only equal if they are they same object. That means that you can’t really compare two wrapper objects:

There Are No Valid Use Cases for ==

You sometimes read about valid use cases for lenient equality ( == ). This section lists them and points out better alternatives.

Use case: checking for undefined or null

The following comparison ensures that x is neither undefined nor null :

While this is a compact way of writing this check, it confuses beginners, and experts can’t be sure whether it is a typo or not. Thus, if you want to check whether x has a value, use the standard check for truthiness (covered in Truthy and Falsy Values ):

If you want to be more precise, you should perform an explicit check for both values:

Use case: working with numbers in strings

If you are not sure whether a value x is a number or a number-as-a-string, you can use checks such as the following:

The preceding checks whether x is either 123 or '123' . Again, this is very compact, and again, it is better to be explicit:

Use case: comparing wrapper instances with primitives

Lenient equals lets you compare primitives with wrapped primitives:

There are three reasons against this approach. First, lenient equality does not work between wrapped primitives:

Second, you should avoid wrappers anyway. Third, if you do use them, it is better to be explicit:

Ordering Operators

JavaScript knows the following ordering operators:

  • Less than ( < )
  • Less than or equal ( <= )
  • Greater than ( > )
  • Greater than or equal ( >= )

These operators work for numbers and for strings:

For strings, they are not very useful, because they are case-sensitive and don’t handle features such as accents well (for details, see Comparing Strings ).

The Algorithm

You evaluate a comparison:

by taking the following steps:

  • Ensure that both operands are primitives. Objects obj are converted to primitives via the internal operation ToPrimitive(obj, Number) (refer to Algorithm: ToPrimitive()—Converting a Value to a Primitive ), which calls obj.valueOf() and, possibly, obj.toString() to do so.
  • If both operands are strings, then compare them by lexicographically comparing the 16-bit code units (see Chapter 24 ) that represent the JavaScript characters of the string.
  • Otherwise, convert both operands to numbers and compare them numerically.

The other ordering operators are handled similarly.

The Plus Operator (+)

Roughly, the plus operator examines its operands. If one of them is a string, the other is also converted to a string and both are concatenated:

Otherwise, both operands are converted to numbers (see Converting to Number ) and added:

That means that the order in which you evaluate matters:

You evaluate an addition:

  • Ensure that both operands are primitives. Objects obj are converted to primitives via the internal operation ToPrimitive(obj) (refer to Algorithm: ToPrimitive()—Converting a Value to a Primitive ), which calls obj.valueOf() and, possibly, obj.toString() to do so. For dates, obj.toString() is called first.
  • If either operand is a string, then convert both to strings and return the concatenation of the results.
  • Otherwise, convert both operands to numbers and return the sum of the results.

Operators for Booleans and Numbers

The following operators only have operands of a single type and also produce results of that type. They are covered elsewhere.

Boolean operators:

Binary logical operators (see Binary Logical Operators: And (&&) and Or (||) ):

Logical Not (see Logical Not (!) ):

Number operators:

Arithmetic operators (see Arithmetic Operators ):

Bitwise operators (see Bitwise Operators ):

Special Operators

Here we will review special operators, namely the conditional, comma, and void operators.

The Conditional Operator ( ? : )

The conditional operator is an expression:

If the condition is true , the result is if_true ; otherwise, the result is if_false . For example:

The parentheses around the operator are not needed, but they make it easier to read.

The Comma Operator

The comma operator evaluates both operands and returns the result of right . Roughly, it does for expressions what the semicolon does for statements.

This example demonstrates that the second operand becomes the result of the operator:

This example demonstrates that both operands are evaluated:

The comma operator is confusing. It’s better to not be clever and to write two separate statements whenever you can.

The void Operator

The syntax for the void operator is:

which evaluates expr and returns undefined . Here are some examples:

Thus, if you implement void as a function, it looks as follows:

The void operator is associated closely with its operand, so use parentheses as necessary. For example, void 4+7 binds as (void 4)+7 .

What is void used for?

Under ECMAScript 5, void is rarely useful. Its main use cases are:

In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URL’s “content,” but only if the result isn’t undefined . Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

Why does JavaScript have a void operator?

According to JavaScript creator Brendan Eich, he added it to the language to help with javascript: links (one of the aforementioned use cases):

I added the void operator to JS before Netscape 2 shipped to make it easy to discard any non-undefined value in a javascript: URL. [ 12 ]

Categorizing Values via typeof and instanceof

If you want to categorize a value, you unfortunately have to distinguish between primitives and objects (refer back to Chapter 8 ) in JavaScript:

  • The typeof operator distinguishes primitives from objects and determines the types of primitives.
  • The instanceof operator determines whether an object is an instance of a given constructor. Consult Chapter 17 for more information on object-oriented programming in JavaScript.

typeof: Categorizing Primitives

The typeof operator:

returns a string describing what kind of value value is. Here are some examples:

typeof is used to distinguish primitives and objects and to categorize primitives (which cannot be handled by instanceof ). Unfortunately, the results of this operator are not completely logical and only loosely correspond to the types of the ECMAScript specification (which are explained in JavaScript’s Types ):

Pitfall: typeof null

Unfortunately, typeof null is 'object' . This is considered a bug ( null is not a member of the internal type Object), but it can’t be fixed, because doing so would break existing code. You thus have to be wary of null . For example, the following function checks whether value is an object:

Trying it out:

The history of typeof null

The first JavaScript engine represented JavaScript values as 32-bit words. The lowest 3 bits of such a word were used as a type tag, to indicate whether the value was an object, an integer, a double, a string, or a boolean (as you can see, even this early engine already stored numbers as integers if possible).

The type tag for objects was 000. In order to represent the value null , the engine used the machine language NULL pointer, a word where all bits are zero. typeof checked the type tag to determine the type of value, which is why it reported null to be an object. [ 13 ]

Checking whether a variable exists

has two use cases:

  • It determines whether x is undefined .
  • It determines whether the variable x exists.

Here are examples of both use cases:

For the first use case, comparing directly with undefined is usually a better choice. However, it doesn’t work for the second use case:

instanceof: Checking Whether an Object Is an Instance of a Given Constructor

The instanceof operator :

determines whether value has been created by the constructor Constr or a subconstructor. Here are some examples:

As expected, instanceof is false for the nonvalues undefined and null :

But it is also false for all other primitive values:

For details on instanceof , consult The instanceof Operator .

Object Operators

The following three operators work on objects. They are explained elsewhere:

[ 10 ] Strictly speaking, setting an array element is a special case of setting a property.

[ 11 ] Thanks to Brandon Benvie (@benvie), who told me about using void for IIFEs.

[ 12 ] Source: http://en.wikipedia.org/wiki/Bookmarklet

[ 13 ] Thanks to Tom Schuster (@evilpies) for pointing me to the source code of the first JavaScript engine.

Compound-Assignment Operators

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

Compound-Assignment Operators in Java

Java supports 11 compound-assignment operators:

Example Usage

To assign the result of an addition operation to a variable using the standard syntax:

But use a compound-assignment operator to effect the same outcome with the simpler syntax:

  • Java Expressions Introduced
  • Conditional Operators
  • Math Glossary: Mathematics Terms and Definitions
  • The Associative and Commutative Properties
  • Parentheses, Braces, and Brackets in Math
  • An Abbreviated JavaScript If Statement
  • Definition of Variable
  • Homework Guidelines for Elementary and Middle School Teachers
  • Order of Operations Worksheets
  • Arithmetic and Geometric Sequences
  • Reading and Writing Binary Numbers
  • The Whys and How-tos for Group Writing in All Content Areas
  • What Are Probability Axioms?
  • JavaScript Nested IF/ELSE Statements
  • Algorithms in Mathematics and Beyond
  • Using the Case (Switch) Ruby Statement

IMAGES

  1. Guide to Compound Assignment Operators in JavaScript

    compound assignment operators javascript

  2. Compound Assignment With Augmented Multiplication (Basic JavaScript

    compound assignment operators javascript

  3. Understanding JavaScript Operators With Types and Examples

    compound assignment operators javascript

  4. Compound assignment operators

    compound assignment operators javascript

  5. JavaScript Operators.

    compound assignment operators javascript

  6. Logical and Assignment Operators in Javascript

    compound assignment operators javascript

VIDEO

  1. Operators in JavaScript

  2. Arithmetic and Assignment operators Javascript Me

  3. Assignment Operator in javascript

  4. 7- Compound Pattern

  5. Javascript assignment operators in 2 minutes (Tagalog)

  6. 03 Operators in JavaScript

COMMENTS

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

  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. This allows multiple assignments to be chained in order to assign a single value to multiple variables. Try it Syntax js x = y Parameters x

  3. What are compound operators in JavaScript?

    Compound assignment operators in JavaScript serve the purpose of combining an assignment operation with another operation, such as arithmetic or bitwise operations. They allow you to perform a calculation and update a variable's value in a single, concise statement. What is the additive operator in JavaScript?

  4. JavaScript Assignment

    Assignment operators assign values to JavaScript variables. Shift Assignment Operators Bitwise Assignment Operators Logical Assignment Operators Note The Logical assignment operators are ES2020 . The = Operator The Simple Assignment Operator assigns a value to a variable. Simple Assignment Examples let x = 10; Try it Yourself » let x = 10 + y;

  5. Addition assignment (+=)

    The addition assignment (+=) operator performs addition (which is either numeric addition or string concatenation) on the two operands and assigns the result to the left operand.

  6. Guide to Compound Assignment Operators in JavaScript

    And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do. Let's use one of the more basic ones which is to have the addition assignment. sum += gradeOne; // 100. Now you can see that sum is equal to 100. Then if I do. sum += gradeTwo; // 180.

  7. compound assignment operators · WebPlatform Docs

    compound assignment operators Summary The following table lists JavaScript compound assignment operators. Syntax Assignment Operators See also Other articles Assignment Operator (=) Attributions Microsoft Developer Network: Article Beginners Concepts

  8. How To Do Math in JavaScript with Operators

    In addition to the standard assignment operator, JavaScript has compound assignment operators, which combine an arithmetic operator with =. For example, the addition operator will start with the original value, and add a new value. // Assign 27 to age variable let age = 27; age += 3; console. log (age);

  9. Expressions and operators

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

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

  11. Compound Assignment With Augmented Addition

    Compound Assignment With Augmented Addition. In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say: 1 myVar = myVar + 5; to add 5 to myVar. Since this is such a common pattern, there are operators which do both a ...

  12. Operators

    The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. ... Assignment operators. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. ... Compound assignment. Name Operator Meaning ...

  13. Demystifying JavaScript Operators: What Does That Symbol Mean?

    The commonly used arithmetic operators in JavaScript include addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Beyond these, we also have the modulus operator ( %...

  14. Assignment Operators in JavaScript

    The sign = denotes the simple assignment operator. JavaScript also has several compound assignment operators, which is actually shorthand for other operators. A list of all such operators are listed below. Table of Contents. ... Compound Assignment Operators. All operators except = listed in the table above are compound assignment operators ...

  15. freeCodeCamp.org

    Learn to Code — For Free

  16. Expressions and operators

    This chapter documents all the JavaScript language operators, expressions and keywords. Expressions and operators by category For an alphabetical listing see the sidebar on the left. Primary expressions Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). this

  17. Operators • JavaScript for impatient programmers (ES2022 edition)

    13.1 Making sense of operators. JavaScript's operators may seem quirky. With the following two rules, they are easier to understand: ... 13.3.2.2 The remaining compound assignment operators. For operators op other than || && ??, the following two ways of assigning are equivalent:

  18. javascript

    ... Functions that contain a compound let assignment Functions that contain a compound const assignment What does compound let assignment and compound const assignment mean? In ECMAScript 5.1 there was notion of compound assignment but in ECMAScript 2015, it seems there is no notion of any compound assignment there is only regular assignments.

  19. Compound Assignment With Augmented Addition

    Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.</p>\n<p dir=\"auto\">One such operator is the += operator.</p>\n<p dir=\"auto\"><code>myVar += 5;</code> will add 5 to myVar.</p>\n<h2 tabindex=\"-1\" dir=\"auto\"><a id=\"user-content-instructions\" class=\"anchor\" aria-h...

  20. More on JavaScript Operators: Assignment operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple 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. There are also compound assignment operators that are shorthand for the operations listed in the following table:

  21. Chapter 9. Operators

    A compound assignment operator is written as op=, where op is one of several binary operators and = is the assignment operator. The following two expressions are equivalent: myvar op= value myvar = myvar op value. In other words, a compound assignment operator op= applies op to both operands and assigns the result to the first operand. Let's look at an example of using the plus operator ...

  22. What Is a Compound-Assignment Operator?

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. Compound-Assignment Operators in Java Java supports 11 compound-assignment operators: += assigns the result of the addition.

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