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

JavaScript OR (||) variable assignment explanation

Given this snippet of JavaScript...

Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?

My understanding is that variable f will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.

Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f having a true boolean value, rather than the value of d itself.

  • variable-assignment
  • or-operator

Bergi's user avatar

  • 4 Old question, but regarding PHP, there is a construct you can use: $f=$a or $f=$b or $f=$c; // etc . PHP has both the || operator and the or operator, which do the same job; however or is evaluated after assignment while || is evaluated before. This also give you the perlish style of $a=getSomething() or die('oops'); –  Manngo Commented Oct 14, 2016 at 7:30
  • 1 In PHP 5.3 you can leave out the middle part of the ternary operator so basing from that... You can also cut that a bit shorter into something like this: $f = $a ?: $b ?: $c; –  Rei Commented Nov 30, 2017 at 10:31
  • 1 As of PHP 7 you can use ?? for this. $a = $b ?? 'default' –  Spencer Ruskin Commented Mar 19, 2018 at 23:09
  • @SpencerRuskin so $a will be assigned the value of $b if $b is true, other 'default' ? –  oldboy Commented Mar 22, 2019 at 18:31
  • That's right. Look at the null coalescing operator section on this page: php.net/manual/en/migration70.new-features.php –  Spencer Ruskin Commented Mar 29, 2019 at 14:54

12 Answers 12

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

Lightness Races in Orbit's user avatar

  • 62 Just mind the 'gotcha' which is that the last one will always get assigned even if they're all undefined, null or false. Setting something you know isn't false, null, or undefined at the end of the chain is a good way to signal nothing was found. –  Erik Reppen Commented Aug 29, 2011 at 16:51
  • 1 I've seen this technique for years, but what striked me just then when I wanted to use it is that the result of the expression is not cast to boolean. You cannot later do if( true == f ) . If an integer was stored in f, then this test will always return false. –  user1115652 Commented Aug 1, 2013 at 2:11
  • 10 Actually, you can do if(true == f) , which is the same as if(f) : the test will pass. If you want to also test the type of f , use strict comparison: if(true === f) , which will fail indeed. –  Alsciende Commented Jun 6, 2016 at 9:44
  • 5 Yes, short-circuit evaluation is common. But the distinction here lies in the way JavaScript returns the last value that halted the execution. @Anurag's answer does a much better job of explaining this. –  Ben.12 Commented Dec 1, 2017 at 21:58
  • not sure if that is the best explanation for beginners. I would recommend: javascript.info/logical-operators –  csguy Commented Jun 7, 2020 at 20:43

This is made to assign a default value , in this case the value of y , if the x variable is falsy .

The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages.

The Logical OR operator ( || ) returns the value of its second operand, if the first one is falsy, otherwise the value of the first operand is returned.

For example:

Falsy values are those who coerce to false when used in boolean context, and they are 0 , null , undefined , an empty string, NaN and of course false .

Christian C. Salvadó's user avatar

  • 3 +1 Is there another operator like that? Or is || exclusive. –  OscarRyz Commented Jun 21, 2010 at 21:13
  • 11 @Support (@Oscar): The Logical && operator has a similar behavior, it returns the value of the first operand if it's by itself falsy and returns the value of the second operand, only if the first one is truthy , e.g. ("foo" && "bar") == "bar" and (0 && "bar") == 0 –  Christian C. Salvadó Commented Jun 21, 2010 at 21:18
  • 14 Falsy is in fact the technical term. –  ChaosPandion Commented Jun 22, 2010 at 2:36
  • 10 So we learned about ||, &&, "Falsy" and "Truly" in this post. Best answer with "hidden" gifts. –  Alex Commented Aug 20, 2015 at 12:36
  • 6 @Alex NB: "Truthy" (!"Truly") –  Bumpy Commented Dec 3, 2016 at 6:20

Javacript uses short-circuit evaluation for logical operators || and && . However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true , or false value.

The following values are considered falsy in JavaScript.

  • "" (empty string)

Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.

The first 5 values upto NaN are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello" which makes the entire expression true, so anything further up will not be evaluated, and "Hello" gets returned as a result of the expression. Similarly, in this case:

The first 5 values are all truthy and get evaluated until it meets the first falsy value ( null ) which makes the expression false, so 2010 isn't evaluated anymore, and null gets returned as a result of the expression.

The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello" to b as it makes it easier to assign a default value, instead of doing if-else checks.

You could call the below example an exploitation of this feature, and I believe it makes code harder to read.

Inside the alert, we check if messages is falsy, and if yes, then evaluate and return noNewMessagesText , otherwise evaluate and return newMessagesText . Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages." .

