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.

Home » JavaScript Tutorial » JavaScript Logical Assignment Operators

JavaScript Logical Assignment Operators

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

ES2021 introduces three logical assignment operators including:

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

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

The Logical OR assignment operator

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

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

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

See another example:

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

The logical OR assignment operator:

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

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

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

The Logical AND assignment operator

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

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

is equivalent to:

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

The nullish coalescing assignment operator

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

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

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

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

The following table illustrates how the logical assignment operators work:

  • The logical OR assignment ( x ||= y ) operator only assigns y to x if x is falsy.
  • The logical AND assignment ( x &&= y ) operator only assigns y to x if x is truthy.
  • The nullish coalescing assignment ( x ??= y ) operator only assigns y to x if x is nullish.

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Assignment operators – JavaScript

The assignment operators modify the value of a variable.

Addition assignment

The addition assignment operator takes the number on the right, adds it to the value stored inside the variable, and stores the new value inside the variable.

Subtraction assignment

The subtraction assignment operator takes the number on the right, subtracts it from the value stored inside the variable, and stores the new value inside the variable.

Multiplication assignment

The multiplication assignment operator takes the number on the right, multiplies it with the value stored inside the variable, and stores the new value inside the variable.

Division assignment

The division assignment operator takes the number on the right, divides the value stored inside the variable by it, and stores the new value inside the variable.

Remainder assignment

The remainder assignment operator takes the number on the right, divides the value stored inside the variable by it, and stores the remainder inside the variable.

Exponentiation assignment

The exponentiation assignment operator raises the value stored inside the variable to the power of the number on the right, and stores the new value inside the variable.

Try the following statements in the console:

The answers will be 3, 1, 2, 1, 1, and 1 (assuming you do each operation in order).

Expressions and operators on MDN

Object.assign() in JavaScript

In JavaScript, the Object.assign() function copies properties from one or more source objects to a target object. It returns the target object.

Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying . Shallow copying is most commonly used in Redux reducers .

Multiple Sources

You can pass multiple source objects to Object.assign() . If there's multiple sources with the same property, the last one in the parameter list wins out.

More Fundamentals Tutorials

  • Check if a Date is Valid in JavaScript
  • Encode base64 in JavaScript
  • Check if URL Contains a String
  • JavaScript Add Month to Date
  • JavaScript Add Days to Date
  • 3 Patterns to Merge Arrays in JavaScript
  • Convert a BigInt to a Number in JavaScript
  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Output
  • JavaScript Comments

JS Variables & Datatypes

  • Variables and Datatypes in JavaScript
  • Global and Local variables in JavaScript
  • JavaScript Let
  • JavaScript Const
  • JavaScript var

JS Operators

Javascript operators.

  • Operator precedence in JavaScript

JavaScript Arithmetic Operators

Javascript assignment operators, javascript comparison operators, javascript logical operators, javascript bitwise operators.

  • JavaScript Ternary Operator
  • JavaScript Comma Operator

JavaScript Unary Operators

  • JavaScript Relational operators

JavaScript String Operators

  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript (4 Different Ways)
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions

JavaScript operators are symbols used to operate the operands. Operators are used to perform specific mathematical and logical computations on operands.

assignment operator objects javascript

JavaScript Operators: There are various operators supported by JavaScript.

Table of Content

JavaScript Ternary Operators

Javascript comma operators, javascript relational operators, javascript bigint operators.

JavaScript Arithmetic Operators perform arithmetic operations: addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation (**).

The assignment operation evaluates the assigned value. Chaining the assignment operator is possible in order to assign a single value to multiple variables

Comparison operators are mainly used to perform the logical operations that determine the equality or difference between the values.

JavaScript Logical Operators perform logical operations: AND (&&), OR (||), and NOT (!), evaluating expressions and returning boolean values.

The bitwise operator in JavaScript is used to convert the number to a 32-bit binary number and perform the bitwise operation. The number is converted back to the 64-bit number after the result. 

The ternary operator has three operands. It is the simplified operator of if/else.

Comma Operator (,)  mainly evaluates its operands from left to right sequentially and returns the value of the rightmost operand. 

A unary operation is an operation with only one operand.

JavaScript  Relational operators  are used to compare its operands and determine the relationship between them. They return a Boolean value (true or false) based on the comparison result.

JavaScript BigInt operators support arithmetic operations on BigInt data type, including addition, subtraction, multiplication, division, and exponentiation. Most operators that can be used between numbers can be used between  BigInt values as well.

JavaScript String Operators include concatenation (+) and concatenation assignment (+=), used to join strings or combine strings with other data types.

We have a list of JavaScript Operators reference where you can know more about these operators.

Please Login to comment...

Similar reads.

  • javascript-operators
  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Array vs Object Destructuring in JavaScript – What’s the Difference?

Oluwatobi Sofela

The destructuring assignment in JavaScript provides a neat and DRY way to extract values from your arrays and objects.

