JS Reference

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

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

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators

Comparison Operators

Logical operators.

  • Conditional Operators
  • Type Operators

JavaScript Arithmetic Operators

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

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

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

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

Advertisement

JavaScript String Operators

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

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

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

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

Conditional (Ternary) Operator

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

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

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

The Nullish Coalescing Operator (??)

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

Otherwise it returns the second argument.

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

The Optional Chaining Operator (?.)

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

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

JavaScript Bitwise Operators

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

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

The typeof Operator

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

Please observe:

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

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

Both array and date return object as type.

The delete Operator

The delete operator deletes a property from an object:

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

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

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

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

This can crash your application.

The Spread (...) Operator

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

The in Operator

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

Object Example

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

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

See the examples below.

Predefined Objects

The instanceof operator.

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

The void Operator

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

JavaScript Operator Precedence

Get Certified

COLOR PICKER

colorpicker

Contact Sales

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

Report Error

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

Top Tutorials

Top references, top examples, get certified.

  • 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

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

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

Learn JavaScript Operators – Logical, Comparison, Ternary, and More JS Operators With Examples

Nathan Sebhastian

JavaScript has many operators that you can use to perform operations on values and variables (also called operands)

Based on the types of operations these JS operators perform, we can divide them up into seven groups:

Arithmetic Operators

Assignment operators, comparison operators, logical operators.

  • Ternary Operators

The typeof Operator

Bitwise operators.

In this handbook, you're going to learn how these operators work with examples. Let's start with arithmetic operators.

The arithmetic operators are used to perform mathematical operations like addition and subtraction.

These operators are frequently used with number data types, so they are similar to a calculator. The following example shows how you can use the + operator to add two variables together:

Here, the two variables x and y are added together using the plus + operator. We also used the console.log() method to print the result of the operation to the screen.

You can use operators directly on values without assigning them to any variable too:

In JavaScript, we have 8 arithmetic operators in total. They are:

  • Subtraction -
  • Multiplication *
  • Remainder %
  • Exponentiation **
  • Increment ++
  • Decrement --

Let's see how these operators work one by one.

1. Addition operator

The addition operator + is used to add two or more numbers together. You've seen how this operator works previously, but here's another example:

You can use the addition operator on both integer and floating numbers.

2. Subtraction operator

The subtraction operator is marked by the minus sign − and you can use it to subtract the right operand from the left operand.

For example, here's how to subtract 3 from 5:

3. Multiplication operator

The multiplication operator is marked by the asterisk * symbol, and you use it to multiply the value on the left by the value on the right of the operator.

4. Division operator

The division operator / is used to divide the left operand by the right operand. Here are some examples of using the operator:

5. Remainder operator

The remainder operator % is also known as the modulo or modulus operator. This operator is used to calculate the remainder after a division has been performed.

A practical example should make this operator easier to understand, so let's see one:

The number 10 can't be divided by 3 perfectly. The result of the division is 3 with a remainder of 1. The remainder operator simply returns that remainder number.

If the left operand can be divided with no remainder, then the operator returns 0.

This operator is commonly used when you want to check if a number is even or odd. If a number is even, dividing it by 2 will result in a remainder of 0, and if it's odd, the remainder will be 1.

6. Exponentiation operator

The exponentiation operator is marked by two asterisks ** . It's one of the newer JavaScript operators and you can use it to calculate the power of a number (based on its exponent).

For example, here's how to calculate 10 to the power of 3:

Here, the number 10 is multiplied by itself 3 times (10 _ 10 _ 10)

The exponentiation operator gives you an easy way to find the power of a specific number.

7. Increment operator

The increment ++ operator is used to increase the value of a number by one. For example:

This operator gives you a faster way to increase a variable value by one. Without the operator, here's how you increment a variable:

Using the increment operator allows you to shorten the second line. You can place this operator before or next to the variable you want to increment:

Both placements shown above are valid. The difference between prefix (before) and postfix (after) placements is that the prefix position will execute the operator after that line of code has been executed.

Consider the following example:

Here, you can see that placing the increment operator next to the variable will print the variable as if it has not been incremented.

When you place the operator before the variable, then the number will be incremented before calling the console.log() method.

8. Decrement operator

The decrement -- operator is used to decrease the value of a number by one. It's the opposite of the increment operator:

Please note that you can only use increment and decrement operators on a variable. An error occurs when you try to use these operators directly on a number value:

