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

JavaScript Assignment Operators

A ssignment operators.

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

Assignment Operators List

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

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

a&&=b

x && (x = y)

||=

x || (x = y)

??=

x ?? (x = y)

Below we have described each operator with an example code:

Addition assignment operator(+=).

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

Subtraction Assignment Operator(-=)

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

Multiplication Assignment Operator(*=)

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

Division Assignment Operator(/=)

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

Remainder Assignment Operator(%=)

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

Exponentiation Assignment Operator

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

Left Shift Assignment Operator(<<=)

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

Right Shift Assignment O perator(>>=)

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

Bitwise AND Assignment Operator(&=)

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

Btwise OR Assignment Operator(|=)

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

Bitwise XOR Assignment Operator(^=)

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

Logical AND Assignment Operator(&&=)

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

Logical OR Assignment Operator( ||= )

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

Nullish coalescing Assignment Operator(??=)

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

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

  • Google Chrome
  • Microsoft Edge

JavaScript Assignment Operators – FAQs

What are assignment operators in javascript.

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

What is the basic assignment operator?

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

What are compound assignment operators?

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

What does the += operator do?

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

How does the *= operator work?

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

Can you use assignment operators with strings?

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

What is the difference between = and ==?

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

What does the **= operator do?

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

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators
  • Discord Emojis List 2024: Copy and Paste
  • Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
  • PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
  • Best Mobile Game Controllers in 2024: Top Picks for iPhone and Android
  • System Design Netflix | A Complete Architecture

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

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

Introduction to JavaScript assignment operators

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

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

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

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

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

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

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

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

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

Chaining JavaScript assignment operators

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

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

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.

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

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

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

Assignment Expressions

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

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

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

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

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

Assignment with Operation

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

is equivalent to this one:

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

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

Table 4-3. Assignment operators

Example

In most cases, the expression:

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

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

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

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

Don’t leave empty-handed

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

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

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

assignment expression javascript

  • Skip to main content
  • Select language
  • Skip to search
  • Add a translation
  • Print this page
  • Assignment operators

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

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

Name Shorthand operator Meaning

Simple assignment operator which assigns a value to a variable. 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.

Left shift assignment

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

Right shift assignment

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

Unsigned right shift assignment

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

Bitwise AND assignment

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

Bitwise XOR assignment

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

Bitwise OR assignment

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

Left operand with another assignment operator

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

Specifications

Specification Status Comment
ECMAScript 1st Edition. Standard Initial definition.
Standard  
Release Candidate  

Browser compatibility

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

Document Tags and Contributors

  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Expressions and operators
  • Numbers and dates
  • Text formatting
  • 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
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Bitwise operators
  • Comma operator
  • Comparison operators
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Grouping operator
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Operator precedence
  • Property accessors
  • Spread 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
  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

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

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

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

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

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

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

For example, 3+4 or x*y .

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

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x .

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

