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.

TutorialsTonight Logo

JAVASCRIPT ASSIGNMENT OPERATORS

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

Assignment Operators

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

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

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

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

javascript assignment operator

Assignment Operators List

Here is the list of all assignment operators in JavaScript:

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

Assignment operator

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

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

Addition assignment operator

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

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

Subtraction assignment operator

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

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

Multiplication assignment operator

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

Division assignment operator

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

Remainder assignment operator

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

Exponentiation assignment operator

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

Left shift assignment

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

Right shift assignment

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

Unsigned right shift assignment

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

Bitwise AND assignment

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

Bitwise OR assignment

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

Bitwise XOR assignment

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

Logical AND assignment

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

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

Logical OR assignment

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

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

Logical nullish assignment

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

Home » JavaScript Tutorial » JavaScript Logical Assignment Operators

JavaScript Logical Assignment Operators

Summary : in this tutorial, you’ll learn about JavaScript logical assignment operators, including the logical OR assignment operator ( ||= ), the logical AND assignment operator ( &&= ), and the nullish assignment operator ( ??= ).

ES2021 introduces three logical assignment operators including:

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

The following table shows the equivalent of the logical assignments operator:

The Logical OR assignment operator

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

In this syntax, the ||= operator only assigns y to x if x is falsy. For example:

In this example, the title variable is undefined , therefore, it’s falsy. Since the title is falsy, the operator ||= assigns the 'untitled' to the title . The output shows the untitled as expected.

See another example:

In this example, the title is 'JavaScript Awesome' so it is truthy. Therefore, the logical OR assignment operator ( ||= ) doesn’t assign the string 'untitled' to the title variable.

The logical OR assignment operator:

is equivalent to the following statement that uses the logical OR operator :

Like the logical OR operator, the logical OR assignment also short-circuits. It means that the logical OR assignment operator only performs an assignment when the x is falsy.

The following example uses the logical assignment operator to display a default message if the search result element is empty:

The Logical AND assignment operator

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

The logical AND assignment operator also short-circuits. It means that

is equivalent to:

The following example uses the logical AND assignment operator to change the last name of a person object if the last name is truthy:

The nullish coalescing assignment operator

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

It’s equivalent to the following statement that uses the nullish coalescing operator :

The following example uses the nullish coalescing assignment operator to add a missing property to an object:

In this example, the user.nickname is undefined , therefore, it’s nullish. The nullish coalescing assignment operator assigns the string 'anonymous' to the user.nickname property.

The following table illustrates how the logical assignment operators work:

  • The logical OR assignment ( x ||= y ) operator only assigns y to x if x is falsy.
  • The logical AND assignment ( x &&= y ) operator only assigns y to x if x is truthy.
  • The nullish coalescing assignment ( x ??= y ) operator only assigns y to x if x is nullish.
  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

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:

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.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. 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. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A 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. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • 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
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • 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: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()
  • JavaScript CallBack Function
  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

JavaScript Comparison and Logical Operators

JavaScript Booleans

JavaScript Bitwise Operators

JavaScript Ternary Operator

  • JavaScript Object.is()
  • JavaScript console.log()

JavaScript operators are special symbols that perform unique operations on one or more operands (values). For example,

The + operator performs addition, we have used it here to add the operands 2 and 3 .

JavaScript Operator Types

Here is a list of different JavaScript operators you will learn in this tutorial:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • String Operators
  • Miscellaneous Operators

1. JavaScript Arithmetic Operators

We use arithmetic operators to perform arithmetic calculations like addition, subtraction, etc. For example,

Here, we used the - operator to subtract 3 from 5 .

Commonly Used Arithmetic Operators

Example 1: arithmetic operators in javascript, example 2: javascript increment and decrement operators.

To learn more about the increment and decrement operators, visit Increment ++ and Decrement -- Operators .

2. JavaScript Assignment Operators

We use assignment operators to assign values to variables. For example,

Here, we used the = operator to assign the value 5 to variable x .

Commonly Used Assignment Operators

Example 3: assignment operators in javascript, 3. javascript comparison operators.

We use comparison operators to compare two values and return a boolean value ( true or false ). For example,

Here, we have used the > comparison operator to check whether a (whose value is 3 ) is greater than b (whose value is 2 ).

Since 3 is greater than 2 , we get true as output.

Commonly Used Comparison Operators

Example 4: comparison operators in javascript.

The equality operators ( == and != ) convert both operands to the same type before comparing their values. For example,

Here, we used the == operator to compare the number 3 and the string 3 .

By default, JavaScript converts string 3 to number 3 and compares the values.

However, the strict equality operators ( === and !== ) do not convert operand types before comparing their values. For example,

Here, JavaScript didn't convert string 4 to number 4 before comparing their values.

Thus, the result is false , as number 4 isn't equal to string 4 .

4. JavaScript Logical Operators

We use logical operators to perform logical operations on boolean values. For example,

Here, && is the logical operator AND . Since both x < 6 and y < 5 are true , the combined result is true .

Commonly Used Logical Operators

Example 5: logical operators in javascript.