Marjan Venema's user avatar

  • 48 This is the best answer in my opinion because of the following explanation: However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true, or false value. –  mastazi Commented Dec 28, 2015 at 3:48
  • 1 @mastazi Yep, it should go in bold font IMHO. –  noober Commented Jan 24, 2016 at 23:51
  • 6 Should be the answer, it shows the values being chosen over test cases. –  Imaginary Commented Sep 14, 2016 at 10:15
  • Agreed, this is my favorite answer as it specifically addresses JavaScript variable assignment concerns. Additionally, if you choose to use a ternary as one of the subsequent variables to test for assignment (after the operator) you must wrap the ternary in parentheses for assignment evaluation to work properly. –  Joey T Commented Jan 29, 2019 at 21:19

Javascript variables are not typed, so f can be assigned an integer value even though it's been assigned through boolean operators.

f is assigned the nearest value that is not equivalent to false . So 0, false, null, undefined, are all passed over:

Alsciende's user avatar

  • 13 Don't forget '' also equal false in this case. –  Brigand Commented Apr 4, 2013 at 17:07
  • Upvote for pointing out that f is assigned the NEAREST value which is a pretty important point here. –  steviesh Commented Jun 6, 2016 at 3:45
  • 3 "Nearest" isn't quite true, though it does have that appearance. The boolean || operator, being a boolean operator has two operands: a left side and a right side. If the left side of the || is truthy , the operation resolves to the left side and the right side is ignored. If the left side is falsy , it resolves to the right side. So null || undefined || 4 || 0 actually resolves to undefined || 4 || 0 which resolves to 4 || 0 which resolves to 4 . –  devios1 Commented Oct 16, 2017 at 16:26
  • @devios1 but 4 is nearest –  milos Commented Oct 19, 2021 at 9:13

There isn't any magic to it. Boolean expressions like a || b || c || d are lazily evaluated. Interpeter looks for the value of a , it's undefined so it's false so it moves on, then it sees b which is null, which still gives false result so it moves on, then it sees c - same story. Finally it sees d and says 'huh, it's not null, so I have my result' and it assigns it to the final variable.

This trick will work in all dynamic languages that do lazy short-circuit evaluation of boolean expressions. In static languages it won't compile (type error). In languages that are eager in evaluating boolean expressions, it'll return logical value (i.e. true in this case).

Marcin's user avatar

  • 6 In the pretty static language C# one can use the ?? operator á la: object f = a ?? b ?? c ?? d ?? e; –  herzmeister Commented Jan 20, 2010 at 11:14
  • 2 herzmeister - thanks! I didn't know that ?? operator can be chained in C# and used in lazy evaluation techniques –  Marek Commented Mar 8, 2012 at 8:49
  • 3 As mentioned elsewhere, that last d will be assigned whether or not it was null/undefined or not. –  BlackVegetable Commented Jul 2, 2013 at 17:17
  • One slight correction: the || operator always resolves to the whole right side operand when the left side is falsy. Being a boolean operator it only sees two inputs: the left side and the right side. The parser doesn't see them as a series of terms, so it doesn't actually stop when it finds the first truthy value unless that value is also the left hand operand of another || . –  devios1 Commented Oct 16, 2017 at 16:38

This question has already received several good answers.

In summary, this technique is taking advantage of a feature of how the language is compiled. That is, JavaScript "short-circuits" the evaluation of Boolean operators and will return the value associated with either the first non-false variable value or whatever the last variable contains. See Anurag's explanation of those values that will evaluate to false.

Using this technique is not good practice for several reasons; however.

Code Readability: This is using Boolean operators, and if the behavior of how this compiles is not understood, then the expected result would be a Boolean value.

Stability: This is using a feature of how the language is compiled that is inconsistent across multiple languages, and due to this it is something that could potentially be targeted for change in the future.

Documented Features: There is an existing alternative that meets this need and is consistent across more languages. This would be the ternary operator:

() ? value 1: Value 2.

Using the ternary operator does require a little more typing, but it clearly distinguishes between the Boolean expression being evaluated and the value being assigned. In addition it can be chained, so the types of default assignments being performed above could be recreated.

Community's user avatar

  • potentially be targeted for change in the future. yes, but I don't that applies for javascript. –  Imaginary Commented Sep 14, 2016 at 10:17
  • Came here and saw all the above answers and was thinking to myself that something just looked off about the assignment. I've just been reading Clean Code by Robert C Martin and this type of assignment definitely violates the "Have no Side Effects" rule...while the author himself states that his book is only one of many techniques for generating good code, I was still surprised that no one else objected to this kind of assignment. +1 –  Albert Rothman Commented Sep 20, 2016 at 23:50
  • Thank you for the response. I think more people need to consider side effects when writing code, but until someone has spent a lot of time maintaining other people's code. They often don't consider it. –  WSimpson Commented Sep 27, 2016 at 13:53
  • 2 You really think that monstrosity is clearer than a || b || c || d || e ? –  devios1 Commented Oct 16, 2017 at 16:41
  • 1 @AlbertRothman I don't see any side effects. Nothing is being mutated. It's simply a shorthand for null coalescing, which is a quite common feature in many languages. –  devios1 Commented Oct 16, 2017 at 16:43