Compound assignment operators
Name Shorthand operator Meaning

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:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

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:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to convert the operand to a number, if it is not already. returns .
returns
( ) Calculates the to the  power, that is, returns .
returns .

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 operators
Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same.
[Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

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

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

Bitwise operator examples
Expression Result Binary Description

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.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

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.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand can be converted to ; otherwise, returns .

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

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

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

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

Short-circuit evaluation

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

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

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

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

For example,

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

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

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

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

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

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

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

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

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

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

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

Deleting array elements

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

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

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

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

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

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

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

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

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

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

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

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

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

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

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

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

Relational operators

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

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

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

The following examples show some uses of the in operator.

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

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

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

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

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

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

Operator precedence
Operator type Individual operators
member
call / create instance
negation/increment
multiply/divide
addition/subtraction
bitwise shift
relational
equality
bitwise-and
bitwise-xor
bitwise-or
logical-and
logical-or
conditional
assignment
comma

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

  • Expressions

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

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

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

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

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

Primary expressions

Basic keywords and general expressions in JavaScript.

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

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

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

  • Grouping operator

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

Comprehensions

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

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

Left values are the destination of an assignment.

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

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

Spread operator

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

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

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

Popular Tutorials

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

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

JavaScript Operators

  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

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

JS Functions

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

Exceptions and Modules

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

JavaScript Asynchronous

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

Miscellaneous

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

JavaScript Tutorials

JavaScript Comparison and Logical Operators

JavaScript Ternary Operator

JavaScript Booleans

JavaScript Bitwise Operators

  • JavaScript Object.is()
  • JavaScript typeof Operator

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

Here, we used the + operator to add the operands 2 and 3 .

JavaScript Operator Types

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

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

1. JavaScript Arithmetic Operators

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

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

Commonly Used Arithmetic Operators

Operator Name Example
Addition
Subtraction
Multiplication
Division
Remainder
Increment (increments by ) or
Decrement (decrements by ) or
Exponentiation (Power)

Example 1: Arithmetic Operators in JavaScript

Note: The increment operator ++ adds 1 to the operand. And, the decrement operator -- decreases the value of the operand by 1 .

To learn more, visit Increment ++ and Decrement -- Operators .

2. JavaScript Assignment Operators

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

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

Commonly Used Assignment Operators

Operator Name Example
Assignment Operator
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Remainder Assignment
Exponentiation Assignment

Example 2: Assignment Operators in JavaScript

3. javascript comparison operators.

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

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

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

Note: In the above example, a > b is called a boolean expression since evaluating it results in a boolean value.

Commonly Used Comparison Operators

Operator Meaning Example
Equal to gives us
Not equal to gives us
Greater than gives us
Less than gives us
Greater than or equal to gives us
Less than or equal to gives us
Strictly equal to gives us
Strictly not equal to gives us

Example 3: Comparison Operators in JavaScript

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

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

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

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

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

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

4. JavaScript Logical Operators

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

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

Commonly Used Logical Operators

Operator Syntax Description
(Logical AND) only if both and are
(Logical OR) if either or is
(Logical NOT) if is and vice versa

Example 4: Logical Operators in JavaScript

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

More on JavaScript Operators

We use bitwise operators to perform binary operations on integers.

Operator Description Example
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
<< Left shift
>> Sign-propagating right shift
>>> Zero-fill right shift

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

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

Here, we used the + operator to concatenate str1 and str2 .

JavaScript has many more operators besides the ones we listed above. You will learn about them in detail in later tutorials.

Operator Description Example
: Evaluates multiple operands and returns the value of the last operand.
: Returns value based on the condition.
Returns the data type of the variable.
Returns t if the specified object is a valid object of the specified class.
Discards any expression's return value.

Table of Contents

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

Before we wrap up, let’s put your knowledge of JavaScript Operators to the test! Can you solve the following challenge?

Write a function to perform basic arithmetic operations.

  • The operations are: + for Addition, - for Subtraction, * for Multiplication and / for Division.
  • Given num1 , num2 , and op specifying the operation to perform, return the result.
  • For example, if num1 = 5 , op = "+" and num2 = 3 , the expected output is 8 .

Video: JavaScript Operators

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

JavaScript Tutorial

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

Javascript operators are used to perform different types of mathematical and logical computations.

The Assignment Operator = assigns values

The Addition Operator + adds values

The Multiplication Operator * multiplies values

The Comparison Operator > compares values

JavaScript Assignment

The Assignment Operator ( = ) assigns a value to a variable:

Assignment Examples

Javascript addition.

The Addition Operator ( + ) adds numbers:

JavaScript Multiplication

The Multiplication Operator ( * ) multiplies numbers:

Multiplying

Types of javascript operators.

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

Arithmetic Operators Example

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation ( )
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Arithmetic operators are fully described in the JS Arithmetic chapter.

Advertisement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator ( += ) adds a value to a variable.

Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Assignment operators are fully described in the JS Assignment chapter.

JavaScript Comparison Operators

Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Comparison operators are fully described in the JS Comparisons chapter.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

Note that strings are compared alphabetically:

JavaScript String Addition

The + can also be used to add (concatenate) strings:

The += assignment operator can also be used to add (concatenate) strings:

The result of text1 will be:

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum, but adding a number and a string will return a string:

The result of x , y , and z will be:

If you add a number and a string, the result will be a string!

JavaScript Logical Operators

Operator Description
&& logical and
|| logical or
! logical not

Logical operators are fully described in the JS Comparisons chapter.

JavaScript Type Operators

Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

Type operators are fully described in the JS Type Conversion chapter.

JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.

Operator Description Example Same as Result Decimal
& AND 5 & 1 0101 & 0001 0001  1
| OR 5 | 1 0101 | 0001 0101  5
~ NOT ~ 5  ~0101 1010  10
^ XOR 5 ^ 1 0101 ^ 0001 0100  4
<< left shift 5 << 1 0101 << 1 1010  10
>> right shift 5 >> 1 0101 >> 1 0010   2
>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010   2

The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers. Because of this, in JavaScript, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

Test Yourself With Exercises

Multiply 10 with 5 , and alert the result.

Start the Exercise

Test Yourself with Exercises!

Exercise 1 »   Exercise 2 »   Exercise 3 »   Exercise 4 »   Exercise 5 »

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]