Note: We use comparison and logical operators in decision-making and loops. You will learn about them in detail in later tutorials.

We use bitwise operators to perform binary operations on integers.

Note: We rarely use bitwise operators in everyday programming. If you are interested, visit JavaScript Bitwise Operators to learn more.

6. JavaScript String Operators

In JavaScript, you can use the + operator to concatenate (join) two or more strings . For example,

Here, we used + on strings to perform concatenation. However, when we use + with numbers, it performs addition.

7. JavaScript Miscellaneous Operators

JavaScript has many more operators besides the ones we listed above.

Thus, we have categorized them as miscellaneous operators. You will learn them in detail in later tutorials.

Commonly Used Miscellaneous Operators

  • JavaScript typeof Operator

Table of Contents

  • Introduction
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript String Operators
  • JavaScript Miscellaneous Operators

Video: JavaScript Operators

Sorry about that.

Related Tutorials

JavaScript Tutorial

James Hibbard

Demystifying JavaScript Operators: What Does That Symbol Mean?

Share this article

Demystifying JavaScript Operators: What Does That Symbol Mean?

What are JavaScript Operators?

A quick word on terminology, arithmetic operators, assignment operators, comparison operators, logical operators, bitwise operators, other operators, frequently asked questions (faqs) about javascript operators.

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.

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.

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

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

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!

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

Network admin, freelance web developer and editor at SitePoint .

SitePoint Premium

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

JS Arithmetic Operators

  • Addition(+) Arithmetic Operator in JavaScript
  • Subtraction(-) Arithmetic Operator in JavaScript
  • Multiplication(*) Arithmetic Operator in JavaScript
  • Division(/) Arithmetic Operator in JavaScript
  • Modulus(%) Arithmetic Operator in JavaScript
  • Exponentiation(**) Arithmetic Operator in JavaScript
  • Increment(+ +) Arithmetic Operator in JavaScript
  • Decrement(--) Arithmetic Operator in JavaScript
  • JavaScript Arithmetic Unary Plus(+) Operator
  • JavaScript Arithmetic Unary Negation(-) Operator

JS Assignment Operators

  • Addition Assignment (+=) Operator in Javascript
  • Subtraction Assignment( -=) Operator in Javascript
  • Multiplication Assignment(*=) Operator in JavaScript
  • Division Assignment(/=) Operator in JavaScript
  • JavaScript Remainder Assignment(%=) Operator
  • Exponentiation Assignment(**=) Operator in JavaScript

Left Shift Assignment (<<=) Operator in JavaScript

  • Right Shift Assignment(>>=) Operator in JavaScript
  • Bitwise AND Assignment (&=) Operator in JavaScript
  • Bitwise OR Assignment (|=) Operator in JavaScript
  • Bitwise XOR Assignment (^=) Operator in JavaScript
  • JavaScript Logical AND assignment (&&=) Operator
  • JavaScript Logical OR assignment (||=) Operator
  • Nullish Coalescing Assignment (??=) Operator in JavaScript