You can't use increment or decrement operator on a number directly.

Arithmetic operators summary

Now you've learned the 8 types of arithmetic operators. Excellent! Keep in mind that you can mix these operators to perform complex mathematical equations.

For example, you can perform an addition and multiplication on a set of numbers:

The order of operations in JavaScript is the same as in mathematics. Multiplication, division, and exponentiation take a higher priority than addition or subtraction (remember that acronym PEMDAS? Parentheses, exponents, multiplication and division, addition and subtraction – there's your order of operations).

You can use parentheses () to change the order of the operations. Wrap the operation you want to execute first as follows:

When using increment or decrement operators together with other operators, you need to place the operators in a prefix position as follows:

This is because a postfix increment or decrement operator will not be executed together with other operations in the same line, as I have explained previously.

Let's try some exercises. Can you guess the result of these operations?

And that's all for arithmetic operators. You've done a wonderful job learning about these operators.

Let's take a short five-minute break before proceeding to the next type of operators.

The second group of operators we're going to explore is the assignment operators.

Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before:

After the basic assignment operator, there are 5 more assignment operators that combine mathematical operations with the assignment. These operators are useful to make your code clean and short.

For example, suppose you want to increment the x variable by 2. Here's how you do it with the basic assignment operator:

There's nothing wrong with the code above, but you can use the addition assignment += to rewrite the second line as follows:

There are 7 kinds of assignment operators that you can use in JavaScript:

The arithmetic operators you've learned in the previous section can be combined with the assignment operator except the increment and decrement operators.

Let's have a quick exercise. Can you guess the results of these assignments?

Now you've learned about assignment operators. Let's continue and learn about comparison operators.

As the name implies, comparison operators are used to compare one value or variable with something else. The operators in this category always return a boolean value: either true or false .

For example, suppose you want to compare if a variable's value is greater than 1. Here's how you do it:

The greater than > operator checks if the value on the left operand is greater than the value on the right operand.

There are 8 kinds of comparison operators available in JavaScript:

Here are some examples of using comparison operators:

The comparison operators are further divided in two types: relational and equality operators.

The relational operators compare the value of one operand relative to the second operand (greater than, less than)

The equality operators check if the value on the left is equal to the value on the right. They can also be used to compare strings like this:

String comparisons are case-sensitive, as shown in the example above.

JavaScript also has two versions of the equality operators: loose and strict.

In strict mode, JavaScript will compare the values without performing a type coercion. To enable strict mode, you need to add one more equal = symbol to the operation as follows:

Since type coercion might result in unwanted behavior, you should use the strict equality operators anytime you do an equality comparison.

Logical operators are used to check whether one or more expressions result in either true or false .

There are three logical operators available in JavaScript:

These operators can only return Boolean values. For example, you can determine whether '7 is greater than 2' and '5 is greater than 4':

These logical operators follow the laws of mathematical logic:

  • && AND operator – if any expression returns false , the result is false
  • || OR operator – if any expression returns true , the result is true
  • ! NOT operator – negates the expression, returning the opposite.

Let's do a little exercise. Try to run these statements on your computer. Can you guess the results?

These logical operators will come in handy when you need to assert that a specific requirement is fulfilled in your code.

Let's say a happyLife requires a job with highIncome and supportiveTeam :

Based on the requirements, you can use the logical AND operator to check whether you have both requirements. When one of the requirements is false , then happyLife equals false as well.

Ternary Operator

The ternary operator (also called the conditional operator) is the only JavaScipt operator that requires 3 operands to run.

Let's imagine you need to implement some specific logic in your code. Suppose you're opening a shop to sell fruit. You give a $3 discount when the total purchase is $20 or more. Otherwise, you give a $1 discount.

You can implement the logic using an if..else statement as follows:

The code above works fine, but you can use the ternary operator to make the code shorter and more concise as follows:

The syntax for the ternary operator is condition ? expression1 : expression2 .

You need to write the condition to evaluate followed by a question ? mark.

Next to the question mark, you write the expression to execute when the condition evaluates to true , followed by a colon : symbol. You can call this expression1 .

Next to the colon symbol, you write the expression to execute when the condition evaluates to false . This is expression2 .

As the example above shows, the ternary operator can be used as an alternative to the if..else statement.

The typeof operator is the only operator that's not represented by symbols. This operator is used to check the data type of the value you placed on the right side of the operator.

Here are some examples of using the operator:

The typeof operator returns the type of the data as a string. The 'number' type represents both integer and float types, the string and boolean represent their respective types.

Arrays, objects, and the null value are of object type, while undefined has its own type.

Bitwise operators are operators that treat their operands as a set of binary digits, but return the result of the operation as a decimal value.

These operators are rarely used in web development, so you can skip this part if you only want to learn practical stuff. But if you're interested to know how they work, then let me show you an example.

A computer uses a binary number system to store decimal numbers in memory. The binary system only uses two numbers, 0 and 1, to represent the whole range of decimal numbers we humans know.

For example, the decimal number 1 is represented as binary number 00000001, and the decimal number 2 is represented as 00000010.

I won't go into detail on how to convert a decimal number into a binary number as that's too much to include in this guide. The main point is that the bitwise operators operate on these binary numbers.

If you want to find the binary number from a specific decimal number, you can Google for the "decimal to binary calculator".

There are 7 types of bitwise operators in JavaScript:

  • Left Shift <<
  • Right Shift >>
  • Zero-fill Right Shift >>>

Let's see how they work.

1. Bitwise AND operator

The bitwise operator AND & returns a 1 when the number 1 overlaps in both operands. The decimal numbers 1 and 2 have no overlapping 1, so using this operator on the numbers return 0:

2. Bitwise OR operator

On the other hand, the bitwise operator OR | returns all 1s in both decimal numbers.

The binary number 00000011 represents the decimal number 3, so the OR operator above returns 3.

Bitwise XOR operator

The Bitwise XOR ^ looks for the differences between two binary numbers. When the corresponding bits are the same, it returns 0:

5 = 00000101

Bitwise NOT operator

Bitwise NOT ~ operator inverts the bits of a decimal number so 0 becomes 1 and 1 becomes 0:

Bitwise Left Shift operator

Bitwise Left Shift << shifts the position of the bit by adding zeroes from the right.

The excess bits are then discarded, changing the decimal number represented by the bits. See the following example:

The right operand is the number of zeroes you will add to the left operand.

Bitwise Right Shift operator

Bitwise Right Shift >> shifts the position of the bits by adding zeroes from the left. It's the opposite of the Left Shift operator:

Bitwise Zero-fill Right Shift operator

Also known as Unsigned Right Shift operator, the Zero-fill Right Shift >>> operator is used to shift the position of the bits to the right, while also changing the sign bit to 0 .

This operator transforms any negative number into a positive number, so you can see how it works when passing a negative number as the left operand:

In the above example, you can see that the >> and >>> operators return different results. The Zero-fill Right Shift operator has no effect when you use it on a positive number.

Now you've learned how the bitwise operators work. If you think they are confusing, then you're not alone! Fortunately, these operators are scarcely used when developing web applications.

You don't need to learn them in depth. It's enough to know what they are.

In this tutorial, you've learned the 7 types of JavaScript operators: Arithmetic, assignment, comparison, logical, ternary, typeof, and bitwise operators.

These operators can be used to manipulate values and variables to achieve a desired outcome.

Congratulations on finishing this guide!

If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book Beginning Modern JavaScript here .

beginning-js-cover

The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.

Here's my promise: You will actually feel like you understand what you're doing with JavaScript.

Until next time!

JavaScript Full Stack Developer currently working with fullstack JS using React and Express. Nathan loves to write about his experience in programming to help other people.

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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.

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:

Specifications

Browser compatibility.

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

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

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 is used to assign 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

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:

  • 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
  • Using promises
  • Iterators and generators
  • Meta programming
  • JavaScript modules
  • Client-side web APIs
  • 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.ListFormat
  • Intl.Locale
  • Intl.NumberFormat
  • Intl.PluralRules
  • Intl.RelativeTimeFormat
  • ReferenceError
  • SharedArrayBuffer
  • 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
  • (currently at stage 1) pipes the value of an expression into a function. This allows the creation of chained function calls in a readable manner. The result is syntactic sugar in which a function call with a single argument can be written like this:">Pipeline operator
  • 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 await...of
  • for each...in
  • function declaration
  • import.meta
  • try...catch
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • The arguments object
  • 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: 'x' is not iterable
  • TypeError: More arguments needed
  • TypeError: Reduce of empty array with no initial value
  • TypeError: can't access dead object
  • TypeError: can't access property "x" of "y"
  • TypeError: can't assign to property "x" on "y": not an 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: cannot use 'in' operator to search for 'x' in 'y'
  • TypeError: cyclic object value
  • TypeError: invalid 'instanceof' 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
  • X.prototype.y called on incompatible type
  • 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
  • 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

Learn the best of web development

Get the latest and greatest from MDN delivered straight to your inbox.

Thanks! Please check your inbox to confirm your subscription.

If you haven’t previously confirmed a subscription to a Mozilla-related newsletter you may have to do so. Please check your inbox or your spam filter for an email from us.

MarketSplash

A Closer Look At JavaScript Operators And Their Significance

Javascript operators play a pivotal role in scripting. From arithmetic to logical operations, understanding these operators is the key to unlocking the language's full potential.

💡 KEY INSIGHTS

  • In JavaScript, arithmetic operators like `+`, `-`, `*`, and `/` are used for performing mathematical calculations, similar to their usage in mathematics.
  • The `==` and `===` operators differ significantly; the former compares values after type coercion, while the latter compares both value and type.
  • JavaScript includes logical operators such as `&&` (and), `||` (or), and `!` (not), which are crucial for controlling program flow based on conditions.
  • Assignment operators like `=`, `+=`, `-=`, `*=`, and `/=` are used to assign and sometimes simultaneously process values in a concise manner.

Javascript operators are fundamental building blocks that enhance the efficiency of your code. They allow for concise expressions, making operations more readable and streamlined. As you progress in your coding journey, a solid grasp of these operators becomes essential to write clean and effective scripts.

Types of Javascript Operators

Arithmetic operators, comparison operators, logical operators, assignment operators, bitwise operators, string operators, ternary operator, type operators, operator precedence, frequently asked questions.

Javascript operators are essential tools that allow us to perform operations on variables and values. They can be broadly categorized based on their functionality.

Arithmetic Operators are used to perform mathematical operations. For instance, addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ).

