• How it works
  • Homework answers

Physics help

Answer to Question #170269 in HTML/JavaScript Web Application for manikanta

Arithmetic Operations

Given a constructor function

ArithmeticOperations in the prefilled code and two numbers firstNumber and secondNumber as inputs, add the following methods to the constructor function using the prototype.MethodDescriptionratioOfNumbersIt Should return the ration of the numberssumOfCubesOfNumbersIt Should return the sum of cubes of the numbersproductOfSquaresOfNumbersIt Should return the product of squares of the numbers

  • The first line of input contains a number firstNumber
  • The second line of input contains a number secondNumber
  • The first line of output should contain the ratio of firstNumber and secondNumber
  • The second line of output should contain the sum of cubes of firstNumber and secondNumber
  • The third line of output should contain the product of squares of firstNumber and secondNumber

Constraints

secondNumber should not be equal to zero

Sample Input 1

Sample Output 1

Sample Input 2

Sample Output 2

i want code in between write code here

"use strict";

process.stdin.resume();

process.stdin.setEncoding("utf-8");

let inputString = "";

let currentLine = 0;

process.stdin.on("data", (inputStdin) => {

 inputString += inputStdin;

process.stdin.on("end", (_) => {

 inputString = inputString.trim().split("\n").map((str) => str.trim());

function readLine() {

 return inputString[currentLine++];

/* Please do not modify anything above this line */

function ArithmeticOperations(firstNumber, secondNumber) {

 this.firstNumber = firstNumber;

 this.secondNumber = secondNumber;

function main() {

 const firstNumber = JSON.parse(readLine());

 const secondNumber = JSON.parse(readLine());

 const operation1 = new ArithmeticOperations(firstNumber, secondNumber);

 /* Write your code here */

 console.log(operation1.ratioOfNumbers());

 console.log(operation1.sumOfCubesOfNumbers());

 console.log(operation1.productOfSquaresOfNumbers());

Need a fast expert's response?

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS !

Leave a comment

Ask your question, related questions.

  • 1. MobileYou are given an incomplete Mobile class.A Mobile object created using the Mobile class should
  • 2. Fare per KilometerGiven total fare fare and distance travelled in kilometers distance for a rental b
  • 3. Final Value with Appreciation Given principal amount principal as an input, time period in years
  • 4. Square at Alternate IndicesGiven an arraymyArray of numbers, write a function to square the alternat
  • 5. Objects with given FruitGiven an array of objects objectEntities in the prefilled code and fruit as
  • 6. Unite FamilyGiven three objects father, mother, and child, write a JS program to concatenate all the
  • 7. Update Pickup PointGiven a previous pickup point in the prefilled code, and updated pickup point are
  • Programming
  • Engineering

10 years of AssignmentExpert

Who Can Help Me with My Assignment

There are three certainties in this world: Death, Taxes and Homework Assignments. No matter where you study, and no matter…

How to finish assignment

How to Finish Assignments When You Can’t

Crunch time is coming, deadlines need to be met, essays need to be submitted, and tests should be studied for.…

Math Exams Study

How to Effectively Study for a Math Test

Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…

JS Tutorial

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

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

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

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

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.

TutorialsTonight Logo

JavaScript Arithmetic Operator

In this tutorial, you will learn about arithmetic operators in javascript with examples.

Arithmetic Operators

Arithmetic operators are the set of operators that performs mathematical operations on the operands like addition, subtraction, multiplication, division, etc.

Some of the arithmetic operators behave differently in different contexts. For example, the addition operator (+) adds 2 numbers but concatenate two strings.

There are the following arithmetic operators in javascript.

Let's discuss each operator and see their examples.

1. Addition operator

Addition operator is used to add two operands. To add operands use + symbol. for example 10 + 15 or we can add variable var a = 5, b = 1, c; c = a + b; .

Concatenating String using + operator

The same operation sign + can concatenate strings also, which means it can attaching two strings side by side. For example, var greeting = "Hello," + " World!" output is Hello, World! .

Adding Strings and numbers

Javascript behaves strangely sometimes. It can add number string (like '2', '4.5', '-10', etc) with actual number (Data type - Number) and give string value. For example, var a = 5 + '5' is a valid expression and gives a string result.

Output of adding number string and numbers depends on orientation of operators. Javascript adds all numbers first and when it comes first string then it starts concatenating all coming operands. For example 2 + '2' = "22" , 2 + 2 + '2' = "42" , 2 + 2 + '2' + 1 = "421" and so on.

2. Subtraction operator

Subtraction operator is used to subtract two operands. To subtract operands use - symbol. for example 10 - 15 or we can subtract variable var a = 5, b = 1, c; c = a - b; .

Subtracting numerical string

Unlike the addition operator which adds and concatenates both, the subtraction operator always subtracts.

3. Multiplication operator

The multiplication operator is used to multiply two operands. To multiply operands use the * symbol. for example 10 * 15 or we can multiply variable var a = 5, b = 1, c; c = a * b; .

4. Division operator

Division operator is used to divide two operands. To divide operands use / symbol. for example 10 / 15 or we can divide variable var a = 5, b = 1, c; c = a / b; .

5. Modulus operator

The modulus operator is used to find the remainder of the division. To find the remainder of the division uses the % symbol. for example 10 % 3 or we can find remainder of variable var a = 5, b = 1, c; c = a % b; .

6. Exponential operator

The exponential operator is used to raise one operand to the power of another. To raise operands use the ** symbol. for example 10 ** 2 or we can raise variable var a = 5, b = 1, c; c = a ** b; .

Javascript also has Math.pow(a,b) method to find exponentials.

7. Floor division operator

Floor division operator is used to find quotient of division. To find quotient of division use // symbol. for example 10 // 3 or we can find quotient of variable var a = 5, b = 1, c; c = a // b; .

Increment operator

Increment operator ++ is used to increase a number by 1.

Increment operator can be used in two ways:

  • pre-increment: When Increment operator is used before the operand. Example - ++a;
  • post-increment: When Increment operator is used after the operand. Example - a++;

Difference in pre-increment and post-increment : Both increase operand by 1 but pre-increment increase value before assigning value to the operand but post-increment increase value after assigning value to number. For example var a = 10; console.log(a++); // output 10 not 11 and var a = 10; console.log(++a); // output 11 .

Decrement operator

Decrement operator -- is used to decrease a number by 1.

Decrement operator can be used in two ways:

  • pre-decrement : When the decrement operator is used before the operand. Example - --a;
  • post-decrement : When decrement operator is used after the operand. Example - a--;

The difference in pre-decrement and post-decrement: Both decrease operand by 1 but pre-decrement decrease value before assigning value to the operand but post-decrement decrease value after assigning value to a number. For example var a = 10; console.log(a--); // output 10 not 9 and var a = 10; console.log(++a); // output 9 .

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

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

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

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

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

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

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

For example, 3+4 or x*y .

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

For example, x++ or ++x .

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

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

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

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

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

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

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

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

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

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

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

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

Bitwise shift operators

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

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

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

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

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

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

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

Short-circuit evaluation

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

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

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

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

For example,

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

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

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

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

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

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

A unary operation is an operation with only one operand.

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

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

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

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

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

Deleting array elements

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

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

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

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

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

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

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

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

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

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

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

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

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

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

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

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

Relational operators

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

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

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

The following examples show some uses of the in operator.

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

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

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

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

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

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

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

  • Expressions

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

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

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

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

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

Primary expressions

Basic keywords and general expressions in JavaScript.

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

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

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

  • Grouping operator

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

Comprehensions

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

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

Left values are the destination of an assignment.

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

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

Spread operator

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

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

Similarly, the spread operator works with function calls:

Document Tags and Contributors

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

JavaScript Operators

Enhance your JavaScript programming skills with this comprehensive chapter on operators. Learn how to use arithmetic, comparison, logical, and assignment operators to perform calculations, compare values, and assign values to variables. Suitable for beginners.

Updated: March 11, 2023

This YouTube channel is packed with awesome videos for coders!

Tons of videos teaching JavaScript and coding. Cool live streams!

Operators are a fundamental part of JavaScript programming. They allow you to perform various operations on data types, including arithmetic operations, logical operations, and comparison operations. In this chapter, we’ll dive deep into how operators work in JavaScript and explore some examples of how they can be used.

Arithmetic Operators

Arithmetic operators in JavaScript are used to perform mathematical calculations on numbers. Here are some examples:

In this example, the arithmetic operators +, -, *, /, and % are used to perform addition, subtraction, multiplication, division, and modulo operations on the numbers x and y.

Comparison Operators

Comparison operators in JavaScript are used to compare values and return a Boolean value (true or false). Here are some examples:

In this example, the comparison operators >, <, >=, <=, ==, and != are used to compare the values of x and y and return a Boolean value.

Logical Operators

Logical operators in JavaScript are used to combine multiple conditions and return a Boolean value (true or false). Here are some examples:

In this example, the logical operators && (and), || (or), and ! (not) are used to combine multiple conditions and return a Boolean value.

Assignment Operators

Assignment operators in JavaScript are used to assign values to variables. Here are some examples:

In this example, the assignment operators += and *= are used to assign values to variables x and y, respectively.

Operators are a powerful feature of JavaScript programming that can greatly enhance the flexibility and efficiency of your code. By understanding how to use arithmetic operators, comparison operators, logical operators, and assignment operators, you can take your programming skills to the next level and write more powerful and efficient code.

DEV Community

DEV Community

Arsalan Mlaik

Posted on Aug 20, 2023

JavaScript Operators: A Comprehensive Guide

JavaScript, being a versatile and widely-used programming language, provides a plethora of operators that empower developers to manipulate data, perform calculations, and make decisions. In this article, we will delve into the world of JavaScript operators, exploring their diverse types, functionalities, and practical examples.

Table of Contents

  • Introduction to JavaScript Operators
  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Unary Operators
  • Conditional (Ternary) Operator
  • Bitwise Operators
  • String Operators
  • Type Operators
  • Operator Precedence
  • Operator Overloading
  • Common Operator Mistakes to Avoid
  • Real-world Examples of Operator Usage
  • Frequently Asked Questions (FAQs)
  • Access Our JavaScript Resources

1. Introduction to JavaScript Operators

At the core of JavaScript lies a rich set of operators that facilitate tasks ranging from basic arithmetic calculations to advanced logical evaluations. Operators are symbols that allow you to perform operations on values and variables.

2. Arithmetic Operators

Arithmetic operators are essential for numeric computations. The plus (+) operator can not only add numbers but also concatenate strings. For instance:

3. Assignment Operators

Assignment operators help in assigning values to variables. The equal sign (=) is the most basic assignment operator. However, compound assignment operators combine operations with assignments. Here's an example:

4. Comparison Operators

Comparison operators are used to compare values. The equality (==) and strict equality (===) operators determine if values are equal. For instance:

5. Logical Operators

Logical operators are crucial for decision-making. The logical AND (&&) and logical OR (||) operators are used to combine conditions. Example:

6. Unary Operators

Unary operators work on a single value. The increment (++) and decrement (--) operators change the value by 1. Example:

7. Conditional (Ternary) Operator

The conditional operator is a concise way to write if-else statements. Example:

8. Bitwise Operators

Bitwise operators manipulate values at the bit level. The bitwise AND (&) and bitwise OR (|) operators perform binary operations. Example:

9. String Operators

String operators, like the concatenation operator (+), combine strings. Example:

10. Type Operators

Type operators provide insights into variable types. The typeof operator tells you the type of a value. Example:

11. Operator Precedence

Operator precedence determines the order in which operators are evaluated. Example:

12. Operator Overloading

JavaScript doesn't support true operator overloading, but operators might behave differently based on types.

13. Common Operator Mistakes

Avoid common mistakes, such as using the wrong operator or misunderstanding operator behavior, to ensure accurate code.

14. Real-world Examples

Explore practical examples of operators in action, from calculating discounts to validating user input.

15. Conclusion

JavaScript operators are indispensable tools that enable developers to manipulate data effectively and make informed decisions in their code. By mastering these operators, you unlock the potential to create dynamic and efficient applications.

Why are operators important in JavaScript? Operators enable developers to perform various tasks, from calculations to logical evaluations.

Can I use arithmetic operators with strings? Yes, JavaScript's loose typing allows using arithmetic operators with strings.

What's the difference between == and ===? The triple equals (===) checks both value and type, while double equals (==) checks value only.

How do logical operators work? Logical operators combine conditions and determine whether a given condition is true or false.

Is operator overloading possible in JavaScript? JavaScript doesn't support traditional operator overloading.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

balastrong profile image

Play 4 Multiplayer Games 🎮 on Github Profiles (README.md)

Leonardo Montini - May 14

opensourcee profile image

Deployment strategies: Canary or Blue-Green?

OpenSource - May 14

stephikebudu profile image

Flexbox vs Grid: How to Choose

Stephany Ikebudu - May 14

mattiamalonni profile image

How to validate Node + Express requests with Joi middleware

Mattia Malonni - May 14

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • JavaScript Assignment and Arithmetic Operators

JavaScript Assignment and Arithmetic Operators

In this JavaScript tutorial, we will learn all about the assignment and arithmetic operators that we can use when programming with JavaScript.

In short, with the arithmetic operators, we can perform arithmetic operations like addition, subtraction, multiplication, division, remainder, and exponentiation.

We use the assignment operators to assign values to variables.

Great documentations about JavaScript operators can be found here and here .

This is part of our Learn JavaScript series:

  • JavaScript Intro – How to See Your Code Output?
  • JavaScript Syntax, Statements, Variables, and Comments

Arithmetic Operators

We will start with the arithmetic operators. As stated in the introduction, these operators are used to perform arithmetic operations.

We create two initial variables and give each a numerical value:

So, x has the value 2 and y has the value 7. We will work with these values throughout this section.

We also create the variable z which is supposed to hold the resulting values:

We only need to declare the variables once with the keyword let . For the following examples, we can just reassign them to other values.

Now, we can perform the actual operations. We start with addition:

Addition Operator

We assign the variable z the addition of x and y . x and y are the operands and + is the operator.

We will now output z to see what value it has:

As we can see, we successfully added x and y since 2+7 is indeed 9.

Likewise, we can perform the other arithmetic operations like

Subtraction Operator

Multiplication operator, division operator.

So, the difference between these statements is the arithmetic operator. In addition, we use + , in subtraction, we use - , in multiplication, we use * , and in division, we use / .

There are two remaining arithmetic operators: exponentiation and remainder.

Exponentiation Operator

The exponentiation operator raises the first operand to the power of the second one:

So, we calculate 7 2 which is 49.

Remainder Operator

The last operator, the remainder operator, returns this value:

This operator is used to calculate the remaining value after a division.

The example says the following: 7 / 2 = 3 and the remainder is 1. So, the 2 fits into the 7 three whole times and there is 1 remaining. The remainder operation only outputs the remainder itself.

Maybe you have come across the remainder operator under its other term “ modu l o “.  

Increment and Decrement

For incrementing and decrementing, JavaScript provides us with the operators of the same name. But there is a difference between using them as prefixes or postfixes.

Let’s create a new variable x :

Now, we perform a postfix incrementation of x and assign this value to a newly created variable y :

Let’s see what value y has:

x has the following value:

So, with the postfix incrementation, y was not affected, but x was incremented by one.

Let’s do the same again, but this time with prefix incrementation:

We set x back to 5 and we perform a prefix incrementation of x and assign this value to y .

y now has this value:

And x has this value:

As we can see, y was also affected by the incrementation because with prefix incrementation the values for both x and y were incremented by 1.

Postfix Decrementation Operator

The same applies to decrementing. We start with postfix decrementation:

We set x back to 5 and we perform a postfix decrementation that we assign to y .

y has this value:

So, y was not affected.

Prefix Decrementation Operator

Whereas, with the prefix decrementation, it looks like this:

x is again set back to 5 and we perform a prefix decrementation that we set to y .

Thus, y is also affected by the prefix decrementation as was the case with prefix incrementation.

Assignment operators

We use assignment operators to assign values to variables.

Simple Assignment Operator

The equal sign = is known as the assignment operator :

Here, we create the variable a , and we assign it the numeric value 4.

Addition Assignment Operator

We can also use the assignment operator to add a value to a variable:

Here, we assign the variable a the new value which is the initial value plus 1. Let’s check what value a now has:

a has the value 5 because it was initially 4 and we added 1 to it.

The statement

is the same as

because we set the variable equal to the initial variable’s value and add 1.

Subtraction Assignment Operator

With subtraction, it looks like similar:

First, we set a back to 4. Then we subtract 1 from a and assign the new value to a . Then we output the value of a which is 3. And as with addition, the statement

Multiplication Assignment Operator

Multiplication looks like this:

Again, we set a back to the value 4. Then, we multiply a by 2 and add the new value to a . Next, we output the new value of a and we can see that it is now 8.

Division Assignment Operator

Division also works like this:

After setting a back to 4, we divide it by 2 and assign the new value to a . The output shows that we did this successfully as we get 2 as the output which is the result of dividing 4 by 2.

Remainder Assignment Operator

We do the same with the remainder:

We set a back to 4 and then we calculate the remainder of dividing 4 by 2 and set this value to a .

Since 2 fits into 4 two times and there is no remaining value, a has the value 0 which is confirmed by outputting a.

Exponentiation Assignment Operator

The exponentiation assignment works the same way:

a is set back to 4. Afterward, we calculate 4 to the power of 3 and assign the new value to the variable a . The output is 64 because 4 3 equals 64.

The remaining assignment operators are a bit different from the ones we have seen by now.

Left-Shift Assignment Operator

We will start with the left shift assignment:

So, what is happening here? We set the variable a that we already declared to the value 5. Then we perform the left shift. In this case, we move the bits 2 to the left and assign the new value to our variable a .

The 2-bit representation of the number 5 is 00101 because 1*2 2 + 1*2 0 = 5.

And we shift these bits 2 to the left, so now we have got this 2-bit number: 10100 which is 1*2 4 + 1*2 2 = 20.

Right-Shift Assignment Operator

Similarly, we can perform a right shift assignment:

We set a to 9. Then, we perform the right shift assignment where we shift the bits 2 to the right. The 2-bit representation of 9 is: 01001.

When we shift the bits 2 to the right, we get 00010 which is 2. The other 1 is outside the scope and is therefore not taken into account.

The remaining assignment operators are bitwise assignment operators.

Bitwise AND Assignment Operator

The first one is the bitwise AND assignment operator:

a is set to 5. Then we perform a bitwise and operation of 5 and 2 and the result is then set as the new value for a . The output value of a is 0.

The 2-bit representation of 5 is 00101 and the 2-bit representation of 2 is 00010. When we put these 2-bit numbers above each other and perform a bitwise and operation, we get 00000 which is 0.

Bitwise OR Assignment Operator

Likewise, we do the same for the bitwise OR assignment operation.

We set a back to 5 again and then we perform a bitwise or operation of 5 and 4 and the result is assigned to a . The result is 5.

The 2-bit representation of 5 is 00101 and the 2-bit representation of 4 is 00100. When we put these 2-bit numbers above each other and perform a bitwise OR operation, we get 00101 which is 5.

Bitwise XOR Assignment Operator

There is also a bitwise XOR assignment operation:

a is set back to 5 again. Then we perform the bitwise XOR operation of 5 and 4 and we assign the result to a .

The result of a bitwise xor operation of 5 and 4 is binary 00001 which is decimal 1.

In this tutorial, we learned all about JavaScript’s assignment and arithmetic operators. We learned how to perform different kinds of arithmetic operations, and how to assign values in different ways.

If you wish to learn more about JavaScript, stay tuned for the other tutorials that are being released to Finxter.

And for more tutorials about other computer and data science-related topics, check out the Finxter email academy !

Happy Coding!

Hi! I’m Luis, an Information Systems student and freelance writer and programmer from Germany. I love coding and creating educational content about computer science. For the articles I’m writing, I combine the knowledge I gained at the university with the insights I get from constantly reading and learning about new technologies. Making education more accessible for everyone is my passion and I hope you like the content I’m creating!

Arithmetic Operators in

About arithmetic operators, arithmetic operators.

JavaScript provides 6 different operators to perform basic arithmetic operations on numbers.

+ : The addition operator is used to find the sum of numbers.

- : The subtraction operator is used to find the difference between two numbers

* : The multiplication operator is used to find the product of two numbers

/ : The division operator is used to divide two numbers. Since JavaScript numbers are always floating-point numbers, there is no integer division.

% : The remainder operator is used to find the remainder of a division performed.

** : The exponentiation operator is used to raise a number to a power. It is the equivalent of using Math.pow()

Order of Operations

When using multiple operators in a line, JavaScript follows an order of precedence as shown in this precedence table . To simplify it to our context, JavaScript uses the PEDMAS (Parentheses, Exponents, Division/Multiplication, Addition/Subtraction) rule we've learnt in elementary math classes.

Shorthand Assignment Operators

Shorthand assignment operators are a shorter way of writing code conducting arithmetic operations on a variable, and assigning the new value to the same variable. For example, consider two variables x and y . Then, x += y is same as x = x + y . Often, this is used with a number instead of a variable y . The 5 other operations can also be conducted in a similar style.

Learn Arithmetic Operators

Popular Articles

  • Jsx: Markup Expressions In Javascript (May 04, 2024)
  • The Tostring() Method (Apr 22, 2024)
  • Understanding The Reflect Api In Javascript (Apr 22, 2024)
  • Proxy Invariants And Usage Guidelines (Apr 22, 2024)
  • Methods For Performing Meta-Level Operations On Objects (Apr 22, 2024)

Javascript Operators

Javascript Operators

Switch to English

Table of Contents

Introduction

Types of javascript operators, arithmetic operators, assignment operators, comparison operators, logical operators, bitwise operators, unary operators, ternary operator, tips and common pitfalls.

Javascript Operators are an integral part of the Javascript programming language. They enable developers to perform operations on variables and values. These operations include arithmetic, comparison, logical, assignment, and more. Understanding Javascript operators is essential for manipulating data and making decisions in your code.

Javascript operators can be categorized into several types:

Arithmetic operators are used to perform mathematical operations like addition (+), subtraction (-), multiplication (*), and division (/). They also include the modulus operator (%) which returns the remainder of a division and increment (++) and decrement (--) operators.

Assignment operators are used to assign values to variables.

Comparison operators are used to compare two values and return a boolean value (true or false) depending on the result of the comparison.

Logical operators are used to combine multiple conditions. They include AND (&&), OR (||), and NOT (!).

Bitwise operators work directly on the binary representations of numbers.

Unary operators operate on a single operand. Examples include typeof, delete, and void.

The ternary operator, also known as the conditional operator, is the only operator in Javascript that takes three operands. It is a shortcut for the if-else statement.

  • Remember that the assignment operator (=) and the equality operator (==) are different. The former assigns a value to a variable while the latter compares two values.
  • When comparing values, it's generally safer to use the strict equality operator (===) as it also checks the type of the values, avoiding unintended truthy or falsy comparisons.
  • The unary plus (+) operator can be used to convert a string to a number. However, if the string does not represent a valid number, the result will be NaN.
  • When using bitwise operators, be aware that they work directly on the 32-bit binary representations of numbers. Therefore, they might produce unexpected results for non-integer or large numbers.
  • In conclusion, operators are fundamental to any programming language and Javascript is no exception. Understanding how to use these operators effectively can greatly enhance your coding skills and help you write more efficient and cleaner code.
  • Skip to primary navigation
  • Skip to content

Call us +1 415 416 0800

Metana

  • Solidity Bootcamp Hot 🔥

Web3 Solidity Bootcamp

The most advanced Solidity curriculum on the internet

Full Stack Web3 Beginner Bootcamp

Starting off with web development and seamlessly integrating web3 development

Web3 Rust Bootcamp

Become an expert Solana blockchain developer with one course!

Coding + Career Growth

Software engineering bootcamp.

Become a Software Engineer - Balance everyday life commitments & launch your coding career in as little as 16 weeks

Metana's JobCamp™️

Learn to make a lasting first impressions, network effectively & search for jobs with confidence.

arithmetic operations in javascript assignment expert

Rated the Best

Ranked as the industry's premier Web3 bootcamp with a stellar 4.8/5 star rating on Course Report.

  • Metana’s Job Guarantee

Metana Bootcamps

  • Full Stack Web3 Bootcamp
  • Rust Bootcamp
  • Cybersecurity Bootcamp
  • AI & Machine Learning Bootcamp
  • Data Analytics Bootcamp
  • Data Science Bootcamp
  • Full Stack Bootcamp
  • Refer a Friend
  • Withdrawal and Refund Policy

[email protected]

Table of Contents

Javascript operators, metana editorial.

  • April 8, 2024

JavaScript operators are the building blocks that bring your code to life. They perform actions on values, compare data, control program flow, and manipulate data structures. Understanding these operators is fundamental to mastering JavaScript and creating dynamic and interactive web experiences. This comprehensive guide delves into the various types of JS operators, their functionalities, and how to use them effectively in your code.

What are the Types of Javascript Operators ?

JavaScript boasts a rich set of operators, each with a specific purpose. Let’s explore the most commonly used categories:

01. Assignment Operators

These operators assign values to variables. The most basic is the single equal sign ( = ), which assigns the value on the right to the variable on the left. For example:

JavaScript also offers compound assignment operators that perform an operation and then assign the result. These include:

  • += : Adds and assigns (e.g., age += 5 is equivalent to age = age + 5 )
  • = : Subtracts and assigns
  • = : Multiplies and assigns
  • /= : Divides and assigns
  • %= : Computes the remainder and assigns

02. Arithmetic Operators

These operators perform mathematical calculations on numbers.

  • + : Addition (e.g., 10 + 5 evaluates to 15)
  • - : Subtraction (e.g., 20 - 3 evaluates to 17)
  • * : Multiplication (e.g., 4 * 6 evaluates to 24)
  • / : Division (e.g., 30 / 2 evaluates to 15)
  • % : Modulus (remainder after division) (e.g., 11 % 3 evaluates to 2)
  • * : Exponentiation (raising a number to a power) (e.g., 2 ** 3 evaluates to 8)

03. Comparison Operators

These operators compare values and return a boolean (true or false) result. They include:

  • == : Loose equality (checks for equal value, can perform type coercion) (e.g., 1 == "1" evaluates to true)
  • === : Strict equality (checks for equal value and type) (e.g., 1 === "1" evaluates to false)
  • != : Not equal (opposite of == )
  • !== : Strict not equal (opposite of === )
  • < : Less than
  • <= : Less than or equal to
  • > : Greater than
  • >= : Greater than or equal to

04. Logical Operators

These operators combine boolean expressions to create more complex logical conditions.

  • && : AND operator (both operands must be true for the result to be true) (e.g., (age > 18) && (isCitizen === true) evaluates to true if age is greater than 18 and isCitizen is true)
  • || : OR operator (at least one operand must be true for the result to be true) (e.g., (loggedIn === true) || (hasAdminRights === true) evaluates to true if either loggedIn or hasAdminRights is true)
  • ! : NOT operator (inverts the boolean value) (e.g., !(age < 13) evaluates to true if age is not less than 13).

05. Conditional (Ternary) Operator

This operator provides a concise way to write an if-else statement in a single line. The syntax is:

For example:

06. Type Operators

These operators check the data type of a value. The most common ones are:

  • typeof : Returns the data type of a value (e.g., typeof(10) evaluates to “number”)
  • instanceof : Checks if an object is an instance of a specific constructor (e.g., object instanceof Array checks if the object is an array)

07. Bitwise Operators

These operators perform bit-level operations on numbers. They are less commonly used in everyday JavaScript but can be helpful for low-level manipulation. Some examples include:

  • & : Bitwise AND
  • | : Bitwise OR
  • ^ : Bitwise XOR
  • << : Left shift
  • >> : Right shift
  • ~ : Bitwise NOT

javascript operators

08. String Operators

JavaScript primarily uses the + operator for string concatenation. However, there are a few nuances:

  • +: When used with strings, it concatenates them (e.g., "Hello" + " World" evaluates to “Hello World”)
  • When used with at least one numeric operand, it converts the other operand to a string and then concatenates (e.g., "Age: " + age evaluates to a string like “Age: 25” if age is 25)

09. Increment and Decrement Operators

These operators are used to increment (increase) or decrement (decrease) the value of a variable by 1. They come in two forms:

  • Pre-increment ( ++x ): Increments the value and then returns the new value (e.g., let count = 5; count++ evaluates to 5 but increments count to 6)
  • Post-increment ( x++ ): Returns the current value and then increments (e.g., let count = 5; let oldCount = count++ assigns 5 to oldCount and then increments count to 6)

Decrement operators ( --x and x-- ) work similarly.

10. Comma Operator

This operator allows you to group multiple expressions into a single statement. However, only the rightmost expression’s value is returned. It’s often used for side effects (actions that don’t necessarily return a value). For example:

11. Special Operators

JavaScript offers a few special operators for specific functionalities:

  • delete : Deletes a property from an object
  • void : Evaluates an expression but discards the result (often used for side effects)
  • in : Checks if a property exists in an object

Let’s Take a Look at Some Examples

Now that you’ve explored the different types of operators, let’s delve into some practical examples to solidify your understanding:

Example 1: Using Arithmetic Operators

Example 2: utilizing comparison operators with logical operators, example 3: conditional (ternary) operator in action, example 4: string concatenation with the plus operator, example 5: incrementing a counter variable, advanced operator usage.

As you become more proficient in JavaScript, you can explore advanced operator usage scenarios:

  • Operator Precedence: Understand the order in which operators are evaluated within an expression. Use parentheses to control the order if needed.
  • Type Coercion: Be aware of how JavaScript implicitly converts values from one type to another during operations. This can sometimes lead to unexpected results.
  • Bitwise Operators for Complex Manipulations: While less common, bitwise operators can be powerful for low-level bit manipulation tasks.

By mastering JavaScript operators, you unlock the true potential of the language. From performing calculations to manipulating data and controlling program flow, operators are the foundation upon which all JavaScript programs are built. This comprehensive guide has equipped you with the knowledge of various operators, their functionalities, and practical examples. Remember, consistent practice and exploration are key to solidifying your understanding.

faq

What are JavaScript operators?

  • JavaScript operators are symbols or keywords used to perform operations on variables and values, like addition, comparison, or logical operations.

How do JavaScript arithmetic operators work?

  • Arithmetic operators in JavaScript perform basic mathematical operations like addition (+), subtraction (-), multiplication (*), and division (/), among others.

What is the purpose of comparison operators in JavaScript?

  • Comparison operators compare two values and return a boolean value (true or false) depending on the outcome of the comparison, such as equal to (==) or greater than (>).

What are logical operators in JavaScript?

  • Logical operators are used to determine the logic between variables or values, including AND (&&), OR (||), and NOT (!), helping in decision-making in code.

How do assignment operators function in JavaScript?

  • Assignment operators assign values to JavaScript variables. The basic assignment operator is =, but there are others like += and -= that combine assignment with arithmetic operations.

What is JavaScript used for in web development?

  • JavaScript is primarily used to create dynamic and interactive web content, enabling functionalities like form validation, animations, and event handling on web pages.

How can I start learning JavaScript ?

  • Start with the basics of syntax and operators, practice simple programs, and progressively move to more complex topics. Online tutorials, courses, and coding communities can be great resources.

What are the benefits of understanding JavaScript operators?

  • Knowing JavaScript operators is crucial for writing efficient and effective code, enabling developers to implement complex logic and algorithms in web development.

How does JavaScript interact with HTML and CSS?

  • JavaScript interacts with HTML and CSS to manipulate web page content and styles dynamically, allowing for interactive and responsive design.

Are JavaScript operators similar to operators in other programming languages?

  • Many JavaScript operators are similar to those in other languages , but it’s important to understand the nuances and specific behaviors in JavaScript’s context.

arithmetic operations in javascript assignment expert

Metana Guarantees a Job 💼

Plus risk free 2-week refund policy ✨.

You’re guaranteed a new job in web3—or you’ll get a full tuition refund. We also offer a hassle-free two-week refund policy. If you’re not satisfied with your purchase for any reason, you can request a refund, no questions asked.

The most advanced Solidity curriculum on the internet!

  • Prior coding experience required
  • 1-on-1 mentorship
  • Expert code reviews
  • Coaching & career services

Learn foundational principles while gaining hands-on experience with Ethereum, DeFi, and Solidity.

  • Beginner - Zero to Hero
  • Your very own personal support tutor

You may also like

arithmetic operations in javascript assignment expert

Understanding the Document Object Model (DOM) in JavaScript

arithmetic operations in javascript assignment expert

Ethereum Gas Station Network (GSN)

Plus risk free 2-week refund policy, events by metana.

Dive into the exciting world of Web3 with us as we explore cutting-edge technical topics, provide valuable insights into the job market landscape, and offer guidance on securing lucrative positions in Web3.

Start Your Application

Secure your spot now. Spots are limited, and we accept qualified applicants on a first come, first served basis..

The application is free and takes just 3 minutes to complete.

What is included in the course?

Expert-curated curriculum, weekly 1:1 video calls with your mentor, weekly group mentoring calls, on-demand mentor support, portfolio reviews by design hiring managers, resume & linkedin profile reviews, active online student community, 1:1 and group career coaching calls, access to our employer network, job guarantee.

Adding {{itemName}} to cart

Added {{itemName}} to cart

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Arithmetic Operators in JavaScript.

    arithmetic operations in javascript assignment expert

  2. JavaScript Arithmetic Operators Example

    arithmetic operations in javascript assignment expert

  3. What is the operation in javascript?

    arithmetic operations in javascript assignment expert

  4. Arithmetic Operators in JavaScript

    arithmetic operations in javascript assignment expert

  5. #10 Javascript arithmetic operations

    arithmetic operations in javascript assignment expert

  6. JavaScript Tutorial #8

    arithmetic operations in javascript assignment expert

VIDEO

  1. JavaScript Arithmetic Operator Tamil

  2. Javascript arithmetic addition

  3. JavaScript Exponentiation Assignment #coding #javascript #tutorial #shorts

  4. JavaScript Arithmetic operators precedence #shorts #javascript #arithmetic #operator #precedence

  5. Arithmetic operators

  6. Arithmetic Operations Program ||

COMMENTS

  1. Answer in Web Application for manikanta #170269

    Arithmetic Operations Given a constructor function ArithmeticOperations in the prefilled code and two ... Be sure that math assignments completed by our experts will be error-free and done according to your instructions specified in the submitted order form. ... Programming. Answer to Question #170269 in HTML/JavaScript Web Application for ...

  2. JavaScript Assignment Operators

    Assignment Operators. Assignment operators are used to assign values to variables in JavaScript. Syntax: data=value. Example: // Lets take some variablesx=10y=20x=y // Here, x is equal to 20y=x // Here, y is equal to 10.

  3. JavaScript Arithmetic

    As in traditional school mathematics, the multiplication is done first. Multiplication ( *) and division ( /) have higher precedence than addition ( +) and subtraction ( - ). And (as in school mathematics) the precedence can be changed by using parentheses. When using parentheses, the operations inside the parentheses are computed first:

  4. JavaScript Arithmetic Operators

    Examples of JavaScript Arithmetic Operators. Addition (+) The addition operator takes two numerical operands and gives their numerical sum. It also concatenates two strings or numbers. Example: In this example we are adding two numbers performs addition, while adding a number and a string results in concatenation.

  5. Javascript Assignment Operators (with Examples)

    Addition assignment operator. The addition assignment operator += is used to add the value of the right operand to the value of the left operand and assigns the result to the left operand. On the basis of the data type of variable, the addition assignment operator may add or concatenate the variables.

  6. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  7. Assignment (=)

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

  8. Javascript Arithmetic Operators (with Examples)

    Arithmetic Operators. Arithmetic operators are the set of operators that performs mathematical operations on the operands like addition, subtraction, multiplication, division, etc. Some of the arithmetic operators behave differently in different contexts. For example, the addition operator (+) adds 2 numbers but concatenate two strings. There ...

  9. Basic math in JavaScript

    Basic math in JavaScript — numbers and operators. Article Actions. ... Change the line that calculates x so the box is 200px wide, but the 200 is calculated using the number 4 and an assignment operator. Change the line that calculates y so the box is 200px high, but the 200 is calculated using the numbers 50 and 3, the multiplication ...

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

  11. Expressions and operators

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

  12. Expressions and operators

    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 = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

  13. JavaScript Operators

    Operators are a powerful feature of JavaScript programming that can greatly enhance the flexibility and efficiency of your code. By understanding how to use arithmetic operators, comparison operators, logical operators, and assignment operators, you can take your programming skills to the next level and write more powerful and efficient code.

  14. JavaScript Operators: A Comprehensive Guide

    At the core of JavaScript lies a rich set of operators that facilitate tasks ranging from basic arithmetic calculations to advanced logical evaluations. Operators are symbols that allow you to perform operations on values and variables. 2. Arithmetic Operators. Arithmetic operators are essential for numeric computations.

  15. JavaScript Assignment and Arithmetic Operators

    The first one is the bitwise AND assignment operator: a = 5; a &= 2; console.log(a); // 0. a is set to 5. Then we perform a bitwise and operation of 5 and 2 and the result is then set as the new value for a. The output value of a is 0. The 2-bit representation of 5 is 00101 and the 2-bit representation of 2 is 00010.

  16. Arithmetic Operators in JavaScript on Exercism

    Shorthand assignment operators are a shorter way of writing code conducting arithmetic operations on a variable, and assigning the new value to the same variable. For example, consider two variables x and y. Then, x += y is same as x = x + y. Often, this is used with a number instead of a variable y. The 5 other operations can also be conducted ...

  17. How To Do Math in JavaScript with Operators

    In addition to the standard assignment operator, JavaScript has compound assignment operators, which combine an arithmetic operator with =. For example, the addition operator will start with the original value, and add a new value. // Assign 27 to age variable let age = 27; age += 3; console.log(age); Output.

  18. Assignment Operators in JavaScript

    The sign = denotes the simple assignment operator. JavaScript also has several compound assignment operators, which is actually shorthand for other operators. A list of all such operators are listed below.

  19. Comprehensive Guide to Javascript Operators

    Javascript Operators are an integral part of the Javascript programming language. They enable developers to perform operations on variables and values. These operations include arithmetic, comparison, logical, assignment, and more. Understanding Javascript operators is essential for manipulating data and making decisions in your code.

  20. JavaScript Arithmetic Operators

    The JavaScript Arithmetic Operators include operators like Addition, Subtraction, Multiplication, Division, and Modulus. All these operators are binary operators, which means they operate on two operands. The below table shows the Arithmetic Operators with examples. 10 % 2 = 0 (Here remainder is zero).

  21. JavaScript Arithmetic Operators

    Identify the components in a JavaScript arithmetic statement, including the assignment symbol, the operator, and the operands. Demonstrate addition and subtraction using JavaScript code with the addition and subtraction operators. Demonstrate multiplication and division using JavaScript code with the multiplication, division, and modulus operators.

  22. JavaScript W3

    Study with Quizlet and memorize flashcards containing terms like JavaScript Arithmetic Operators, The numbers (in an arithmetic operation) are called, The operation (to be performed between the two operands) is defined by: and more.

  23. Javascript Operators

    The basic assignment operator is =, but there are others like += and -= that combine assignment with arithmetic operations. What is JavaScript used for in web development? JavaScript is primarily used to create dynamic and interactive web content, enabling functionalities like form validation, animations, and event handling on web pages.

  24. Python Operators

    In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /, etc.