This article aims to show you exactly how array and object destructuring assignments work in JavaScript.

So, without any further ado, let’s get started with array destructuring.

What Is Array Destructuring?

Array destructuring is a unique technique that allows you to neatly extract an array’s value into new variables.

For instance, without using the array destructuring assignment technique, you would copy an array’s value into a new variable like so:

Try it on StackBlitz

Notice that the snippet above has a lot of repeated code which is not a DRY ( D on’t R epeat Y ourself) way of coding.

Let’s now see how array destructuring makes things neater and DRYer.

You see, like magic, we’ve cleaned up our code by placing the three new variables (that is, firstName , lastName , and website ) into an array object ( [...] ). Then, we assigned them the profile array's values.

In other words, we instructed the computer to extract the profile array’s values into the variables on the left-hand side of the assignment operator .

Therefore, JavaScript will parse the profile array and copy its first value ( "Oluwatobi" ) into the destructuring array’s first variable ( firstName ).

Likewise, the computer will extract the profile array’s second value ( "Sofela" ) into the destructuring array’s second variable ( lastName ).

Lastly, JavaScript will copy the profile array’s third value ( "codesweetly.com" ) into the destructuring array’s third variable ( website ).

Notice that the snippet above destructured the profile array by referencing it. However, you can also do direct destructuring of an array. Let’s see how.

How to Do Direct Array Destructuring

JavaScript lets you destructure an array directly like so:

Suppose you prefer to separate your variable declarations from their assignments. In that case, JavaScript has you covered. Let’s see how.

How to Use Array Destructuring While Separating Variable Declarations from Their Assignments

Whenever you use array destructuring, JavaScript allows you to separate your variable declarations from their assignments.

Here’s an example:

What if you want "Oluwatobi" assigned to the firstName variable—and the rest of the array items to another variable? How you do that? Let’s find out below.

How to Use Array Destructuring to Assign the Rest of an Array Literal to a Variable

JavaScript allows you to use the rest operator within a destructuring array to assign the rest of a regular array to a variable.

Note: Always use the rest operator as the last item of your destructuring array to avoid getting a SyntaxError .

Now, what if you only want to extract "codesweetly.com" ? Let's discuss the technique you can use below.

How to Use Array Destructuring to Extract Values at Any Index

Here’s how you can use array destructuring to extract values at any index position of a regular array:

In the snippet above, we used commas to skip variables at the destructuring array's first and second index positions.

By so doing, we were able to link the website variable to the third index value of the regular array on the right side of the assignment operator (that is, "codesweetly.com" ).

At times, however, the value you wish to extract from an array is undefined . In that case, JavaScript provides a way to set default values in the destructuring array. Let’s learn more about this below.

How Default Values Work in an Array Destructuring Assignment

Setting a default value can be handy when the value you wish to extract from an array does not exist (or is set to undefined ).

Here’s how you can set one inside a destructuring array:

In the snippet above, we set "Tobi" and "CodeSweetly" as the default values of the firstName and website variables.

Therefore, in our attempt to extract the first index value from the right-hand side array, the computer defaulted to "CodeSweetly" —because only a zeroth index value exists in ["Oluwatobi"] .

So, what if you need to swap firstName ’s value with that of website ? Again, you can use array destructuring to get the job done. Let’s see how.

How to Use Array Destructuring to Swap Variables’ Values

You can use the array destructuring assignment to swap the values of two or more different variables.

Here's an example:

In the snippet above, we used direct array destructuring to reassign the firstName and website variables with the values of the array literal on the right-hand side of the assignment operator.

As such, firstName ’s value will change from "Oluwatobi" to "CodeSweetly" . While website ’s content will change from "CodeSweetly" to "Oluwatobi" .

Keep in mind that you can also use array destructuring to extract values from a regular array to a function’s parameters. Let’s talk more about this below.

How to Use Array Destructuring to Extract Values from an Array to a Function’s Parameters

Here’s how you can use array destructuring to extract an array’s value to a function’s parameter:

In the snippet above, we used an array destructuring parameter to extract the profile array’s values into the getUserBio ’s firstName and lastName parameters.

Note: An array destructuring parameter is typically called a destructuring parameter .

Here’s another example:

In the snippet above, we used two array destructuring parameters to extract the profile array’s values into the getUserBio ’s website and userName parameters.

There are times you may need to invoke a function containing a destructuring parameter without passing any argument to it. In that case, you will need to use a technique that prevents the browser from throwing a TypeError .

Let’s learn about the technique below.

How to Invoke a Function Containing Array Destructuring Parameters Without Supplying Any Argument

Consider the function below:

Now, let’s invoke the getUserBio function without passing any argument to its destructuring parameter:

Try it on CodeSandBox

After invoking the getUserBio function above, the browser will throw an error similar to TypeError: undefined is not iterable .

The TypeError message happens because functions containing a destructuring parameter expect you to supply at least one argument.