Comparison Operators are used to compare two values. Common ones include equals to ( == ), not equals to ( != ), greater than ( > ), and less than ( < ).

Logical Operators evaluate the logic between variables or values. The primary logical operators are AND ( && ), OR ( || ), and NOT ( ! ).

Assignment Operators assign values to variables. The most common is the equals ( = ) operator, but there are others like add and assign ( += ), subtract and assign ( -= ).

Bitwise Operators operate on 32-bit binary representations of numbers. These include bitwise AND ( & ), bitwise OR ( | ), and bitwise XOR ( ^ ).

String Operators are used to manipulate strings. The most common is the concatenation ( + ) operator.

Ternary Operator is a shorthand for the if-else statement. It's represented as ? : .

Type Operators determine the type of a variable. The typeof operator is widely used for this purpose.

Each of these operators plays a crucial role in Javascript programming, enabling developers to create dynamic and interactive web applications.

Addition Operator

Subtraction operator, multiplication operator, division operator, modulus operator, increment and decrement, exponentiation operator.

In Javascript, Arithmetic Operators are used to perform mathematical calculations on numbers. These operators are fundamental for any kind of numerical computation in scripts.

The Addition ( + ) operator adds numbers together. It can also be used to concatenate strings.

The Subtraction ( - ) operator subtracts one number from another.