JS Comparison Operators

  • Equality(==) Comparison Operator in JavaScript
  • Inequality(!=) Comparison Operator in JavaScript
  • Strict Equality(===) Comparison Operator in JavaScript
  • Strict Inequality(!==) Comparison Operator in JavaScript
  • Greater than(>) Comparison Operator in JavaScript
  • Greater Than or Equal(>=) Comparison Operator in JavaScript
  • Less Than or Equal(

JS Logical Operators

  • NOT(!) Logical Operator inJavaScript
  • AND(&&) Logical Operator in JavaScript
  • OR(||) Logical Operator in JavaScript

JS Bitwise Operators

  • AND(&) Bitwise Operator in JavaScript
  • OR(|) Bitwise Operator in JavaScript
  • XOR(^) Bitwise Operator in JavaScript
  • NOT(~) Bitwise Operator in JavaScript
  • Left Shift (
  • Right Shift (>>) Bitwise Operator in JavaScript
  • Zero Fill Right Shift (>>>) Bitwise Operator in JavaScript

JS Unary Operators

  • JavaScript typeof Operator
  • JavaScript delete Operator

JS Relational Operators

  • JavaScript in Operator
  • JavaScript Instanceof Operator

JS Other Operators

  • JavaScript String Operators
  • JavaScript yield Operator
  • JavaScript Pipeline Operator
  • JavaScript Grouping Operator

The Left Shift Assignment Operator is represented by “<<=”. This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator’s left as a 32-bit binary number. This can also be explained as the number is shifted to the left by the integer which is the right of the operator and assign the result to the variable.

Where –

  • a is the first operand, and
  • b is the second operand.

Example 1: In this example, we will see the implementation of the left shift assignment.

Example 2: In this example, we will see left shift operator is not used for the negative number.

Example 3: In this example, we will see the implementation of the left shift assignment operator.

We have a complete list of Javascript Assignment Operators, Please check this article Javascript Assignment Operator .

Supported Browser:

Please Login to comment...

Similar reads.

  • Web Technologies
  • Google Releases ‘Prompting Guide’ With Tips For Gemini In Workspace
  • Google Cloud Next 24 | Gmail Voice Input, Gemini for Google Chat, Meet ‘Translate for me,’ & More
  • 10 Best Viber Alternatives for Better Communication
  • 12 Best Database Management Software in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. JavaScript Operators.

    assignment operator in js

  2. What is operator in javascript with example?

    assignment operator in js

  3. Javascript Assignment Operators (with Examples)

    assignment operator in js

  4. JavaScript Assignment Operators

    assignment operator in js

  5. Operators in the Javascript

    assignment operator in js

  6. JavaScript Assignment Operators

    assignment operator in js

VIDEO

  1. Ternary Operator in Java (?:) || Conditional Operator with Source Code #java #ternary

  2. Saudi Arabia jobs

  3. সি: Operators in C Programming in One Video

  4. Statistics 2 Week 9 Graded Assignment Solution // IITM BS Online Degree Program || Foundation

  5. What are assignment operators in javascript

  6. 021 JavaScript Assignment Operator

COMMENTS

  1. JavaScript Assignment

    JavaScript Assignment Operators. Assignment operators assign values to JavaScript variables. Operator Example Same As = x = y: x = y += x += y: x = x + y-= x -= y: x = x - y *= x *= y: ... The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

  2. Assignment (=)

    The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...

  3. JavaScript Assignment Operators

    Division Assignment Operator (/=) The Division Assignment operator divides a variable by the value of the right operand and assigns the result to the variable. Example: Javascript. let yoo = 10; const moo = 2; // Expected output 5 console.log(yoo = yoo / moo); // Expected output Infinity console.log(yoo /= 0); Output:

  4. Expressions and operators

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

  5. JavaScript Assignment Operators

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

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

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

  8. Javascript Assignment Operators (with Examples)

    Here is the list of all assignment operators in JavaScript: In the following table if variable a is not defined then assume it to be 10. Operator Description Example Equivalent to = Assignment operator: a = 10: a = 10 += Addition assignment operator: a += 10: a = a + 10-= Subtraction assignment operator: a -= 10: a = a - 10 *=

  9. JavaScript Logical Assignment Operators

    The logical OR assignment operator ( ||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy: In this syntax, the ||= operator only assigns y to x if x is falsy. For example: console .log(title); Code language: JavaScript (javascript) Output: In this example, the title variable is undefined ...

  10. Expressions and operators

    The shorthand assignment operator += can also be used to concatenate strings. For example, var mystring = 'alpha'; mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring. Conditional (ternary) operator. The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two ...

  11. JavaScript Assignment Operators

    The JavaScript Assignment operators are used to assign values to the declared variables. Equals (=) operator is the most commonly used assignment operator. For example: var i = 10; The below table displays all the JavaScript assignment operators. JavaScript Assignment Operators. Example. Explanation. =.

  12. 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. List of Assignment operators; Simple Assignement Operator; Compound Assignment Operators;

  13. JavaScript OR (||) variable assignment explanation

    The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned. For example: "foo" || "bar"; // returns "foo".

  14. JavaScript Operators (with Examples)

    2. JavaScript Assignment Operators. We use assignment operators to assign values to variables. For example, let x = 5; Here, we used the = operator to assign the value 5 to variable x. Commonly Used Assignment Operators

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

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

  16. Bitwise OR Assignment (|=) Operator in JavaScript

    The Bitwise OR Assignment Operator in Javascript is represented by (|=). This operator is used to perform a bitwise OR operation on both operands and assign the result to the left operands. Syntax: Where -. Example 1: In this example, we will use basic numeric values to perform Bitwise OR Assignment Operation. Output: In this example, the ...

  17. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  18. Expressions and operators

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

  19. Multiplication Assignment(*=) Operator in JavaScript

    Multiplication Assignment Operator (*=) in JavaScript is used to multiply two operands and assign the result to the right operand. Syntax: variable1 *= variable2. // variable1 = variable1 * variable2. Example 1: In this example, we multiply two numerical values using the Multiplication Assignment Operator (*=) and assign the result variable in ...

  20. [committed] c++: Fix ICE with weird copy assignment operator [PR114572]

    > > While ctors/dtors don't return anything (undeclared void or this pointer > on arm) and copy assignment operators normally return a reference to *this, > it isn't invalid to return uselessly some class object which might need > destructing, but the OpenMP clause handling code wasn't expecting that. > > The following patch fixes that.

  21. Addition Assignment (+=) Operator in Javascript

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

  22. Right Shift Assignment(>>=) Operator in JavaScript

    The Right Shift Assignment Operator is represented by ">>=". This operator shifts the first operand to the right and assigns the result to the variable. It can also be explained as shifting the first operand to the right in a specified amount of bits which is the second operand integer and then assigning the result to the first operand. Syntax:

  23. Left Shift Assignment (<<=) Operator in JavaScript

    The Left Shift Assignment Operator is represented by "<<=". This operator moves the specified number of bits to the left and assigns that result to the variable. We can fill the vacated place by 0. The left shift operator treats the integer stored in the variable to the operator's left as a 32-bit binary number.