So, you can avoid such error messages by assigning a default argument to the destructuring parameter.

Notice in the snippet above that we assigned an empty array as the destructuring parameter’s default argument.

So, let’s now invoke the getUserBio function without passing any argument to its destructuring parameter:

The function will output:

Keep in mind that you do not have to use an empty array as the destructuring parameter’s default argument. You can use any other value that is not null or undefined .

So, now that we know how array destructuring works, let's discuss object destructuring so we can see the differences.

What Is Object Destructuring in JavaScript?

Object destructuring is a unique technique that allows you to neatly extract an object’s value into new variables.

For instance, without using the object destructuring assignment technique, we would extract an object’s value into a new variable like so:

Let’s now see how the object destructuring assignment makes things neater and DRY.

You see, like magic, we’ve cleaned up our code by placing the three new variables into a properties object ( {...} ) and assigning them the profile object’s values.

In other words, we instructed the computer to extract the profile object’s values into the variables on the left-hand side of the assignment operator .

Therefore, JavaScript will parse the profile object and copy its first value ( "Oluwatobi" ) into the destructuring object’s first variable ( firstName ).

Likewise, the computer will extract the profile object’s second value ( "Sofela" ) into the destructuring object’s second variable ( lastName ).

Lastly, JavaScript will copy the profile object’s third value ( "codesweetly.com" ) into the destructuring object’s third variable ( website ).

Keep in mind that in { firstName: firstName, lastName: lastName, website: website } , the keys are references to the profile object’s properties – while the keys’ values represent the new variables.

Anatomy of a JavaScript object destructuring assignment

Alternatively, you can use shorthand syntax to make your code easier to read.

In the snippet above, we shortened { firstName: firstName, age: age, gender: gender } to { firstName, age, gender } . You can learn more about the shorthand technique here .

Observe that the snippets above illustrated how to assign an object’s value to a variable when both the object’s property and the variable have the same name.

However, you can also assign a property’s value to a variable of a different name. Let’s see how.

How to Use Object Destructuring When the Property’s Name Differs from That of the Variable

JavaScript permits you to use object destructuring to extract a property’s value into a variable even if both the property and the variable’s names are different.

In the snippet above, the computer successfully extracted the profile object’s values into the variables named forename , surname , and onlineSite —even though the properties and variables are of different names.

Note: const { firstName: forename } = profile is equivalent to const forename = profile.firstName .

In the snippet above, the computer successfully extracted the profile object’s value into the surname variable—even though the property and variable are of different names.

Note: const { lastName: { familyName: surname } } = profile is equivalent to const surname = profile.lastName.familyName .

Notice that so far, we’ve destructured the profile object by referencing it. However, you can also do direct destructuring of an object. Let’s see how.

How to Do Direct Object Destructuring

JavaScript permits direct destructuring of a properties object like so:

Suppose you prefer to separate your variable declarations from their assignments. In that case, JavaScript has you covered. Let see how.

How to Use Object Destructuring While Separating Variable Declarations from Their Assignments

Whenever you use object destructuring, JavaScript allows you to separate your variable declarations from their assignments.

  • Make sure that you encase the object destructuring assignment in parentheses. By so doing, the computer will know that the object destructuring is an object literal, not a block.
  • Place a semicolon ( ; ) after the parentheses of an object destructuring assignment. By doing so, you will prevent the computer from interpreting the parentheses as an invocator of a function that may be on the previous line.

What if you want "Oluwatobi" assigned to the firstName variable—and the rest of the object’s values to another variable? How can you do this? Let’s find out below.

How to Use Object Destructuring to Assign the Rest of an Object to a Variable

JavaScript allows you to use the rest operator within a destructuring object to assign the rest of an object literal to a variable.

Note: Always use the rest operator as the last item of your destructuring object to avoid getting a SyntaxError .

At times, the value you wish to extract from a properties object is undefined . In that case, JavaScript provides a way to set default values in the destructuring object. Let’s learn more about this below.

How Default Values Work in an Object Destructuring Assignment

Setting a default value can be handy when the value you wish to extract from an object does not exist (or is set to undefined ).

Here’s how you can set one inside a destructuring properties object:

Therefore, in our attempt to extract the second property’s value from the right-hand side object, the computer defaulted to "CodeSweetly" —because only a single property exists in {firstName: "Oluwatobi"} .

So, what if you need to swap firstName ’s value with that of website ? Again, you can use object destructuring to get the job done. Let’s see how below.

How to Use Object Destructuring to Swap Values

You can use the object destructuring assignment to swap the values of two or more different variables.

The snippet above used direct object destructuring to reassign the firstName and website variables with the values of the object literal on the right-hand side of the assignment operator.

Keep in mind that you can also use object destructuring to extract values from properties to a function’s parameters. Let’s talk more about this below.

How to Use Object Destructuring to Extract Values from Properties to a Function’s Parameters

