Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Clean Code in JavaScript

You're reading from  Clean Code in JavaScript

Product type Book
Published in Jan 2020
Publisher Packt
ISBN-13 9781789957648
Pages 548 pages
Edition 1st Edition
Languages
Concepts
Author (1):
James Padolsey James Padolsey
Profile icon James Padolsey

Table of Contents (26) Chapters

Preface 1. Section 1: What is Clean Code Anyway?
2. Setting the Scene 3. The Tenets of Clean Code 4. The Enemies of Clean Code 5. SOLID and Other Principles 6. Naming Things Is Hard 7. Section 2: JavaScript and Its Bits
8. Primitive and Built-In Types 9. Dynamic Typing 10. Operators 11. Parts of Syntax and Scope 12. Control Flow 13. Section 3: Crafting Abstractions
14. Design Patterns 15. Real-World Challenges 16. Section 4: Testing and Tooling
17. The Landscape of Testing 18. Writing Clean Tests 19. Tools for Cleaner Code 20. Section 5: Collaboration and Making Changes
21. Documenting Your Code 22. Other Peoples' Code 23. Communication and Advocacy 24. Case Study 25. Other Books You May Enjoy

Operators

In the previous chapter on 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....

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.

...

Arithmetic and numeric operators

There are eight arithmetic or numeric operators in JavaScript:

  • Addition: a + b
  • Subtraction: a - b
  • Division: a / b
  • Multiplication: a * b
  • Remainder: a % b
  • Exponentiation: a ** b
  • Unary plus: +a
  • Unary minus: -a
Arithmetic and numeric operators will typically coerce their operands to numbers. The only exception is the + addition operator, which will, if passed a non-numerical operand, assume the function of string concatenation instead of addition.

There is one guaranteed outcome of all of these operations that is worth knowing about beforehand. An input of NaN guarantees an output of NaN:

1 + NaN; // => NaN
1 / NaN; // => NaN
1 * NaN; // => NaN
-NaN; // => NaN
+NaN; // => NaN
// etc.

Beyond that basic assumption, each of these operators behaves in a slightly different way, so it's worth going over each of them individually.

...

Logical operators

Logical operators are typically used to build logical expressions where the result of the expression informs some action or inaction. There are three logical operators in JavaScript:

  • The NOT operator (!a)
  • The AND operator (a && b)
  • The OR operator (a || b)

As with most other operators, they can accept a variety of types and will coerce as necessary. The AND and OR operators, unusually, do not always evaluate to a Boolean value, and both utilize a mechanism called short-circuit evaluation to only execute both operands if some condition is met. We'll learn more about this as we explore each individual logical operator.

The logical NOT operator

The NOT operator is a unary operator. It accepts only...

Comparative operators

Comparative operators are a collection of binary operators that always return Boolean derived from a comparison between the two operands:

  • Abstract equality (a == b)
  • Abstract inequality (a != b)
  • Strict equality (a === b)
  • Strict inequality (a !== b)
  • Greater than (a > b)
  • Greater than or equal to (a >= b)
  • Less than (a < b)
  • Less than or equal to (a <= b)
  • Instance of (a instanceof b)
  • In (a in b)

Each of these operators has slightly different functions and coercive behavior so it's useful to go through each of them individually.

Abstract equality and inequality

The abstract equality (==) and inequality (!=) operators rely on the same algorithm internally, which is responsible for determining...

Assignment operators

An assignment operator will assign the value of its right-side operand to its left-side operand and will return the newly assigned value. The left-side operand of an assignment operation must always be an assignable and valid identifier or property. Examples of this would include the following:

value = 1;
value.property = 1;
value['property'] = 1;

You can additionally use destructuring assignment, which enables you to declare your left-side operand as either an object-literal-like or array-like structure that designates the identifiers you wish to assign and the values you wish to be assigned:

[name, hobby] = ['Pikachu', 'Eating Ketchup'];
name; // => "Pikachu"
hobby: // => "Eating Ketchup"

We will explore destructuring assignment further in a little bit. For now, it's only important to know that it...

Property access operators

Accessing properties in JavaScript is achieved by using one of two operators:

  • Direct property access: obj.property
  • Computed property access: obj[property]

Direct property access

The syntax for directly accessing a property is a single period character, with a left-side operand that is the object you wish to access, and with a right-side operand that is the property name you wish to access:

const street = {
name: 'Marshal St.'
};

street.name; // => "Marshal St."

The right-side operand must be a valid JavaScript identifier, and as such, cannot start with a number, cannot contain whitespace, and in general, cannot contain any punctuation characters that exist elsewhere within...

Other operators and syntax

There are a few remaining operators and pieces of syntax that we have yet to explore and that don't fall into any other operator category:

  • The delete operator: delete VALUE
  • The void operator: void VALUE
  • The new operator: new VALUE
  • Spread syntax: ... VALUE
  • Grouping: (VALUE)
  • The comma operator: VALUE, VALUE, ...

The delete operator

The delete operator can be used to remove properties from objects, as such its only operand usually takes the form of a property accessor, like so:

delete object.property;
delete object[property];

Only properties that are deemed configurable can be deleted in this manner. All properties added conventionally are, by default, configurable and can, therefore, be deleted...

Bitwise operators

JavaScript has seven bitwise operators. The term bitwise here means to operate on binary numbers. These operators are rarely utilized but are useful to know about nonetheless:

  • Bitwise unsigned right-shift operator: >>>
  • Bitwise left-shift operator: <<
  • Bitwise right-shift operator: >>
  • Bitwise OR: |
  • Bitwise AND: &
  • Bitwise XOR: ^
  • Bitwise NOT: ~ (a unary operator)
Bitwise operations are incredibly rare in JavaScript since you're usually dealing with higher-level sequences of bits like strings or numbers. However, it's worth having at least a cursory understanding of bitwise operations so that if you encounter the need, you can cope.

All bitwise operators in JavaScript will first coerce their operands (or a singular operand, in the case of bitwise NOT ~) to a 32-bit integer representation. This means that, internally, a number such...

Summary

In this chapter, we have exhaustively covered the operators available in JavaScript. Collectively, the last past three chapters have given us an incredibly strong foundational understanding of JavaScript syntax, enabling us to feel utterly comfortable when constructing expressions.

In the next chapter, we'll continue to explore the language by applying our existing knowledge of types and operators to the landscapes of declaration and control flow. We'll be exploring how to use larger language constructs to craft clean code and will be discussing many of the traps and idiosyncrasies present in those constructs.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Clean Code in JavaScript
Published in: Jan 2020 Publisher: Packt ISBN-13: 9781789957648
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}