Function expressions

In JavaScript, a function is not a “magical language structure”, but a special kind of value.

The syntax that we used before is called a Function Declaration :

There is another syntax for creating a function that is called a Function Expression .

It allows us to create a new function in the middle of any expression.

For example:

Here we can see a variable sayHi getting a value, the new function, created as function() { alert("Hello"); } .

As the function creation happens in the context of the assignment expression (to the right side of = ), this is a Function Expression .

Please note, there’s no name after the function keyword. Omitting a name is allowed for Function Expressions.

Here we immediately assign it to the variable, so the meaning of these code samples is the same: "create a function and put it into the variable sayHi ".

In more advanced situations, that we’ll come across later, a function may be created and immediately called or scheduled for a later execution, not stored anywhere, thus remaining anonymous.

Function is a value

Let’s reiterate: no matter how the function is created, a function is a value. Both examples above store a function in the sayHi variable.

We can even print out that value using alert :

Please note that the last line does not run the function, because there are no parentheses after sayHi . There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that.

In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.

Surely, a function is a special value, in the sense that we can call it like sayHi() .

But it’s still a value. So we can work with it like with other kinds of values.

We can copy a function to another variable:

Here’s what happens above in detail:

  • The Function Declaration (1) creates the function and puts it into the variable named sayHi .
  • Line (2) copies it into the variable func . Please note again: there are no parentheses after sayHi . If there were, then func = sayHi() would write the result of the call sayHi() into func , not the function sayHi itself.
  • Now the function can be called as both sayHi() and func() .

We could also have used a Function Expression to declare sayHi , in the first line:

Everything would work the same.

You might wonder, why do Function Expressions have a semicolon ; at the end, but Function Declarations do not:

The answer is simple: a Function Expression is created here as function(…) {…} inside the assignment statement: let sayHi = …; . The semicolon ; is recommended at the end of the statement, it’s not a part of the function syntax.

The semicolon would be there for a simpler assignment, such as let sayHi = 5; , and it’s also there for a function assignment.

Callback functions

Let’s look at more examples of passing functions as values and using function expressions.

We’ll write a function ask(question, yes, no) with three parameters:

The function should ask the question and, depending on the user’s answer, call yes() or no() :

In practice, such functions are quite useful. The major difference between a real-life ask and the example above is that real-life functions use more complex ways to interact with the user than a simple confirm . In the browser, such functions usually draw a nice-looking question window. But that’s another story.

The arguments showOk and showCancel of ask are called callback functions or just callbacks .

The idea is that we pass a function and expect it to be “called back” later if necessary. In our case, showOk becomes the callback for “yes” answer, and showCancel for “no” answer.

We can use Function Expressions to write an equivalent, shorter function:

Here, functions are declared right inside the ask(...) call. They have no name, and so are called anonymous . Such functions are not accessible outside of ask (because they are not assigned to variables), but that’s just what we want here.

Such code appears in our scripts very naturally, it’s in the spirit of JavaScript.

Regular values like strings or numbers represent the data .

A function can be perceived as an action .

We can pass it between variables and run when we want.

Function Expression vs Function Declaration

Let’s formulate the key differences between Function Declarations and Expressions.

First, the syntax: how to differentiate between them in the code.

Function Declaration: a function, declared as a separate statement, in the main code flow:

Function Expression: a function, created inside an expression or inside another syntax construct. Here, the function is created on the right side of the “assignment expression” = :

The more subtle difference is when a function is created by the JavaScript engine.