Here’s how you can use object destructuring to copy a property’s value to a function’s parameter:

In the snippet above, we used an object destructuring parameter to copy the profile object’s values into getUserBio ’s firstName and lastName parameters.

Note: An object destructuring parameter is typically called a destructuring parameter .

In the snippet above, we used two destructuring parameters to copy the profile object’s values into getUserBio ’s website and userName parameters.

Note: If you are unclear about the destructuring parameter above, you may grasp it better by reviewing this section .

How to Invoke a Function Containing Destructured Parameters Without Supplying Any Argument

After invoking the getUserBio function above, the browser will throw an error similar to TypeError: (destructured parameter) is undefined .

Notice that in the snippet above, we assigned an empty object as the destructuring parameter’s default argument.

Keep in mind that you do not have to use an empty object as the destructuring parameter’s default argument. You can use any other value that is not null or undefined .

Wrapping It Up

Array and object destructuring work similarly. The main difference between the two destructuring assignments is this:

  • Array destructuring extracts values from an array. But object destructuring extracts values from a JavaScript object.

This article discussed how array and object destructuring works in JavaScript. We also looked at the main difference between the two destructuring assignments.

Thanks for reading!

And here's a useful ReactJS resource:

I wrote a book about React!

  • It's beginner’s friendly ✔
  • It has live code snippets ✔
  • It contains scalable projects ✔
  • It has plenty of easy-to-grasp examples ✔

The React Explained Clearly book is all you need to understand ReactJS.

Click Here to Get Your Copy

React Explained Clearly Book Now Available at Amazon

O-sweet-programming, my interest is to make you sweeter for all.

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

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • Double Savings Offer on Courses
  • Share Your Experience
  • JavaScript Tutorial

JavaScript Basics

  • Introduction to JavaScript
  • JavaScript Versions
  • How to Add JavaScript in HTML Document?
  • JavaScript Statements
  • JavaScript Syntax
  • JavaScript Output
  • JavaScript Comments

JS Variables & Datatypes

  • Variables and Datatypes in JavaScript
  • Global and Local variables in JavaScript
  • JavaScript Let
  • JavaScript Const
  • JavaScript var

JS Operators

Javascript operators.

  • Operator precedence in JavaScript
  • JavaScript Arithmetic Operators
  • JavaScript Assignment Operators
  • JavaScript Comparison Operators
  • JavaScript Logical Operators
  • JavaScript Bitwise Operators
  • JavaScript Ternary Operator
  • JavaScript Comma Operator
  • JavaScript Unary Operators
  • JavaScript Relational operators
  • JavaScript String Operators
  • JavaScript Loops
  • 7 Loops of JavaScript
  • JavaScript For Loop
  • JavaScript While Loop
  • JavaScript for-in Loop
  • JavaScript for...of Loop
  • JavaScript do...while Loop

JS Perfomance & Debugging

  • JavaScript | Performance
  • Debugging in JavaScript
  • JavaScript Errors Throw and Try to Catch
  • Objects in Javascript
  • Introduction to Object Oriented Programming in JavaScript
  • JavaScript Objects
  • Creating objects in JavaScript (4 Different Ways)
  • JavaScript JSON Objects
  • JavaScript Object Reference

JS Function

  • Functions in JavaScript
  • How to write a function in JavaScript ?
  • JavaScript Function Call
  • Different ways of writing functions in JavaScript
  • Difference between Methods and Functions in JavaScript
  • Explain the Different Function States in JavaScript
  • JavaScript Function Complete Reference
  • JavaScript Arrays
  • JavaScript Array Methods
  • Best-Known JavaScript Array Methods
  • What are the Important Array Methods of JavaScript ?
  • JavaScript Array Reference
  • JavaScript Strings
  • JavaScript String Methods
  • JavaScript String Reference
  • JavaScript Numbers
  • How numbers are stored in JavaScript ?
  • How to create a Number object using JavaScript ?
  • JavaScript Number Reference
  • JavaScript Math Object
  • What is the use of Math object in JavaScript ?
  • JavaScript Math Reference
  • JavaScript Map
  • What is JavaScript Map and how to use it ?
  • JavaScript Map Reference
  • Sets in JavaScript
  • How are elements ordered in a Set in JavaScript ?
  • How to iterate over Set elements in JavaScript ?
  • How to sort a set in JavaScript ?
  • JavaScript Set Reference
  • JavaScript Date
  • JavaScript Promise
  • JavaScript BigInt
  • JavaScript Boolean
  • JavaScript Proxy/Handler
  • JavaScript WeakMap
  • JavaScript WeakSet
  • JavaScript Function Generator
  • JavaScript JSON
  • Arrow functions in JavaScript
  • JavaScript this Keyword
  • Strict mode in JavaScript
  • Introduction to ES6
  • JavaScript Hoisting
  • Async and Await in JavaScript

JavaScript Exercises

  • JavaScript Exercises, Practice Questions and Solutions
  • Full Stack Development Course