Return output first true value .

If all are false return last false value.

Arshid KV's user avatar

Its called Short circuit operator.

Short-circuit evaluation says, the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression. when the first argument of the OR (||) function evaluates to true, the overall value must be true.

It could also be used to set a default value for function argument.`

Vijay's user avatar

It's setting the new variable ( z ) to either the value of x if it's "truthy" (non-zero, a valid object/array/function/whatever it is) or y otherwise. It's a relatively common way of providing a default value in case x doesn't exist.

For example, if you have a function that takes an optional callback parameter, you could provide a default callback that doesn't do anything:

Matthew Crumley's user avatar

It means that if x is set, the value for z will be x , otherwise if y is set then its value will be set as the z 's value.

it's the same as

It's possible because logical operators in JavaScript doesn't return boolean values but the value of the last element needed to complete the operation (in an OR sentence it would be the first non-false value, in an AND sentence it would be the last one). If the operation fails, then false is returned.

Andris's user avatar

  • 5 this is wrong! if (x) { z = x; } else {z = y;} if the first value is false, the second value is always assigned not depending what the value actually is. –  evilpie Commented Jun 21, 2010 at 20:13
  • Except that I think it just assigns y to z if x is false . That's the way it works for me in FF, of course, that might be implementation dependent, too. –  tvanfosson Commented Jun 21, 2010 at 20:15
  • 7 The last part about returning false isn't true (no pun intended). If the first value is falsey, the || operator just returns the second value, regardless of whether it's truthy or not. –  Matthew Crumley Commented Jun 21, 2010 at 20:15
  • -1. Your equivalent code snippet is accurate, but the important point is that z gets set to the value of x if that value is truthy . Otherwise it gets set to the value of y . This means that if x is set to, for example, 0 , or the empty string "" , this doesn’t do what you say, since those values are falsy . –  Daniel Cassidy Commented Sep 27, 2010 at 16:56

It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.

Will output 'bob';

tvanfosson's user avatar

  • 1 You should clarify what you mean by ‘empty’. Empty strings coerce to false , but empty arrays or objects coerce to true . –  Daniel Cassidy Commented Sep 27, 2010 at 16:58
  • @Daniel "null, empty, or 0" -- null would apply with respect to arrays and objects. Point taken, though. –  tvanfosson Commented Sep 27, 2010 at 17:01

According to the Bill Higgins' Blog post; the Javascript logical OR assignment idiom (Feb. 2007), this behavior is true as of v1.2 (at least)

He also suggests another use for it (quoted): " lightweight normalization of cross-browser differences "

Alon Brontman's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript variables variable-assignment or-operator 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

Logical operators

There are four logical operators in JavaScript: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing). Here we cover the first three, the ?? operator is in the next article.

Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.

Let’s see the details.

The “OR” operator is represented with two vertical line symbols:

In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .

In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens with boolean values.

There are four possible logical combinations:

As we can see, the result is always true except for the case when both operands are false .

If an operand is not a boolean, it’s converted to a boolean for the evaluation.

For instance, the number 1 is treated as true , the number 0 as false :

Most of the time, OR || is used in an if statement to test if any of the given conditions is true .

For example:

We can pass more conditions:

OR "||" finds the first truthy value

The logic described above is somewhat classical. Now, let’s bring in the “extra” features of JavaScript.

The extended algorithm works as follows.

Given multiple OR’ed values:

The OR || operator does the following:

  • Evaluates operands from left to right.
  • For each operand, converts it to boolean. If the result is true , stops and returns the original value of that operand.
  • If all operands have been evaluated (i.e. all were false ), returns the last operand.

A value is returned in its original form, without the conversion.

In other words, a chain of OR || returns the first truthy value or the last one if no truthy value is found.

For instance:

This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.

Getting the first truthy value from a list of variables or expressions.

For instance, we have firstName , lastName and nickName variables, all optional (i.e. can be undefined or have falsy values).

Let’s use OR || to choose the one that has the data and show it (or "Anonymous" if nothing set):

If all variables were falsy, "Anonymous" would show up.

Short-circuit evaluation.

Another feature of OR || operator is the so-called “short-circuit” evaluation.

It means that || processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.

The importance of this feature becomes obvious if an operand isn’t just a value, but an expression with a side effect, such as a variable assignment or a function call.

In the example below, only the second message is printed:

In the first line, the OR || operator stops the evaluation immediately upon seeing true , so the alert isn’t run.

Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.

&& (AND)

The AND operator is represented with two ampersands && :

In classical programming, AND returns true if both operands are truthy and false otherwise:

An example with if :

Just as with OR, any value is allowed as an operand of AND:

AND “&&” finds the first falsy value

Given multiple AND’ed values:

The AND && operator does the following:

  • For each operand, converts it to a boolean. If the result is false , stops and returns the original value of that operand.
  • If all operands have been evaluated (i.e. all were truthy), returns the last operand.

In other words, AND returns the first falsy value or the last value if none were found.

The rules above are similar to OR. The difference is that AND returns the first falsy value while OR returns the first truthy one.

We can also pass several values in a row. See how the first falsy one is returned:

When all values are truthy, the last value is returned:

The precedence of AND && operator is higher than OR || .

So the code a && b || c && d is essentially the same as if the && expressions were in parentheses: (a && b) || (c && d) .

Sometimes, people use the AND && operator as a "shorter way to write if ".

The action in the right part of && would execute only if the evaluation reaches it. That is, only if (x > 0) is true.

So we basically have an analogue for:

Although, the variant with && appears shorter, if is more obvious and tends to be a little bit more readable. So we recommend using every construct for its purpose: use if if we want if and use && if we want AND.

The boolean NOT operator is represented with an exclamation sign ! .

The syntax is pretty simple:

The operator accepts a single argument and does the following:

  • Converts the operand to boolean type: true/false .
  • Returns the inverse value.

A double NOT !! is sometimes used for converting a value to boolean type:

That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.

There’s a little more verbose way to do the same thing – a built-in Boolean function:

The precedence of NOT ! is the highest of all logical operators, so it always executes first, before && or || .

What's the result of OR?

What is the code below going to output?

The answer is 2 , that’s the first truthy value.

What's the result of OR'ed alerts?

What will the code below output?

The answer: first 1 , then 2 .

The call to alert does not return a value. Or, in other words, it returns undefined .

  • The first OR || evaluates its left operand alert(1) . That shows the first message with 1 .
  • The alert returns undefined , so OR goes on to the second operand searching for a truthy value.
  • The second operand 2 is truthy, so the execution is halted, 2 is returned and then shown by the outer alert.

There will be no 3 , because the evaluation does not reach alert(3) .

What is the result of AND?

What is this code going to show?

The answer: null , because it’s the first falsy value from the list.

What is the result of AND'ed alerts?

What will this code show?

The answer: 1 , and then undefined .

The call to alert returns undefined (it just shows a message, so there’s no meaningful return).

Because of that, && evaluates the left operand (outputs 1 ), and immediately stops, because undefined is a falsy value. And && looks for a falsy value and returns it, so it’s done.

The result of OR AND OR

What will the result be?

The answer: 3 .

The precedence of AND && is higher than || , so it executes first.

The result of 2 && 3 = 3 , so the expression becomes:

Now the result is the first truthy value: 3 .

Check the range between

Write an if condition to check that age is between 14 and 90 inclusively.

“Inclusively” means that age can reach the edges 14 or 90 .

Check the range outside

Write an if condition to check that age is NOT between 14 and 90 inclusively.

Create two variants: the first one using NOT ! , the second one – without it.

The first variant:

The second variant:

A question about "if"

Which of these alert s are going to execute?

What will the results of the expressions be inside if(...) ?

The answer: the first and the third will execute.

Check the login

Write the code which asks for a login with prompt .

If the visitor enters "Admin" , then prompt for a password, if the input is an empty line or Esc – show “Canceled”, if it’s another string – then show “I don’t know you”.

The password is checked as follows:

  • If it equals “TheMaster”, then show “Welcome!”,
  • Another string – show “Wrong password”,
  • For an empty string or cancelled input, show “Canceled”

The schema:

Please use nested if blocks. Mind the overall readability of the code.

Hint: passing an empty input to a prompt returns an empty string '' . Pressing ESC during a prompt returns null .

Run the demo

Note the vertical indents inside the if blocks. They are technically not required, but make the code more readable.

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Home » JavaScript Tutorial » An Introduction to JavaScript Logical Operators

An Introduction to JavaScript Logical Operators

Javascript Logical Operator

Summary : in this tutorial, you will learn how to use the JavaScript logical operators including the logical NOT operator( ! ), the logical AND operator ( && ) and the logical OR operator ( || ).

The logical operators are important in JavaScript because they allow you to compare variables and do something based on the result of that comparison.

For example, if the result of the comparison is true , you can run a block of code; if it’s false , you can execute another code block.

JavaScript provides three logical operators:

  • ! (Logical NOT)
  • || (Logical OR)
  • && (Logical AND)

1) The Logical NOT operator (!)

JavaScript uses an exclamation point ! to represent the logical NOT operator. The ! operator can be applied to a single value of any type, not just a Boolean value.

When you apply the ! operator to a boolean value, the ! returns true if the value is false and vice versa. For example:

In this example, the eligible is true so !eligible returns false . And since the required is true , the !required returns false .

When you apply the ! operator to a non-Boolean value. The ! operator converts the value to a boolean value and then negates it.

The following example shows how to use the ! operator:

The logical ! operator works based on the following rules:

  • If a is undefined , the result is true .
  • If a is null , the result is true .
  • If a is a number other than 0 , the result is false .
  • If a is NaN , the result is true .
  • If a is an object , the result is false.
  • If a is an empty string, the result is true . If a is a non-empty string, the result is false

The following demonstrates the results of the logical ! operator when applying to a non-boolean value:

Double-negation (!!)

Sometimes, you may see the double negation ( !! ) in the code. The !! uses the logical NOT operator ( ! ) twice to convert a value to its real boolean value.

The result is the same as using the Boolean() function. For example:

The first ! operator negates the Boolean value of the counter variable. If the counter is true , then the ! operator makes it false and vice versa.

The second ! operator negates the result of the first ! operator and returns the real boolean value of the counter variable.

2) The Logical AND operator (&&)

JavaScript uses the double ampersand ( && ) to represent the logical AND operator. The following expression uses the && operator:

If a can be converted to true , the && operator returns the b ; otherwise, it returns the a . This rule is applied to all boolean values.

The following truth table illustrates the result of the && operator when it is applied to two Boolean values:

aba && b
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

The result of the && operator is true only if both values are true , otherwise, it is false . For example:

In this example, the eligible is false , therefore, the value of the expression eligible && required is false .

See the following example:

In this example, both eligible and required are true , therefore, the value of the expression eligible && required is true .

Short-circuit evaluation

The && operator is short-circuited. It means that the && operator evaluates the second value only if the first one doesn’t suffice to determine the value of an expression. For example:

In this example, b is true therefore the && operator could not determine the result without further evaluating the second expression ( 1/0 ).

The result is Infinity which is the result of the expression ( 1/0 ). However:

In this case, b is false , the && operator doesn’t need to evaluate the second expression because it can determine the final result as false based value of the first value.

The chain of && operators

The following expression uses multiple && operators:

The &&  operator carries the following:

  • Evaluates values from left to right.
  • For each value, convert it to a boolean. If the result is  false , stops and returns the original value.
  • If all values are truthy values, return the last value.

In other words, The && operator returns the first falsey value or the last truthy value.

If a value can be converted to  true , it is called a truthy value. If a value can be converted to  false , it is a called a falsey value.

3) The Logical OR operator (||)

JavaScript uses the double-pipe || to represent the logical OR operator. You can apply the || operator to two values of any type:

If  a can be converted to  true , returns  a ; else, returns  b . This rule is also applied to boolean values.

The following truth table illustrates the result of the || operator based on the value of the operands:

aba || b
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

The || operator returns false if both values are evaluated to false . In case either value is true , the || operator returns true . For example:

See another example:

In this example, the expression eligible || required returns false because both values are false .

The || operator is also short-circuited

Similar to the && operator, the || operator is short-circuited. It means that if the first value evaluates to true , the && operator doesn’t evaluate the second one.

The chain of || operators

The following example shows how to use multiple || operators in an expression:

The ||  operator does the following:

  • For each value, convert it to a boolean value. If the result of the conversion is  true , stops and returns the value.
  • If all values have been evaluated to false , returns the last value.

In other words, the chain of the ||  operators returns the first truthy value or the last one if no truthy value is found.

Logical operator precedence

When you mix logical operators in an expression, the JavaScript engine evaluates the operators based on a specified order. This order is called the operator precedence .

In other words, the operator precedence is the order of evaluating logical operators in an expression.

The precedence of the logical operator is in the following order from the highest to the lowest:

  • Logical NOT (!)
  • Logical AND (&&)
  • Logical OR (||)
  • The NOT operator ( ! ) negates a boolean value. The ( !! ) converts a value into its real boolean value.
  • The AND operator ( && ) is applied to two Boolean values and returns true if both are true.
  • The OR operator ( || ) is applied to two Boolean values and returns true if one of the operands is true .
  • Both && and || operator are short-circuited. They can also be applied to non-Boolean values.
  • The logical operator precedence from the highest to the lowest is ! , && and || .
  • The AND operator returns the first falsey value or the last truthy value.
  • The || operator returns the first falsey value.

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]

Top Tutorials

Top references, top examples, get certified.

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

Nathan Sebhastian

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

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

Arithmetic Operators

Assignment operators, comparison operators, logical operators.

  • Ternary Operators

The typeof Operator

Bitwise operators.

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

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

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

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

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

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

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

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

1. Addition operator

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

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

2. Subtraction operator

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

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

3. Multiplication operator

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

4. Division operator

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

5. Remainder operator

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

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

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

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

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

6. Exponentiation operator

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

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

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

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

7. Increment operator

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

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

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

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

Consider the following example:

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

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

8. Decrement operator

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

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

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

Arithmetic operators summary

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

NameOperation exampleMeaning
Assignment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Remainder assignment
Exponentiation assignment

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

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

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

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

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

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

There are 8 kinds of comparison operators available in JavaScript:

NameOperation exampleMeaning
Equal Returns if the operands are equal
Not equal Returns if the operands are not equal
Strict equal Returns if the operands are equal and have the same type
Strict not equal Returns if the operands are not equal, or have different types
Greater than Returns if the left operand is greater than the right operand
Greater than or equal Returns if the left operand is greater than or equal to the right operand
Less than Returns if the left operand is less than the right operand
Less than or equal Returns if the left operand is less than or equal to the right operand

Here are some examples of using comparison operators:

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

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

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

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

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

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

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

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

There are three logical operators available in JavaScript:

NameOperation exampleMeaning
Logical AND Returns if all operands are , else returns
Logical OR`xy`Returns if one of the operands is , else returns
Logical NOT Reverse the result: returns if and vice versa

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

These logical operators follow the laws of mathematical logic:

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

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

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

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

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

Ternary Operator

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

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

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

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

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

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

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

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

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

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

Here are some examples of using the operator:

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

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

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

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

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

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

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

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

There are 7 types of bitwise operators in JavaScript:

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

Let's see how they work.

1. Bitwise AND operator

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

2. Bitwise OR operator

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

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

Bitwise XOR operator

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

5 = 00000101

Bitwise NOT operator

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

Bitwise Left Shift operator

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

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

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

Bitwise Right Shift operator

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

Bitwise Zero-fill Right Shift operator

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

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

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

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

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

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

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

Congratulations on finishing this guide!

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

beginning-js-cover

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

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

Until next time!

Read more posts .

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

  • 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

  • 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 Logical AND assignment (&&=) Operator

This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value.

We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y) .   If the value of x is true, then the statement (x = y) executes, and the value of y gets stored into x but if the value of x is a falsy value then the statement (x = y) does not get executed.

is equivalent to 

Example: This example shows the basic use of the Javascript Logical AND assignment(&&=) operator.

           

Example 2: This example shows the basic use of the Javascript Logical AND assignment(&&=) operator.

       

Javascript Logical AND assignment(&&=) operator

Javascript Logical AND assignment(&&=) operator

We have a complete list of Javascript Operators, to check those please go through the Javascript Operators Complete Reference article.

Supported Browsers:

author

Please Login to comment...

Similar reads.

  • Web Technologies
  • javascript-operators
  • JavaScript-Questions
  • 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?

logo

JavaScript Operators and Operator Precedence – Beginner‘s Guide

' data-src=

JavaScript makes heavy use of operators to manipulate values and variables in code. As a beginner, grasping how these operators work and their order of evaluation can be confusing initially. In this comprehensive 2650+ words guide, we will cover all the key concepts you need to know about operators in JavaScript.

What are Operators in JavaScript?

Operators are special symbols or keywords that perform operations on operands (values and variables).

For example:

The value that the operator works on is called the operand . Operands can be literal values, variables, or more complex expressions that resolve to a value.

According to Code Frequency analysis of open-source JavaScript projects on Github, some of the most commonly used operators are:

OperatorFrequency of Use
.#1 most used
=#3 most used
+#6 most used
++#8 most used
*#11 most used

This shows operators are extensively used in real-world JavaScript code.

Some broad categories of JavaScript operators include:

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

Later we will explain the most popular operators falling under these categories that every JavaScript developer should know.

Operator Precedence in JavaScript

Operator precedence determines the order in which operations get performed in expressions with multiple operators.

Certain operators have higher precedence than others. For example, the multiplication operator has a higher precedence than the addition operator.

Consider this example:

Here, the multiplication happens first before the addition because it has higher precedence. So 3 * 4 equals 12, then 2 gets added giving 14.

The overall order is:

  • Parentheses
  • Exponential
  • Multiplication & Division (left-to-right)
  • Addition & Subtraction (left-to-right)

Following this exact precedence order, JavaScript evaluates each expression from start to finish.

Understanding this flow helps avoid errors in complex statements with multiple operators. Getting it wrong can lead to unintended behavior.

Now let‘s dive deeper into the most popular JavaScript operator categories.

Types of Operators in JavaScript

JavaScript includes a diverse range of operators to perform different types of actions and operations. We will focus on the operators you need to know as a beginner.

1. Arithmetic Operators

These operators are used to perform common mathematical calculations:

This covers basic math operations like addition/subtraction to more complex ones like modulus, exponential, increment and decrement.

According to Code Frequency stats, the + and ++ operators appear in the top 10 most used operators in JavaScript code on Github.

Arithmetic operators take numerical values (either literals or variables) as their operands. By combining them, we can execute complex math in JavaScript.

2. Assignment Operators

The most basic assignment operator is = that assigns a value to a variable.

Some other assignment operators:

These operators first perform the arithmetic operation on current and new value, and assign the result back to the variable.

Assignment operators rank high in usage frequency – the basic = assignment operator is #3 most used across JavaScript projects per Code Frequency.

3. Comparison Operators

Comparison operators compare two operand values or expressions and return a boolean true / false result based on that condition.

The comparison operators supported in JavaScript are:

  • Equal to (==)
  • Strict equal to (===)
  • Not equal to (!=)
  • Strict not equal (!==)
  • Greater than (>)
  • Greater than or equal to (>=)
  • Less than (<)
  • Less than or equal to (<=)

Equal to (==) compares values only, while strict equal to (===) checks the value AND matches data type.

Using === avoids unexpected type coercions.

4. Logical Operators

Logical operators evaluate an expression and return a boolean true or false.

The logical operators are:

  • Logical AND (&&)
  • Logical OR (||)
  • Logical NOT (!)

These allow creating complex boolean logic conditions in code.

5. Ternary Operator

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

It adheres to this syntax:

This acts as a shorthand for if-else statement in assigning values based on conditions.

Operator Precedence Revisited

We learned about different JavaScript operators. But what happens when an expression contains multiple operators? Operator precedence rules decide the order of evaluation.

Here, multiplication occurs before addition because it has higher precedence. So x equals 25 instead of 35.

The complete JavaScript operator precedence order is:

  • Grouping – parentheses ()
  • Negation/Increment operators (!, –, ++)
  • Exponential (**)
  • Multiplication/Division (*, /)
  • Addition/Subtraction (+, -)
  • Relational operators (<, <=, >, >=)
  • Equality operators (==, !=, ===, !==)
  • Assignment operators (=, +=, -= etc.)
  • Comma Operator (,)

This precise precedence hierarchy is applied while evaluating expressions with multiple operators.

Understanding this order allows you to correctly reason about complex statements. Getting it wrong will lead to unintended behavior.

Examples of Operator Precedence

Let‘s breakdown a few examples in detail:

These examples clearly show how operator precedence can dramatically affect results.

Familiarity with these rules will let you interpret and debug complex code much more easily.

Getting precedence wrong is a common source of unexpected behavior and bugs in JavaScript code.

Common Operator Precedence Errors

Some typical errors that occur due to incorrect assumptions about operator precedence:

1. Incorrect string concatenation

2. Mathematical calculations go wrong

3. Incorrect boolean logic

These kinds of errors can be avoided by properly applying the operator precedence rules.

Using parentheses also helps in overriding default precedence when unsure.

Associativity of Operators

Associativity refers to the direction in which operators of the same precedence are evaluated.

Most JavaScript operators are left-to-right associative – they group left-to-right in the absence of parentheses.

But a few operators show right-to-left associativity – they group right-to-left direction.

For instance, the exponentiation operator (**) is right-to-left associative:

This behavior can cause mistakes if we assume left-to-right evaluation for everything.

So be aware of associativity rules to accurately reason about complex expressions.

Recommended Practices

When working extensively with operators, adopt these best practices:

  • Use parentheses to explicitly dictate order, improves readability
  • Break down large expressions into smaller components
  • Use descriptive variable/function names
  • Follow a consistent formatting style guide
  • Add comments explaining complex logic flow and operations
  • Use strict equality checks (===) instead of loose equality (==)
  • Use template literals for string manipulation instead of concatenation
  • Prefer increment/decrement operators (++/–) when possible

Cultivating these good habits early on will help avoid lots of pitfalls later in complex JavaScript applications.

New and Experimental Operators

JavaScript continues to evolve with newer ECMAScript standards introducing experimental features.

Some operators added recently:

1. Nullish Coalescing Operator (??)

The ?? operator returns the right-hand value when the left one is null or undefined.

2. Optional Chaining Operator (?.)

The ?. operator stops evaluation if trying to access non-existent property.

These experimental operators open new possibilities and use cases going forward.

In this comprehensive 2600+ words guide, we started by answering:

  • What operators are and how they evaluate operands
  • Different categories of operators like arithmetic, logical and more
  • Operator precedence determines order of evaluation
  • Examples showed precedence dramatically affects results

We then covered specifics of the most popular operators used in JavaScript:

  • Arithmetic operators for math calculations
  • Assignment operators to assign values
  • Comparison operators return boolean result
  • Logical operators combine boolean logic
  • Ternary operator shorthands if-else conditional

And some key concepts like:

  • Operator precedence order – which operator gets evaluated first
  • Common mistakes due to incorrect assumptions
  • Associativity rules – left-to-right or right-to-left
  • Best practices for clean and optimized code

JavaScript operators provide the building blocks that power complex logic. Mastering them early on gives a major boost for becoming an efficient JavaScript programmer.

Of all the operator concepts covered, which one did you find most useful and why? Let me know in the comments!

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

How to Build an Advanced Real-time Twitter Sentiment Monitoring Pipeline

How to Build an Advanced Real-time Twitter Sentiment Monitoring Pipeline

Sentiment analysis has become an indispensable tool for gaining quantified insights into public opinion. By automatically…

How is == Different from === in JavaScript? Strict vs Loose Equality Explained

How is == Different from === in JavaScript? Strict vs Loose Equality Explained

Understanding equality operators is key to writing good JavaScript code. However, the subtle differences between ==…

Python If-Else Statements: A Beginner‘s Guide

Python If-Else Statements: A Beginner‘s Guide

Conditional statements like if-else are an essential part of any programming language. They allow you to…

So that whole coding bootcamp thing is a scam, right?

So that whole coding bootcamp thing is a scam, right?

As a lead software engineer with over 18 years of experience building complex full-stack enterprise systems,…

Playing Make-Believe with Proxy Servers

Playing Make-Believe with Proxy Servers

Introduction Proxy servers act as intermediaries for requests between clients and servers. By intercepting traffic, proxies…

React Binding Patterns: 5 Approaches for Handling this

React Binding Patterns: 5 Approaches for Handling this

JavaScript‘s this keyword behavior has confused developers for ages. When using React with ES6 classes, the…

COMMENTS

  1. Logical OR assignment (||=)

    Logical OR assignment (||=) - JavaScript - MDN Web Docs

  2. Expressions and operators

    Expressions and operators - JavaScript - MDN Web Docs

  3. JavaScript OR (||) variable assignment explanation

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

  4. JavaScript Assignment

    JavaScript Assignment

  5. JavaScript Logical Assignment Operators

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

  6. Assignment (=)

    Assignment (=) The assignment (=) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.

  7. Logical operators

    Logical operators

  8. An Introduction to JavaScript Logical Operators

    The following example shows how to use the ! operator: !a. The logical ! operator works based on the following rules: If a is undefined, the result is true. If a is null, the result is true. If a is a number other than 0, the result is false. If a is NaN, the result is true. If a is an object, the result is false.

  9. JavaScript Operators

    Javascript operators are used to perform different types of mathematical and logical computations. Examples: The Assignment Operator = assigns values. The Addition Operator + adds values. The Multiplication Operator * multiplies values. The Comparison Operator > compares values

  10. Learn JavaScript Operators

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

  11. Assignment operators

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

  12. Assignment operators

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

  13. Expressions and operators

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

  14. JavaScript Assignment Operators

    JavaScript Assignment Operators

  15. JavaScript Operators (with Examples)

    JavaScript Operators (with Examples)

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

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

    Boolean - JavaScript - MDN Web Docs - Mozilla

  19. JavaScript Logical AND assignment (&&=) Operator

    This operator is represented by x &&= y, and it is called the logical AND assignment operator. It assigns the value of y into x only if x is a truthy value. We use this operator x &&= y like this. Now break this expression into two parts, x && (x = y). If the value of x is true, then the statement (x = y) executes, and the value of y gets ...

  20. JavaScript Operators and Operator Precedence

    Different categories of operators like arithmetic, logical and more; Operator precedence determines order of evaluation; Examples showed precedence dramatically affects results; We then covered specifics of the most popular operators used in JavaScript: Arithmetic operators for math calculations; Assignment operators to assign values

  21. Operator precedence

    Operator precedence - JavaScript - MDN Web Docs - Mozilla