A Function Expression is created when the execution reaches it and is usable only from that moment.

Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called, etc. ) from now on.

Function Declarations are different.

A Function Declaration can be called earlier than it is defined.

For example, a global Function Declaration is visible in the whole script, no matter where it is.

That’s due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.

And after all Function Declarations are processed, the code is executed. So it has access to these functions.

For example, this works:

The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.

…If it were a Function Expression, then it wouldn’t work:

Function Expressions are created when the execution reaches them. That would happen only in the line (*) . Too late.

Another special feature of Function Declarations is their block scope.

In strict mode, when a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it.

For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.

If we use Function Declaration, it won’t work as intended:

That’s because a Function Declaration is only visible inside the code block in which it resides.

Here’s another example:

What can we do to make welcome visible outside of if ?

The correct approach would be to use a Function Expression and assign welcome to the variable that is declared outside of if and has the proper visibility.

This code works as intended:

Or we could simplify it even further using a question mark operator ? :

As a rule of thumb, when we need to declare a function, the first thing to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.

That’s also better for readability, as it’s easier to look up function f(…) {…} in the code than let f = function(…) {…}; . Function Declarations are more “eye-catching”.

…But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we’ve just seen an example), then Function Expression should be used.

  • Functions are values. They can be assigned, copied or declared in any place of the code.
  • If the function is declared as a separate statement in the main code flow, that’s called a “Function Declaration”.
  • If the function is created as a part of an expression, it’s called a “Function Expression”.
  • Function Declarations are processed before the code block is executed. They are visible everywhere in the block.
  • Function Expressions are created when the execution flow reaches them.

In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable.

So we should use a Function Expression only when a Function Declaration is not fit for the task. We’ve seen a couple of examples of that in this chapter, and will see more in the future.

Lesson navigation

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Assign variable in if condition statement, good practice or not? [closed]

I moved one years ago from classic OO languages such like Java to JavaScript. The following code is definitely not recommended (or even not correct) in Java:

Basically I just found out that I can assign a variable to a value in an if condition statement, and immediately check the assigned value as if it is boolean.

For a safer bet, I usually separate that into two lines of code, assign first then check the variable, but now that I found this, I am just wondering whether is it good practice or not in the eyes of experienced JavaScript developers?

Carson's user avatar

  • "The following code is definitely not recommended (or event not correct) in Java..." Is it even correct in JavaScript? Because, as far as I can see, you return an integer ( return parseInt(...) ) if dayNumber != -1 is true, but a boolean if it is false. –  Daniel Kvist Commented Jul 3, 2015 at 10:35

10 Answers 10

I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single = instead of == or === . For example, when you see this:

you don't know if that's what they meant to do, or if they intended to write this:

If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:

Matthew Crumley's user avatar

  • 2 @Matthew Crumley : this answers my question in a clear way. I am not checking by assigning but checking whatever the value evaluates to be after the assignment. Is this understanding right? –  Michael Mao Commented Apr 5, 2010 at 2:10
  • 2 @Michael: yes, that's correct. Adding the comparison basically just makes your intentions more clear. –  Matthew Crumley Commented Apr 5, 2010 at 2:13
  • 5 The last example doesn't work, however, if you're testing for fail/success of a function that returns a boolean. In other words, while if (resultArr = myNeedle.exec(myHaystack)) {...} works, if ((resultArr = myNeedle.exec(myHaystack)) === true) {...} does not because the assignment to resultArr is always truthy even when the function result is not. If anyone uses this.. construct, remember to declare the result variable first; 'var' is not legal within the if condition statement. –  Ville Commented Apr 15, 2013 at 22:10
  • 4 You can use if (!!(value = someFunction())) , but as you said, the problem is that you can't use var inside if so you either end up creating a global, or achieve nothing as you have to declare value in a separate line anyway. Shame, I really liked this construction in C++. –  riv Commented Mar 30, 2015 at 17:05
  • 1 @riv, you're right; in case the function returns a boolean – like I said in my above comment – then the conditional works as expected. But if the function returns a boolean (as in my example) then the whole construct is kind of non-sensical; clearly my line of thinking was – judging from the example – that the function would return an array. A quick test indicates that the condition evaluates to true only when the function returns true , but in all other cases (including when an array, string, number, or null is returned) it evaluates to false . –  Ville Commented Sep 10, 2015 at 4:06