The Multiplication ( * ) operator multiplies numbers.

The Division ( / ) operator divides one number by another.

The Modulus ( % ) operator returns the remainder of a division.

The Increment ( ++ ) and Decrement ( -- ) operators increase or decrease a number by one, respectively.

The Exponentiation ( ** ) operator raises a number to the power of another number.

Arithmetic operators are fundamental in Javascript, allowing for a wide range of mathematical operations, from basic calculations to complex algorithms. Familiarity with these operators is essential for effective coding.

Not Equal To

Strictly equal to, strictly not equal to, greater than and less than, greater than or equal to and less than or equal to.

In Javascript, Comparison Operators are essential tools that allow us to compare values, whether they are numbers, strings, or other data types. These operators return a boolean value, either true or false , based on the outcome of the comparison.

The Equal To ( == ) operator checks if two values are equivalent, without considering their data type.

The Not Equal To ( != ) operator checks if two values are not equivalent.

The Strictly Equal To ( === ) operator checks if two values are equivalent and of the same data type.

The == operator will compare for equality after doing any necessary type conversions . The === operator will not do the conversion, so if two values are not the same type === will simply return false . Both are equally quick.

The Strictly Not Equal To ( !== ) operator checks if two values are not equivalent or if they are of different data types.

The Greater Than ( > ) and Less Than ( < ) operators compare two values to determine if one is larger or smaller than the other.