An operator is capable of manipulating a certain value or operand. Operators are used to performing specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. In JavaScript, operators are used to comparing values, perform arithmetic operations, etc. There are various operators supported by JavaScript:  

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators
  • Ternary Operators
  • typeof Operator

Arithmetic Operators:  There are various Arithmetic Operators – 

+ (Addition):  ‘+’ operator performs addition on two operands. 

Example: 

Note: ‘+’ operator can also be used to concatenate (add) strings. 

– (Subtraction):  ‘-‘ operator performs subtraction on two operands. 

Example : 

* (Multiplication):  ‘*’ operator performs multiplication on two operands. 

/ (Division):  ‘/’ operator performs division on two operands (divide the numerator by the denominator). 

% (Modulus):  ‘%’ operator gives a remainder of an integer division. 

+ + (Increment):  ‘+ +’ operator increases an integer value by one. 

– – (Decrement):  ‘- -‘ operator decreases an integer value by one. 

Assignment Operators:  There are various Assignment Operators in JavaScript – 

= (Assignment Operator):  Assigns right operand value to left operand. 

+= (Add and Assignment Operator):  Sums up left and right operand values and then assigns the result to the left operand. 

– = (Subtract and Assignment Operator):  It subtracts the right side value from the left side value and then assigns the result to the left operand. 

similarly there are *= (Multiply and Assignment) , /= (Divide and Assignment) , %= (Modules and Assignment)  

Comparison Operators:  There are various Comparison Operators in JavaScript – 

= =:  Compares the equality of two operands. If equal then the condition is true otherwise false. 

Note: Type not considered in ‘= =’ operator.    = = =:  This operator compares the equality of two operands with type. If equal(type and value both) then the condition is true otherwise false. 

!= (Not Equal):  Compares inequality of two operands. True if operands are not equal. 

> (Greater than):  This operator checks whether the left side value is greater than the right side value. If yes then it returns true otherwise it returns false. 

< (Less than):  This operator checks whether the left side value is less than the right side value. If yes then it returns true otherwise it returns false. 

> = (Greater than or Equal to):  This operator checks whether the left side operand is greater than or equal to the right side operand. If yes then it returns true otherwise it returns false. 

<= (Less than or Equal to):  This operator checks whether the left side operand value is less than or equal to the right side operand value. If yes then it returns true otherwise it returns false. 

Logical Operators:  There are various Logical Operators in JavaScript – 

&& (Logical AND):  It checks whether two operands are non-zero (0, false, undefined, null, or “” are considered as zero), if yes then return the last operand when evaluating from left to right. 

|| (Logical OR):  It checks whether two operands are non-zero (0, false, undefined, null, or “” is considered as zero), if yes then return the first operand when evaluating from left to right. 

! (Logical NOT):  It reverses the boolean result of the operand (or condition). 

Ternary Operator: 

: ? Operator:  It is like the short form of the if-else condition. 

Syntax: 

where A and B are values and if the condition is true then Y = A otherwise Y = B. 

typeof Operator: It returns the type of a variable. 

Syntax:   

Example:  

Output:  

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples .

Please Login to comment...

Similar reads.

  • javascript-operators
  • Web Technologies

three90RightbarBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Expressions and operators

« 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: JavaScript Copy Code 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.

Operator precedence

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-hand-side expressions

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:

© 2016 Mozilla Contributors Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-us/docs/web/javascript/guide/expressions_and_operators

  • Skip to main content
  • Select language
  • Skip to search
  • বাংলা (বাংলাদেশ)
  • Bahasa Indonesia
  • Português (do Brasil)
  • Add a translation
  • Print this page
  • Expressions and operators

Non-standard features

This chapter documents all the JavaScript language operators, expressions and keywords.

Expressions and operators by category

For an alphabetical listing see the sidebar on the left.

Primary expressions

Basic keywords and general expressions in JavaScript.

Left-hand-side expressions

Left values are the destination of an assignment.

Increment and decrement

Postfix/prefix increment and postfix/prefix decrement operators.

Unary operators

A unary operation is operation with only one operand.

  • Arithmetic operators

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

Relational operators

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

Equality operators

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

Bitwise shift operators

Operations to shift all bits of the operand.

Binary bitwise operators

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

Binary logical operators

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

Conditional (ternary) operator

The conditional operator returns one of two values based on the logical value of the condition.

  • Assignment operators

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

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

  • Comma operator

Specifications

  • Operator precedence

Document Tags and Contributors

  • 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
  • JavaScript basics
  • JavaScript technologies overview
  • Introduction to Object Oriented JavaScript
  • 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:
  • Standard built-in objects
  • ArrayBuffer
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.float32x4
  • SIMD.float64x2
  • SIMD.int16x8
  • SIMD.int32x4
  • SIMD.int8x16
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Property accessors
  • Spread operator
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Statements and declarations
  • Legacy generator function
  • for each...in
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template strings
  • Deprecated features
  • New in JavaScript
  • ECMAScript 5 support in Mozilla
  • ECMAScript 6 support in Mozilla
  • ECMAScript 7 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

