Computer Science

Javascript Operators

JavaScript operators are symbols used to perform operations on variables and values. They can be used for arithmetic, comparison, logical, assignment, and more. Examples of operators include + for addition, - for subtraction, and === for strict equality comparison. Understanding and using operators is fundamental for writing efficient and functional JavaScript code.

Written by Perlego with AI-assistance

7 Key excerpts on "Javascript Operators"

  • Book cover image for: Clean Code in JavaScript
    eBook - ePub

    Clean Code in JavaScript

    Develop reliable, maintainable, and robust JavaScript

    dynamic typing , we explored topics such as type-coercion and detection; we also covered several operators. In this chapter, we'll continue this exploration by delving into every single operator that the JavaScript language makes available. Having a rich understanding of JavaScript's operators will make us feel utterly empowered in a language that can, at times, appear confusing. There is, unfortunately, no shortcut to understanding JavaScript, but as you begin to explore its operators, you will see patterns emerge. For example, many of the multiplicative operators work in a similar manner, as do the logical operators. Once you are comfortable with the main operators, you will begin to see that there is a grace underlying the complexity.
    It may be useful to treat this chapter as more of a reference if you're pressed for time. Do not feel like you need to exhaustively retain every detail of every operator's behavior. In this chapter, we will cover the following topics:
    • What is an operator?
    • Arithmetic and numeric operators
    • Logical operators
    • Comparative operators
    • Assignment operators
    • Property access operators
    • Other operators and syntax
    • Bitwise operators
    Now that we're ready to dive in, the very first question we need to ask ourselves is: what even is an operator?
    Passage contains an image

    What is an operator?

    An operator in JavaScript is a standalone piece of syntax that forms an expression and is typically used to derive something or compute a logical or mathematical output from a set of inputs (called operands ).
    Here, we can see an expression containing an operator (+) with two operands (3 and 5): 3 + 5 Any operator can be said to have four characteristics:
    • Its arity : how many operands the operator accepts
    • Its function : what the operator does with its operands and what it evaluates to
    • Its precedence : how the operator will be grouped when used in combination with other operators
    • Its associativity : how the operator will behave when neighbored with operators of the same precedence
    It's important to understand these foundational characteristics as it will vastly aid your usage of operators in JavaScript.
    Passage contains an image

    Operator arity

    Arity refers to how many operands (or inputs
    ) an operator can receive. An operand is a formal term for the value(s) that you can
    give or pass to an operator.
    If we consider the greater-than operator (>), it receives two operands: a > b
    In this example, a is its first operand (or left-side operand). And b
  • Book cover image for: JavaScript for Web Warriors
    • Patrick Carey, Sasha Vodnik, Patrick Carey(Authors)
    • 2021(Publication Date)
    CHAPTER 2 WORKING WITH FUNCTIONS, DATA TYPES, AND OPERATORS 52 Javascript Operators are binary or unary. A binary operator requires an operand before and after the operator. The equal sign in the statement myNumber = 100; is an example of a binary operator. A unary operator requires just a single operand either before or after the operator. For example, the increment operator (++), an arithmetic operator, is used to increase an operand by a value of one. The statement myNumber++; changes the value of the myNumber variable to 101. Another type of JavaScript operator, bitwise operators, operate on integer values; this is a fairly complex topic. Bitwise operators and other complex operators are beyond the scope of this book. Note The operand to the left of an operator is known as the left operand, and the operand to the right of an operator is known as the right operand. Note Arithmetic Operators Arithmetic operators are used in JavaScript to perform mathematical calculations, such as addition, subtraction, mul- tiplication, and division. You can also use an arithmetic operator to return the modulus of a calculation, which is the remainder left when you divide one number by another number. Figure 2-8 describes the arithmetic operators supported by JavaScript. You might be confused by the difference between the division ( / ) operator and the modulus (%) operator. The division operator performs a standard mathematical division operation so that the expression 15/6 returns a value of 2.5. The modulus operator returns the remainder after a division so that the expression 15%6 returns a value of 3 because that is the remainder when 15 is divided by 6. Arithmetic operations can also be performed on a single variable using unary operators. Figure 2-9 lists the arithmetic unary operators available in JavaScript.
  • Book cover image for: Customizing Vendor Systems for Better User Experiences
    eBook - PDF
    But JavaScript also allows for other mathematical operators: • - for subtraction • * for multiplication • / for division In addition, there are other numeric operators that can be useful. For instance, ++ is used to increment a JavaScript number variable by one, and -- is used to decrement a number variable by one. These can come in handy when running function over a large set of data, like we will do with loops in Chapter 6. If you need to keep track of how many times the loop has run, you can set a variable to increment each time the loop runs, like this: for(i = 0; i < 10; i++) { // Do something } Here the for() loop first sets a variable called i to the numeric value of 0. It then runs the statements inside of the loop as long as the second statement JavaScript Basics 33 is true. As long as i continues to be less than 10, the loop will run. Finally, the last statement increments the value of i by one each time the loop runs. Instead of writing i = i + 1, we can just write i++. Assignment Operators We’ve also seen at least one operator for assigning a value to a JavaScript var- iable: the =. If we want to set the value of the variable myVariable to the phrase “Seashells by the sea shore,” we can use the = to do that: var myVariable = "Seashells by the sea shore"; One useful assignment operator that we will also use is the += variable. This operator assigns the value of a variable to whatever the existing value is plus the new value. In the case of numeric variables, this will be the same as using the addition operator. But in the case of strings, this will concatenate the strings for you. For instance: // Numeric variables var myVariable = 5; myVariable += 15; // Returns 20 // String variables var myVariable = "Today is "; myVariable += "Sunday"; // Returns "Today is Sunday" Comparison Operators Comparison operators are used to compare two values.
  • Book cover image for: Beginning HTML and CSS
    • Rob Larsen(Author)
    • 2013(Publication Date)
    • Wrox
      (Publisher)
    The symbol is used in an expression with either one or two values and performs a calculation on the values to generate a result. For example, here is an expression that uses the multiplication operator:
    var area = (width * height);
    An expression is just like a mathematical expression. The values are known as operands . Operators that require only one operand (or value) are sometimes referred to as unary operators , whereas those that require two values are sometimes called binary operators .
    The different types of operators you see in this section are
    • Arithmetic
    • Assignment
    • Comparison
    • Logical
    • String
    You see lots of examples of the operators in action both later in this chapter and in the next two chapters. First, however, it’s time to learn about each type of operator.

    Arithmetic Operators

    Arithmetic operators perform arithmetic operations upon operands. (Note that in the examples in Table 10-2 , x = 10.)
    Table 10-2:
    JavaScript’s Arithmetic Operators

    Assignment Operators

    The basic assignment operator is the equal sign, but do not take this to mean that it checks whether two values are equal. Rather, it’s used to assign a value to the variable on the left of the equal sign, as you saw in the previous section, which introduced variables.
    The basic assignment operator can be combined with several other operators to allow you to assign a value to a variable and perform an operation in one step. For example, look at the following statement where there is an assignment operator and an arithmetic operator:
    total = total - profit; This can be reduced to the following statement: total -= profit;
    Although it might not look like much, this kind of shorthand can save a lot of code if you have many calculations like this to perform (see Table 10-3
  • Book cover image for: JavaScript All-in-One For Dummies
    • Chris Minnick(Author)
    • 2023(Publication Date)
    • For Dummies
      (Publisher)
    Working with Operators and Expressions CHAPTER 4 Working with Operators and Expressions 85 x = (4-5-2) / (2*2); The result of this statement is -3 / 4, or -.75. Assignment operators The assignment operator assigns a value to the operand on the left based on the operand on the right: x = 10; You can also chain together assignment operators. For example: x = y = z = 0; Remember that the associativity of the assignment operator is from right to left. So, the way JavaScript executes this expression is by assigning 0 to z, and then the value of z to y, and then the value of y to x. In the end, all three variables are 0. Comparison operators The comparison operators test for equality of the left and right operands, and return a Boolean (true or false) value. Table 4-1 shows the complete list of com- parison operators. TABLE 4-1 JavaScript Comparison Operators Operator Description Example == Equality 3 == “3” // true != Inequality 3 != 3 // false === Strict equality 3 === “3” // false !== Strict inequality 3 !== “3” // true > Greater than 7 > 1 // true >= Greater than or equal to 7 >= 7 // true < Less than 7 < 10 // true <= Less than or equal to 2 <= 2 // true 86 BOOK 1 JavaScript Fundamentals The equality and inequality operators (== and !=, respectively) only compare the values of the left and right operands. When possible, they change the type of the operand on the right to match the operand on the left. This behavior is, from the standpoint of JavaScript, a friendly thing to do. However, it results in some strange behaviors that can cause bugs in programs. For example, using the equality operator, the following statement evaluates to true: 0 == "0" In reality, the number 0 is not the same as a string containing a 0. Relying on JavaScript to automatically convert a string (for example, from a form input) to a number might not break your program, but it’s considered bad coding practice to use a string where you mean to use a number (or vice versa).
  • Book cover image for: JavaScript from Beginner to Professional
    eBook - ePub

    JavaScript from Beginner to Professional

    Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages

    • Laurence Lars Svekis, Maaike van Putten, Rob Percival, Laurence Svekis, Codestars By Rob Percival(Authors)
    • 2021(Publication Date)
    • Packt Publishing
      (Publisher)
    After seeing quite a few data types and some ways to convert them, it is time for the next major building block: operators. These come in handy whenever we want to work with the variables, modify them, perform calculations on them, and compare them. They are called operators because we use them to operate on our variables.

    Arithmetic operators

    Arithmetic operators can be used to perform operations with numbers. Most of these operations will feel very natural to you because they are the basic mathematics you will have come across earlier in life already.

    Addition

    Addition in JavaScript is very simple, we have seen it already. We use + for this operation:
    let nr1 = 12 ; let nr2 = 14 ; let result1 = nr1 + nr2;
    However, this operator can also come in very handy for concatenating strings. Note the added space after "Hello" to ensure the end result contains space characters:
    let str1 = "Hello " ; let str2 = "addition" ; let result2 = str1 + str2;
    The output of printing result1 and result2 will be as follows:
    26 Hello addition As you can see, adding numbers and strings lead to different results. If we add two different strings, it will concatenate them into a single string.
    Practice exercise 2.2
    Create a variable for your name, another one for your age, and another one for whether you can code JavaScript or not.
    Log to the console the following sentence, where name , age and true /false are variables:
    Hello, my name is Maaike, I am 29 years old and I can code JavaScript: true.

    Subtraction

    Subtraction works as we would expect it as well. We use - for this operation. What do you think gets stored in the variable in this second example?
    let nr1 = 20 ; let nr2 = 4 ; let str1 = "Hi" ; let nr3 = 3 ; let result1 = nr1 - nr2; let result2 = str1 - nr3; console .log(result1, result2);
    The output is as follows: 16 NaN
    The first result is 16 . And the second result is more interesting. It gives NaN , not an error, but just simply the conclusion that a word and a number subtracted is not a number. Thanks for not crashing, JavaScript!

    Multiplication

    We can multiply two numeric values with the *
  • Book cover image for: Professional JavaScript for Web Developers
    • Matt Frisbie(Author)
    • 2019(Publication Date)
    • Wrox
      (Publisher)
    The core language features of JavaScript are defined in ECMA-262 as a pseudolanguage named ECMAScript. ECMAScript contains all of the basic syntax, operators, data types, and objects necessary to complete basic computing tasks, though it provides no way to get input or to produce output. Understanding ECMAScript and its intricacies is vital to a complete understanding of JavaScript as implemented in web browsers. The following are some of the basic elements of ECMAScript:
    • The basic data types in ECMAScript are Undefined, Null, Boolean, Number, String, and Symbol.
    • Unlike other languages, there's no separate data type for integers versus floating-point values; the Number type represents all numbers.
    • There is also a complex data type, Object, that is the base type for all objects in the language.
    • A strict mode places restrictions on certain error-prone parts of the language.
    • ECMAScript provides a lot of the basic operators available in C and other C-like languages, including arithmetic operators, Boolean operators, relational operators, equality operators, and assignment operators.
    • The language features flow-control statements borrowed heavily from other languages, such as the if statement, the for statement, and the switch statement.
    Functions in ECMAScript behave differently than functions in other languages:
    • There is no need to specify the return value of the function because any function can return any value at any time.
    • Functions that don't specify a return value actually return the special value undefined
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.