The Greater Than or Equal To ( >= ) and Less Than or Equal To ( <= ) operators compare two values, considering equality as well.

Understanding and effectively using comparison operators is crucial for decision-making in code, allowing for conditions, loops, and other control structures to function correctly.

Logical AND

Logical not, short-circuit evaluation.

In Javascript, Logical Operators are used to determine the logic between multiple conditions. These operators are fundamental for creating conditions in various control structures, such as if statements and loops.

The Logical AND ( && ) operator returns true if both conditions are true. Otherwise, it returns false .

The Logical OR ( || ) operator returns true if at least one of the conditions is true. If both are false, it returns false .

The Logical NOT ( ! ) operator inverts the value of a condition. If a condition is true , it returns false , and vice versa.

Logical operators in Javascript use Short-Circuit Evaluation . This means that as soon as the outcome of the operation is determined, the evaluation stops.

Logical operators play a pivotal role in decision-making within scripts. They allow developers to create complex conditions and ensure that code runs under the desired circumstances.

Basic Assignment

Addition assignment, subtraction assignment, multiplication assignment, division assignment, modulus assignment.

In Javascript, Assignment Operators are used to assign values to variables. They are fundamental tools that help in storing and updating data values efficiently within scripts.

The Basic Assignment ( = ) operator assigns a value to a variable.

The Addition Assignment ( += ) operator adds a value to a variable and then assigns the result to that variable.

The Subtraction Assignment ( -= ) operator subtracts a value from a variable and then assigns the result to that variable.

The Multiplication Assignment ( *= ) operator multiplies a variable by a value and then assigns the result to that variable.

The Division Assignment ( /= ) operator divides a variable by a value and then assigns the result to that variable.

The Modulus Assignment ( %= ) operator finds the remainder when a variable is divided by a value and then assigns the result to that variable.

Assignment operators are essential in Javascript for managing and manipulating data. They provide a concise way to update variable values, making code more readable and efficient.

Bitwise AND

Bitwise xor, bitwise not, right shift.

In Javascript, Bitwise Operators work directly on the binary representations of numbers. These operators are essential when dealing with low-level data manipulation, such as working with bits and bytes.

The Bitwise AND ( & ) operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

The Bitwise OR ( | ) operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1, the corresponding result bit is set to 1.

The Bitwise XOR ( ^ ) operator sets each bit to 1 if only one of the two bits is 1.

The Bitwise NOT ( ~ ) operator inverts the bits of its operand.

The Left Shift ( << ) operator shifts the bits of the first operand to the left by the number of positions specified by the second operand.

The Right Shift ( >> ) operator shifts the bits of the first operand to the right by the number of positions specified by the second operand.

Bitwise operators are powerful tools for manipulating data at the bit level. While they might seem complex at first, understanding their functionality can be invaluable in certain programming scenarios, especially in performance-critical applications.

Concatenation Operator

Concatenation assignment operator, comparing strings, accessing characters, string length.

In Javascript, String Operators are used to manipulate and work with text. Strings are a fundamental data type, and understanding how to operate on them is crucial for creating dynamic and user-friendly applications.

The Concatenation ( + ) operator is used to join two or more strings together.

The Concatenation Assignment ( += ) operator appends a string to an existing string variable.

Strings can be compared using standard comparison operators like == , != , < , and > . When comparing strings, Javascript uses the Unicode value of characters.

You can access individual characters in a string using Bracket Notation .

The length property returns the number of characters in a string.

String operators and properties provide a way to handle text effectively in Javascript. Whether you're building a simple website or a complex web application, mastering string manipulation is essential for a smooth user experience.

Basic Syntax

Simple usage, nested ternary, assigning values.

In Javascript, the Ternary Operator offers a concise way to perform conditional operations. It's a shorthand for the if...else statement and is particularly useful for simple, inline decisions.

The ternary operator has three parts: a condition, a result for true , and a result for false .

Here's a basic example to determine if a number is even or odd.

Ternary operators can be nested for multiple conditions. However, for readability, it's best to use them sparingly in this manner.

It's common to use the ternary operator for quick assignments based on conditions.