I see no proof that it is not good practice. Yes, it may look like a mistake but that is easily remedied by judicious commenting. Take for instance:

Why should that function be allowed to run a 2nd time with:

Because the first version LOOKS bad? I cannot agree with that logic.

borisdiakur's user avatar

  • 58 Not to dig up an old comment, but I don't agree with your arguments. Readable code should explain itself without the need for a comment - adding a comment to confusing code isn't a remedy. As for the second part, which says the alternative is to call the function again, I don't think anyone intends to do that. Instead you would do x = processorItensiveFunction(); if(x) { alert(x); } –  maksim Commented Dec 25, 2014 at 23:34
  • 13 @maksim: I like readable code, but that doesn't necessarily mean code should be dumbed down or too verbose. Spreading things over multiple lines and juggling values between variables can actually lead to worse code. Inserted code can have unforeseen side effects in a weakly typed / flexible language like JS. Assignment in a conditional statement is valid in javascript, because your just asking "if assignment is valid, do something which possibly includes the result of the assignment". But indeed, assigning before the conditional is also valid, not too verbose, and more commonly used. –  okdewit Commented Jul 15, 2015 at 11:30
  • 1 @maksim why would you think if ( ! x = anyFunction() ) is not readable? It doesn't need any comments whatsoever. –  jdrake Commented Jun 8, 2017 at 10:08
  • If you fix OPC, work with other devs of varying skill levels (in other words, you are a professional) you will hate that this is even possible. –  davidjmcclelland Commented Oct 17, 2017 at 19:32
  • 3 @maksim - also your solution would be very inconvenient in an if-else situation. Consider- if (condition) {...} else if (x = processorIntensiveFunction()) {alert(x)} Your prior x = processorIntensiveFunction(); would be a wasted effort should the initial condition be true. –  Adrian Bartholomew Commented Jun 3, 2019 at 1:03

I did it many times. To bypass the JavaScript warning, I add two parens:

You should avoid it, if you really want to use it, write a comment above it saying what you are doing.

Ming-Tang's user avatar

  • 2 @SHiNKiROU : how can I see javascript warnings? Is there a Javascript compiler? or the interpreter will generate some sort of warning? I am using Firefox console as in javascript debugging all the time but never see any similar outputs. Sorry about my limited experience. –  Michael Mao Commented Apr 5, 2010 at 1:57
  • 6 @Michael: JSLint ( jslint.com ) is a popular program/library that checks JavaScript programs for possible mistakes or bad code. –  Matthew Crumley Commented Apr 5, 2010 at 2:44
  • Use Mozilla Firefox with Firebug and/or Web Developer extension to check warnings. –  Ming-Tang Commented Apr 5, 2010 at 3:33
  • 1 I just tried it with if ((a = [1, 2]).length > 0) { console.log(a); } where a isn't initialized anywhere yet and it indeed worked (nice! makes using regex much easier). Is this correct that I don't need any of var|const|let here? Do you happen to know where I could read more about this trick ? –  t3chb0t Commented Oct 27, 2019 at 11:16
  • 3 @t3chb0t: As of 2022, in JavaScript, the = assignment without var|let|const is an expression . That means, it can be used anywhere expressions can be used, including within an if(...) . Also note, that unless the variable a has been declared earlier, it will be global . This is usually not what you want. –  Michael Commented Sep 5, 2022 at 14:04

There is one case when you do it, with while -loops. When reading files, you usualy do like this:

Look at the while -loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if -statement, but I guess a while loop can be included in your question as well.

The reason to this is that when using a FileInputStream , every time you call FileInputStream.readLine() , it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null , and then called it from inside of the loop too, you would only get every second line.

Hope you understand, and good luck!

user229044's user avatar

If you were to refer to Martin Fowlers book Refactoring improving the design of existing code ! Then there are several cases where it would be good practice eg. long complex conditionals to use a function or method call to assert your case:

"Motivation One of the most common areas of complexity in a program lies in complex conditional logic. As you write code to test conditions and to do various things depending on various conditions, you quickly end up with a pretty long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells you what happens but can easily obscure why it happens. As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of code with a method call named after the intention of that block of code. > With conditions you can receive further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the condition and make it clearly what you > are branching on. You also highlight the reason for the branching."