Best Programming Guides with Examples

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Email Address

JavaScript Assignment Operators Example

JavaScript Assignment Operators Example

Assignment operator in javascript with example; In this tutorial, you will learn about JavaScript assignment operators with the help of examples. And as well as learn how to assign a value of the right operand to its left operand in js using these assignment operators.

List of JS Assignment Operators

If you want to assign a value of the right(first) operand to its left(second) operand, you can use equal operator in js.

See the example of assignment operator is equal (=):

In this example, Assigned the number 15 to the variable x.

See another example for better understanding:

It’s equivalent to the above example:

JS assignment operator has several shortcuts for performing all the arithmetic operations , which let you assign to the right operand the left operand.

Here, you can see that examples of the following assignment operators:

  • += : addition assignment
  • -= : subtraction assignment
  • *= : multiplication assignment
  • /= : division assignment
  • %= : remainder assignment
  • **= : exponentiation assignment

See the following example:

In this tutorial, you have learned how to use JavaScript assignment operators.

Recommended JavaScript Tutorial

assignment operator objects javascript

Author Admin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

View all posts by Admin

Leave a Reply Cancel reply

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

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

  • Skip to main content
  • Select language
  • Skip to search
  • Arguments object

Using the Spread Syntax with Arguments

Rest, default, and destructured parameters.

The arguments object is an Array -like object corresponding to the arguments passed to a function.

Description

The arguments object is a local variable available within all functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to them as follows:

The arguments can also be set:

The arguments object is not an Array . It is similar to an Array , but does not have any Array properties except length . For example, it does not have the pop method. However it can be converted to a real Array :

Using slice on arguments prevents optimizations in some JavaScript engines (V8 for example - more information ). If you care for them, try constructing a new array by iterating through the arguments object instead. An alternative would be to use the despised Array constructor as a function:

You can use the arguments object if you call a function with more arguments than it is formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments. Use arguments.length to determine the number of arguments passed to the function, and then process each argument by using the arguments object. To determine the number of parameters in the function signature , use the Function.length property.

Using typeof with Arguments

The typeof arguments returns 'object'. 

The typeof individual arguments can be determined with the use of indexing.

You can also use the Array.from() method or the spread operator to convert arguments to a real Array:

Defining a function that concatenates several strings

This example defines a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.

Defining a function that creates HTML lists

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is " u " if the list is to be unordered (bulleted), or " o " if the list is to be ordered (numbered). The function is defined as follows:

You can pass any number of arguments to this function, and it adds each argument as an item to a list of the type indicated. For example:

The arguments object can be used in conjunction with rest , default , and  destructured  parameters.

While the presence of  rest ,  default , or  destructured  parameters does not alter the behavior of the arguments  object in strict mode code , there is a subtle difference for non-strict code.

When a non-strict function does not contain  rest ,  default , or  destructured  parameters, then the values in the  arguments  object do track the values of the arguments (and vice versa). See the code below:

When a non-strict function does  contain  rest ,  default , or  destructured  parameters, then the values in the  arguments  object  do not  track the values of the arguments (and vice versa). Instead, they reflect the arguments provided at the time of invocation:

Specifications

Browser compatibility, document tags and contributors.

  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Arithmetic operators
  • Array comprehensions
  • Assignment operators
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • 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

JS Tutorial

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

An array is a special variable, which can hold more than one value:

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const .

Spaces and line breaks are not important. A declaration can span multiple lines:

You can also create an array, and then provide the elements:

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

The two examples above do exactly the same.

There is no need to use new Array() .

For simplicity, readability and execution speed, use the array literal method.

Advertisement

Accessing Array Elements

You access an array element by referring to the index number :

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars :

Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Objects use names to access its "members". In this example, person.firstName returns John:

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array elements).

The length property is always one more than the highest array index.

Accessing the First Array Element

Accessing the last array element, looping array elements.

One way to loop through an array, is using a for loop:

You can also use the Array.forEach() function:

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

New element can also be added to an array using the length property:

Adding elements with high indexes can create undefined "holes" in an array:

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes .  

WARNING !! If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results .

 Example:

The difference between arrays and objects.

In JavaScript, arrays use numbered indexes .  

In JavaScript, objects use named indexes .

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text) .
  • You should use arrays when you want the element names to be numbers .

JavaScript new Array()

JavaScript has a built-in array constructor new Array() .

But you can safely use [] instead.

These two different statements both create a new empty array named points:

These two different statements both create a new array containing 6 numbers:

The new keyword can produce some unexpected results:

A Common Error

is not the same as:

How to Recognize an Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns " object ":

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray() :

Solution 2:

The instanceof operator returns true if an object is created by a given constructor:

Complete Array Reference

For a complete Array reference, go to our:

Complete JavaScript Array Reference .

The reference contains descriptions and examples of all Array properties and methods.

Test Yourself With Exercises

Get the value " Volvo " from the cars array.

Start the Exercise

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.

Firefox is no longer supported on Windows 8.1 and below.

Please download Firefox ESR (Extended Support Release) to use Firefox.

Download Firefox ESR 64-bit

Download Firefox ESR 32-bit

Firefox is no longer supported on macOS 10.14 and below.

Mozilla Foundation Security Advisory 2024-18

Security vulnerabilities fixed in firefox 125.

  • Firefox 125

# CVE-2024-3852: GetBoundName in the JIT returned the wrong object

Description.

GetBoundName could return the wrong version of an object when JIT optimizations were applied.

  • Bug 1883542

# CVE-2024-3853: Use-after-free if garbage collection runs during realm initialization

A use-after-free could result if a JavaScript realm was in the process of being initialized when a garbage collection started.

  • Bug 1884427

# CVE-2024-3854: Out-of-bounds-read after mis-optimized switch statement

In some code patterns the JIT incorrectly optimized switch statements and generated code with out-of-bounds-reads.

  • Bug 1884552

# CVE-2024-3855: Incorrect JIT optimization of MSubstr leads to out-of-bounds reads

In certain cases the JIT incorrectly optimized MSubstr operations, which led to out-of-bounds reads.

  • Bug 1885828

# CVE-2024-3856: Use-after-free in WASM garbage collection

A use-after-free could occur during WASM execution if garbage collection ran during the creation of an array.

  • Bug 1885829

# CVE-2024-3857: Incorrect JITting of arguments led to use-after-free during garbage collection

The JIT created incorrect code for arguments in certain cases. This led to potential use-after-free crashes during garbage collection.

  • Bug 1886683

# CVE-2024-3858: Corrupt pointer dereference in js::CheckTracedThing<js::Shape>

It was possible to mutate a JavaScript object so that the JIT could crash while tracing it.

  • Bug 1888892

# CVE-2024-3859: Integer-overflow led to out-of-bounds-read in the OpenType sanitizer

On 32-bit versions there were integer-overflows that led to an out-of-bounds-read that potentially could be triggered by a malformed OpenType font.

  • Bug 1874489

# CVE-2024-3860: Crash when tracing empty shape lists

An out-of-memory condition during object initialization could result in an empty shape list. If the JIT subsequently traced the object it would crash.

  • Bug 1881417

# CVE-2024-3861: Potential use-after-free due to AlignedBuffer self-move

If an AlignedBuffer were assigned to itself, the subsequent self-move could result in an incorrect reference count and later use-after-free.

  • Bug 1883158

# CVE-2024-3862: Potential use of uninitialized memory in MarkStack assignment operator on self-assignment

The MarkStack assignment operator, part of the JavaScript engine, could access uninitialized memory if it were used in a self-assignment.

  • Bug 1884457

# CVE-2024-3863: Download Protections were bypassed by .xrm-ms files on Windows

The executable file warning was not presented when downloading .xrm-ms files. Note: This issue only affected Windows operating systems. Other operating systems are unaffected.

  • Bug 1885855

# CVE-2024-3302: Denial of Service using HTTP/2 CONTINUATION frames

There was no limit to the number of HTTP/2 CONTINUATION frames that would be processed. A server could abuse this to create an Out of Memory condition in the browser.

  • Bug 1881183
  • VU#421644 - HTTP/2 CONTINUATION frames can be utilized for DoS attacks

# CVE-2024-3864: Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

Memory safety bug present in Firefox 124, Firefox ESR 115.9, and Thunderbird 115.9. This bug showed evidence of memory corruption and we presume that with enough effort this could have been exploited to run arbitrary code.

  • Memory safety bug fixed in Firefox 125, Firefox ESR 115.10, and Thunderbird 115.10

# CVE-2024-3865: Memory safety bugs fixed in Firefox 125

Memory safety bugs present in Firefox 124. Some of these bugs showed evidence of memory corruption and we presume that with enough effort some of these could have been exploited to run arbitrary code.

  • Memory safety bugs fixed in Firefox 125

IMAGES

  1. JavaScript Assignment Operators

    assignment operator objects javascript

  2. Javascript Assignment Operators (with Examples)

    assignment operator objects javascript

  3. JavaScript Operators.

    assignment operator objects javascript

  4. What is JavaScript Operators?

    assignment operator objects javascript

  5. Assignment operators in javascript || Javascript assignment operators

    assignment operator objects javascript

  6. JavaScript Assignment Operators

    assignment operator objects javascript

VIDEO

  1. Operators in JavaScript

  2. Assignment Operator & Comparison Operator in Javascript

  3. #20. Assignment Operators in Java

  4. 9

  5. Session 1

  6. Assignment operators