The ternary operator provides a compact way to handle conditional logic. While it's a powerful tool, it's essential to use it judiciously to ensure that code remains clear and maintainable.

typeof Operator

Instanceof operator, type conversion, automatic type coercion, checking array type.

In Javascript, Type Operators help determine and manipulate the data type of variables. Understanding these operators is crucial, given Javascript's dynamic typing, where a variable's type can change during runtime.

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

The instanceof operator tests whether an object is an instance of a particular constructor or class.

Javascript provides ways to convert between types explicitly. For instance, you can convert a string to a number using the Number() function.

Javascript often automatically converts types when you perform operations on values of different types. Being aware of this behavior is essential to avoid unexpected results.

To check if a variable is an array, you can use the Array.isArray() method.

Type operators and related methods are foundational in Javascript. They allow developers to handle data types effectively, ensuring that operations and comparisons produce the expected outcomes.

Basic Principle

Using parentheses, multiple operators, common precedence levels, checking precedence.

In Javascript, Operator Precedence determines the order in which operators are evaluated when performing an operation. It's a fundamental concept that ensures calculations are executed correctly and consistently.

Operators with higher precedence are evaluated before operators with lower precedence. For instance, multiplication has higher precedence than addition.

To override the default precedence or to make code clearer, you can use parentheses. Expressions inside parentheses are evaluated first.

When multiple operators with the same precedence appear in an expression, they are evaluated from left to right.

Here's a brief overview of some common operators and their precedence levels:

  • Highest : Parentheses ()
  • High : Exponentiation **
  • Medium : Multiplication * , Division / , and Modulus %
  • Low : Addition + and Subtraction -

If you're ever unsure about operator precedence, it's always a good practice to use parentheses to clarify the order of operations.

Understanding operator precedence is vital for writing accurate and efficient code. It ensures that calculations are executed as intended, preventing potential bugs and unexpected results.

What Are Unary Operators?

Unary Operators are operators that take only one operand. The most common unary operators in Javascript are the + and - used to indicate positive and negative numbers, respectively. Another example is the typeof operator, which returns the type of a variable.

Can I Use Bitwise Operators on Non-integer Values?

Yes, but Javascript will convert non-integer values to integers before applying the Bitwise Operation . This conversion can lead to unexpected results, so it's essential to be cautious.

How Can I Determine Operator Precedence in Complex Expressions?

For complex expressions, it's always a good idea to use parentheses to ensure the desired order of operations. If in doubt, refer to the official Javascript documentation or use parentheses for clarity.

Having delved into the nuances of Javascript operators, it's evident how integral they are to the language. Harnessing their power can significantly elevate your coding prowess and efficiency.

Let’s test your knowledge!

Which of the following operators is used to perform a bitwise AND operation in JavaScript?

Continue learning with these javasript guides.

  • JavaScript Trim In Depth: Functions And Applications
  • Getting To Know JavaScript Slice In Detail
  • How To Effectively Use JavaScript Replace
  • How JavaScript Regex Transforms Web Development: A Close Look
  • A Practical Approach To JavaScript Find Techniques

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
  • Aggregation Pipeline Stages in MongoDB - Set 1
  • Aggregation Pipeline Stages in MongoDB - Set 2
  • PyMongoArrow: Export and Import MongoDB data to Pandas DataFrame and NumPy
  • MongoDB Queries Document
  • How to Enable Authentication on MongoDB ?
  • MongoDB - dropIndexes() Method
  • How to Use Go With MongoDB?
  • MongoDB - sort() Method
  • $substrCP (aggregation) operator in MongoDB
  • MongoDB $arrayElemAt Operator
  • MongoDB $concatArrays Operator
  • MongoDB $isArray Operator
  • MongoDB $strcasecmp Operator
  • MongoDB $toUpper Operator
  • MongoDB $toLower Operator
  • MongoDB $divide Operator
  • MongoDB $ln Operator
  • Indexing in MongoDB
  • MongoDB Tutorial in Java

How to Use $unwind Operator in MongoDB?

MongoDB is a NoSQL database widely used for its powerful aggregation framework which allows for complex data manipulation and analysis . One of the key operators in MongoDB’s aggregation pipeline is $unwind , which is used to deconstruct arrays within documents.

In this article, we will learn about the $unwind operator by understanding their examples in different situations and so on.