And yes his answer is also valid for Java implementations. It does not assign the conditional function to a variable though in the examples.

Community's user avatar

  • This seems to be about using functions/methods, especially when also using conditionals. This does not address the question. –  Akaisteph7 Commented May 11, 2023 at 15:41

I came here from golang, where it's common to see something like

In which err is scoped to that if block only. As such, here's what I'm doing in es6, which seems pretty ugly, but doesn't make my rather strict eslint rules whinge, and achieves the same.

The extra braces define a new, uh, "lexical scope"? Which means I can use const , and err isn't available to the outer block.

Adam Barnes's user avatar

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

Ben Zotto's user avatar

  • 1 @quixoto : Could I do this trick in Java? I wonder... I don't have jdk by hand atm so I am unable to get a sample code in Java. From my poor memory, Java will just get you a Runtime error if the returning value evaluates something not boolean as in if conditional statement, right? –  Michael Mao Commented Apr 5, 2010 at 1:52
  • 2 Ah, yes, in Java it's type-checked to be a boolean type. But you can do if (foo = getSomeBoolValue()) { } –  Ben Zotto Commented Apr 5, 2010 at 1:57
  • 1 yeah that's right. a boolean variable to test whether something succeeded and another variable to store the value returned. That's how Java does its job, I am too familiar with that so I feel strange to see Javascript can do two things in one mere line :) –  Michael Mao Commented Apr 5, 2010 at 2:00
  • @BenZotto it's not good practice why? "To avoid accidental misuse of a variable, it is usually a good idea to introduce the variable into the smallest scope possible. In particular, it is usually best to delay the definition of a variable until one can give it an initial value ... One of the most elegant applications of these two principles is to declare a variable in a conditional." -- Stroustrup, "The C++ Programming Language." –  jdrake Commented Jun 8, 2017 at 10:12
  • 2 Hi, I came here as node.js javascript user. Why there it's not good practice in one case I had pain with: if (myvar = 'just a test') Creates a node.js GLOBAL variable myvar ( nodejs.org/docs/latest-v12.x/api/globals.html#globals_global ). So if you're like me and used that variable in server request handling (coming back to it after a few seconds when other requests might have dropped in and stuff), you can be surprised at what results you get. So the recommendation is: Be aware that this pattern creates a global variable in node.js. –  tinkering.online Commented May 2, 2020 at 12:01

You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

Nitrodist's user avatar

  • @Nitrodist : thanks for this example. I am really not pro in either Java or javascript... It is good to know this approach is also feasible in Java :) –  Michael Mao Commented Apr 5, 2010 at 10:46
  • 1 I don't see the point of this. You can do it in Java, PHP and many other languages. The question was about Javascript. –  pmrotule Commented Nov 24, 2016 at 10:55
  • No it isn't necessarily, you need to re-read the question carefully. –  Nitrodist Commented Dec 1, 2016 at 21:14

It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.

You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.

thethanghn's user avatar

  • @thethanghn: that exactly what I am afraid of. when I get older and lazy I just don't want to type more into the code if fewer keystrokes will just suffice :) –  Michael Mao Commented Apr 5, 2010 at 2:37
  • 2 No, I don't get confused and I do it all the time. There are benefits to it. –  jdrake Commented Jun 8, 2017 at 10:12
  • It really depends, though, doesn't it? If you come from a 'C' background (and other languages based on C), then the construct is very familiar, and the alternatives are very awkward. IMO, it is something that is learned once and then you know. It's not something you will trip over more than once. –  Max Waterman Commented Jun 10, 2020 at 1:33

you could do something like so:

Joseph Le Brech's user avatar

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

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • What was the first "Star Trek" style teleporter in SF?
  • Why is notation in logic so different from algebra?
  • Matrix Multiplication & Addition
  • Text wrapping in longtable not working
  • A seven letter *
  • Nausea during high altitude cycling climbs
  • How do I apologize to a lecturer who told me not to ever call him again?
  • Why is a USB memory stick getting hotter when connected to USB-3 (compared to USB-2)?
  • Trill with “no turn” in Lilypond
  • Stained passport am I screwed
  • Is there a way to do a PhD such that you get a broad view of a field or subfield as a whole?
  • What does "Two rolls" quote really mean?
  • How to run only selected lines of a shell script?
  • Does the USA plan to establish a military facility on Saint Martin's Island in the Bay of Bengal?
  • When has the SR-71 been used for civilian purposes?
  • Random debug messages appearing in terminal, vim, and zsh: "channel 0: window sent adjust [...]" on Ubuntu 22.04
  • Is it helpful to use a thicker gage wire for part of a long circuit run that could have higher loads?
  • What's "the archetypal book" called?
  • What should I do if my student has quarrel with my collaborator
  • An instructor is being added to co-teach a course for questionable reasons, against the course author's wishes—what can be done?
  • I'm rewriting a 2019 oneshot and am up to 37,000 words already. Should I make them chapters or keep it as a long oneshot?
  • quantulum abest, quo minus .
  • Is there an error in Lurie, HTT, Proposition 6.1.2.6.?
  • Using rule-based symbology for overlapping layers in QGIS

assignment expression javascript

IMAGES

  1. JavaScript Operators and Expressions

    assignment expression javascript

  2. Four real JavaScript examples: (a) a simple assignment statement; (b) a

    assignment expression javascript

  3. JavaScript Assignment Operators

    assignment expression javascript

  4. Assignment Operators in JavaScript

    assignment expression javascript

  5. JavaScript Assignment Operators

    assignment expression javascript

  6. The new Logical Assignment Operators in JavaScript

    assignment expression javascript

VIDEO

  1. 28. Module :Programmer en JavaScript |Secteur : Digital & IA |الجافاسكريبت من البداية إلى الإحتراف

  2. Function declaration in JavaScript versus function expression

  3. Use Destructuring Assignment to Pass an Object as a Function's Parameters (ES6) freeCodeCamp

  4. LaunchCode

  5. Tìm hiểu Regular Expression

  6. 👶 JavaScript для начинающих: 5. Выражения и присваивание

COMMENTS

  1. Assignment (=)

    The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables. ... JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object ...

  2. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  3. Expressions and operators

    Expressions and operators. This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value.

  4. How do you use the ? : (conditional) operator in JavaScript?

    It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator". If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.

  5. JavaScript Assignment Operators

    Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables. In Destructuring Assignment on the left-hand side, we define which value should be unpacked from the sourced v

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

  7. Logical AND assignment (&&=)

    The logical AND assignment (&&=) operator only evaluates the right operand and assigns to the left if the left operand is truthy. Logical AND assignment short-circuits, meaning that x &&= y is equivalent to x && (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not truthy, due to ...

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

  9. Assignment Expressions

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

  10. Assignment operators

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

  11. Expressions and 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. this. Use the this keyword to refer to the current object. In general, this refers to the calling object in a method.

  12. JavaScript Operators (with Examples)

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

  13. JavaScript Operators

    There are different types of JavaScript operators: Arithmetic Operators. Assignment Operators. Comparison Operators. String Operators. Logical Operators. Bitwise Operators. Ternary Operators. Type Operators.

  14. javascript

    In JavaScript the = operator is an expression and evaluates the assigned value. Because it is an expression it can be used anywhere an expression is allowed even though it causes a side-effect. Thus: settings.maxId != null && (params.max_id = settings.maxId)

  15. JavaScript Expressions and Statements

    A function expression is part of a variable assignment expression and may or may not contain a name. Since this type of function appears after the assignment operator =, it is evaluated as an ...

  16. Logical OR assignment (||=)

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

  17. Expressions and operators

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

  18. Function expressions

    A Function Expression is created when the execution reaches it and is usable only from that moment. Once the execution flow passes to the right side of the assignment let sum = function… - here we go, the function is created and can be used (assigned, called, etc. ) from now on. Function Declarations are different.

  19. Expression statement

    Expression statement. An expression statement is an expression used in a place where a statement is expected. The expression is evaluated and its result is discarded — therefore, it makes sense only for expressions that have side effects, such as executing a function or updating a variable.

  20. javascript

    Assignment in a conditional statement is valid in javascript, because your just asking "if assignment is valid, do something which possibly includes the result of the assignment". But indeed, assigning before the conditional is also valid, not too verbose, and more commonly used. - okdewit.