COMMENTS

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

  2. javascript

    The = operator is an assignment operator. You are assigning an object to a value. The == operator is a conditional equality operation. You are confirming whether two things have equal values. There is also a === operator. This compares not only value, but also type. Assignment Operators. Comparison Operators

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

  4. The Comprehensive Guide to Operators, Expressions, and Statements in

    As we can see from the list above, JavaScript has lots of operators. Assignment operators. Assignment operators are used to give a variable a value. It reads from right to left. For example, let a = 1 sets the value of variable a to 1. We can also have more than one assignment operator in one line by writing: let a = b = c = 1.

  5. JavaScript Logical Assignment Operators

    The Logical AND assignment operator. The logical AND assignment operator only assigns y to x if x is truthy: x &&= y; The logical AND assignment operator also short-circuits. It means that. x &&= y; is equivalent to: x && (x = y); The following example uses the logical AND assignment operator to change the last name of a person object if the ...

  6. Expressions and operators

    The delete operator deletes a property from an object. void The void operator discards an expression's return value. typeof The typeof operator determines the type of a given object. + The unary plus operator converts its operand to Number type.-The unary negation operator converts its operand to Number type and then negates it. ~ Bitwise NOT ...

  7. Assignment operators

    The assignment operators modify the value of a variable. Addition assignment. The addition assignment operator takes the number on the right, adds it to the value stored inside the variable, and stores the new value inside the variable. let x = 1; x += 2; // 3 Subtraction assignment

  8. Object.assign() in JavaScript

    Object.assign() is commonly used to shallow copy objects, although the spread operator is generally faster than Object.assign() for shallow copying. Shallow copying is most commonly used in Redux reducers .

  9. Addition assignment (+=)

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

  10. 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 ... It returns the operand type, The possible types that exist in javascript are undefined, Object, boolean, number, string, symbol, and function. typeof ...

  11. Array vs Object Destructuring in JavaScript

    Get started. The destructuring assignment in JavaScript provides a neat and DRY way to extract values from your arrays and objects. This article aims to show you exactly how array and object destructuring assignments work in JavaScript. So, without any further ado, let's get started with array destructuring.

  12. JavaScript Operators

    Logical Operators: There are various Logical Operators in JavaScript -. && (Logical AND): It checks whether two operands are non-zero (0, false, undefined, null, or "" are considered as zero), if yes then return the last operand when evaluating from left to right. Example : Y = 5 and X = 6. Y && X is 6.

  13. javascript Expressions and operators

    The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand. ... 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 delete operator deletes an object, an object's property, or an element at a ...

  14. Javascript AND operator within assignment

    Basically, the Logical AND operator (&&), will return the value of the second operand if the first is truthy, and it will return the value of the first operand if it is by itself falsy, for example:true && "foo"; // "foo" NaN && "anything"; // NaN 0 && "anything"; // 0 Note that falsy values are those that coerce to false when used in boolean context, they are null, undefined, 0, NaN, an empty ...

  15. Understanding Destructuring, Rest Parameters, and Spread Syntax in

    The default assignment for object destructuring creates new variables with the same name as the object property. If you do not want the new variable to have the same name as the property name, you also have the option of renaming the new variable by using a colon (:) to decide a new name, as seen with noteId in the following:// Assign a custom name to a destructured value const {id: noteId ...

  16. Expressions and operators

    Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals. Comma operator The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.

  17. JavaScript Assignment Operators Example

    x += 45; JS assignment operator has several shortcuts for performing all the arithmetic operations, which let you assign to the right operand the left operand. Here, you can see that examples of the following assignment operators: +=: addition assignment. -=: subtraction assignment. *=: multiplication assignment. /=: division assignment.

  18. Arguments object

    The arguments object is a local variable available within all functions. You can refer to a function's arguments within the function by using the arguments object. This object contains an entry for each argument passed to the function, the first entry's index starting at 0. For example, if a function is passed three arguments, you can refer to ...

  19. Using promises

    With promises, we accomplish this by creating a promise chain. The API design of promises makes this great, because callbacks are attached to the returned promise object, instead of being passed into a function. Here's the magic: the then() function returns a new promise, different from the original: js.

  20. JavaScript Arrays

    Creating an Array. Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [ item1, item2, ... ]; It is a common practice to declare arrays with the const keyword. Learn more about const with arrays in the chapter: JS Array Const.

  21. Object.assign()

    Which Object.assign() static method copies all enumerable own properties from on or more root objects to a target object. It profits the modified target request. ... JavaScript. Learn in run scripts in the browser. Accessibility. Learn to induce the web accessibility till total. Plus Advantage. Overview. A customized MDN experience.

  22. Security Vulnerabilities fixed in Firefox 125

    It was possible to mutate a JavaScript object so that the JIT could crash while tracing it. ... Potential use of uninitialized memory in MarkStack assignment operator on self-assignment Reporter Ronald Crane Impact moderate Description. The MarkStack assignment operator, part of the JavaScript engine, could access uninitialized memory if it ...