What is $unwind Operator?

  • The $unwind operator in MongoDB’s aggregation framework is used to deconstruct an array field from the input documents to output a document for each element of the array.
  • This is particularly useful when we want to perform operations on the individual elements of an array or when we need to level nested arrays within documents.

The syntax for the $unwind operator is as follows:

Explanation: Here the “ arrayField ” is the name of the array field to be deconstructed.

Examples of How to Use $unwind Operator in MongoDB

To understand  How to Use $unwind Operator in MongoDB collection  we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called students which contains various information.

Example 1: Counting the Number of Subjects for Each Student

  • The below example uses the $unwind operator to deconstruct the subjects array and creating a separate document for each subject taken by each student.
  • The $group stage then groups the documents by the student’s name ( $name ) and uses the $sum operator to count the number of subjects for each student.

Example 2: Finding the Most Common Subject Among Students

  • This example also uses $unwind to deconstruct the subjects array.
  • After that, the $group stage groups the documents by subject ( $subjects ) and uses the $sum operator to count the occurrences of each subject.
  • The $sort stage then sorts the subjects based on their count in descending order ( -1 ), and the $limit stage limits the output to the first document, which represents the most common subject

Example 3: Creating a List of Unique Subjects Across All Students

  • This example uses $unwind to deconstruct the subjects array.
  • The $group stage groups all the documents together (using _id: null ) and uses the $addToSet operator to create an array of unique subjects across all students.

Overall, The $unwind operator is a powerful tool in MongoDB’s aggregation framework and it allowing for the efficient deconstruction of arrays within documents. Whether you’re working with single arrays, nested arrays, or performing advanced data analysis tasks, the $unwind operator provides a flexible solution. By mastering the usage of $unwind and combining it with other aggregation stages, you can perform complex data manipulation easily.

Please Login to comment...

Similar reads.

  • What are Tiktok AI Avatars?
  • Poe Introduces A Price-per-message Revenue Model For AI Bot Creators
  • Truecaller For Web Now Available For Android Users In India
  • Google Introduces New AI-powered Vids App
  • 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.

    javascript operator assignment

  2. Operators in the Javascript

    javascript operator assignment

  3. What is operator in javascript with example?

    javascript operator assignment

  4. What is JavaScript Operators?

    javascript operator assignment

  5. JavaScript Assignment Operators

    javascript operator assignment

  6. Javascript Assignment Operators (with Examples)

    javascript operator assignment

VIDEO

  1. Operators in JavaScript

  2. JS Coding Assignment-2

  3. JavaScript Operator #javascript #viral #shortviral2023 #webdevelopment

  4. JavaScript Exercise 3: Operators

  5. Equal To operator in Javascript

  6. Spread Operator in Javascript (...Operator) #javascript #like #share #subscribe #lovecoding

COMMENTS

  1. Assignment (=)

    The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. ... JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.

  2. JavaScript Assignment

    Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

  3. JavaScript Operators

    Javascript operators are used to perform different types of mathematical and logical computations. Examples: The Assignment Operator = assigns values. The Addition Operator + adds values. ... The Addition Assignment Operator (+=) adds a value to a variable. Assignment. let x = 10; x += 5;

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

  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. JavaScript Operators Reference

    JavaScript Operators. Operators are used to assign values, compare values, perform arithmetic operations, and more. There are different types of JavaScript operators: Arithmetic Operators. Assignment Operators. Comparison Operators. Logical Operators. Conditional Operators. Type Operators.

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

  8. Assignment operators

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

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

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

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

  12. Learn JavaScript Operators

    The second group of operators we're going to explore is the assignment operators. Assignment operators are used to assign a specific value to a variable. The basic assignment operator is marked by the equal = symbol, and you've already seen this operator in action before: let x = 5; After the basic assignment operator, there are 5 more ...

  13. Operators

    The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. MDN // Assignment Operators. ... 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.

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

  15. JavaScript Operators

    JavaScript Assignment Operators. The assignment operation evaluates the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables. Name. Description. Syntax. Example. Assignment (=) This operator assigns the right operand value to the left operand.

  16. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. 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 ...

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

  18. A Closer Look At Javascript Operators And Their Significance

    In Javascript, Assignment Operators are used to assign values to variables. They are fundamental tools that help in storing and updating data values efficiently within scripts. Basic Assignment. The Basic Assignment (=) operator assigns a value to a variable. let x = 10; // x now holds the value 10

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

  20. How to Use $unwind Operator in MongoDB?

    A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.