Logical Operators

The main logical operators are:

  • && - and

These automatically coerce types, which is idiomatic to do, despite being somewhat confusing.

When using logical operators, the operands will be coerced to booleans before being compared.

Values coerced to true are called truthy values; all other values are falsy values. The falsy values:

A truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy. (Definition: mdn ).
  • Not Operator

We use ! to convert a truthy value to false , or a falsy value to true .

  • And Operator

The && operator takes two operands:

  • If the first operand is falsy, it evaluates to the first operand
  • If the first operand is truthy, and it evaluates to the second operand
  • Or Operator

The || operator takes two operands:

  • If the first operand is truthy, it evaluates to the first operand
  • If the first operand is false, and it evaluates to the second operand
  • Short Circuiting

Both && and || are short-circuiting operators:

  • && : if the first operand is evaluated as falsy, the second operand will not be evaluated at all (i.e. side-effects will not occur)
  • || : if the first operand is evaluated as truthy, the second operand will not be evaluated at all

Logical assignment operators in Typescript

Portrait of Tom

Hi there, Tom here! As of writing, Typescript 4's stable release is imminent (August 2020) and with it are some very nice changes to come.

Typescript 4 ahead

One of those is the addition of logical assignment operators, which allow to use the logical operators with an assignment. As a reminder, here are the logical operators being used for the new logical assignment operators:

These new logical assignment operators themselves are part of the collection of compound assignment operators , which apply an operator to two arguments and then assign the result to the left side. They are available in many languages and now get enhanced in Typescript.

Code, please!

What does that mean? You probably already know a few compound assignment operators:

The new logical assignment operators now give you the ability to use your logical operator of choice for the same kind of assignment:

Note that these new operators were already available in JS and are also natively suppported by V8.

And that’s about it for one of Typescript 4’s great new features. Thanks for the quick read and I hope you could learn something!

expressFlow is now Lean-Forge

  • Course List
  • Introduction to TypeScript
  • Environment Setup
  • Workspace & first app
  • Basic Syntax
  • Variables & Constants
  • Conditional Control
  • if, else if, else & switch
  • Iteration Control
  • for, while, do-while loops
  • Intermediate
  • Map Collections
  • Object Oriented Programming
  • OOP: Classes & Objects
  • OOP: Standalone Objects
  • OOP: Constructors
  • OOP: Property Modifiers
  • OOP: Access Modifiers
  • OOP: Parameter Properties
  • OOP: Getters & Setters
  • OOP: Static methods
  • OOP: Index Signatures
  • OOP: Inheritance
  • OOP: Composition
  • Compilation Config (tsconfig.json)

TypeScript Operators Tutorial

In this TypeScript tutorial we learn the standard arithmetic, assignment, comparison (relational) and logical (conditional) operators.

We also discuss the negation, concatenation, typeof and ternary operators as well as operator precedence in TypeScript.

  • What are operators
  • Arithmetic operators
  • Assignment operators
  • Comparison (Relational) operators
  • Logical (Conditional) operators
  • Other: The negation operator
  • Other: The concatenation operator
  • Other: The typeof operator
  • Other: The ternary operator
  • Operator precedence

Summary: Points to remember

Operators are one or more symbols in TypeScript that is special to the compiler and allows us to perform various operations within our application.

As an example, let’s consider the + symbol. The + symbol is an operator to perform arithmetic on two or more numeric values. But, when used on two or more strings, the + operator will combine (concatenate) them into a single string.

Types in TypeScript fall under the following categories:

  • Comparison (Relational)
  • Logical (Conditional)
  • Concatenation

TypeScript supports the following the arithmetic operators.

TypeScript supports the following assignment operators.

TypeScript supports the following comparison operators.

Typically, if we want to to turn a positive number into a negative number, we would have to multiply that number by -1.

The negation operator can turn a number negative simply be prefixing it with the - operator.

When working with arithmetic, the + operator will perform an addition. But, when working with strings, the + operator will combine (concatenate) the strings together.

The typeof operator will get and return the data type of the operand we specify.

The typeof operator is simply the keyword typeof .

The ternary operator is a shorthand method of writing a if/else statement that only contains a single execution statement.

note If this doesn’t make sense at the moment, don’t worry, we cover the ternary statement again the tutorial lesson on conditional control statements .

Let’s consider the following if else statement.

In the example above, we evaluate if a number is 10 or not and print a message to the console. Let’s convert this into shorthand with the ternary operator.

Certain operators in TypeScript will have higher precedence than others.

As an example, let’s consider the precedence of the multiplication and addition operators.

If we read the calculation from left to right, we would do the addition first. But, the multiplication operator has a higher precedence than the addition operator, so it will do that part of the calculation first.

We can change the operator precedence by wrapping operators in parentheses.

In the example above, we want the addition to be performed before the multiplication, so we wrap the addition in parentheses.

  • Operators are symbols that have a special meaning to the compiler.
  • TypeScript supports the typical arithmetic, assignment, comparison (relational) and logical (conditional) operators.
  • Typescript also supports the negation, concatenation, typeof and ternary operators.
  • Some operators have greater importance than others and we change operator precedence with parentheses.
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Logical AND (&&)

The logical AND ( && ) (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true . Otherwise it will be false .

More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy .

Description

Logical AND ( && ) evaluates operands from left to right, returning immediately with the value of the first falsy operand it encounters; if all values are truthy , the value of the last operand is returned.

If a value can be converted to true , the value is so-called truthy . If a value can be converted to false , the value is so-called falsy .

Examples of expressions that can be converted to false are:

  • empty string ( "" or '' or `` );
  • undefined .

The AND operator preserves non-Boolean values and returns them as they are:

Even though the && operator can be used with non-Boolean operands, it is still considered a boolean operator since its return value can always be converted to a boolean primitive . To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.

Short-circuit evaluation

The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.

Consider the pseudocode below.

The expr part is never evaluated because the first operand (some falsy expression) is evaluated as falsy . If expr is a function, the function is never called. See the example below:

Operator precedence

The AND operator has a higher precedence than the OR operator, meaning the && operator is executed before the || operator (see operator precedence ).

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

Conversion rules for booleans

Converting and to or.

The following operation involving booleans :

is always equal to:

Converting OR to AND

Removing nested parentheses.

As logical expressions are evaluated left to right, it is always possible to remove parentheses from a complex expression provided that certain rules are followed.

The following composite operation involving booleans :

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

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

TypeScript Operators

  • Typescript Keyof Type Operator
  • TypeScript Constraints
  • TypeScript Instanceof Operator
  • TypeScript Object
  • TypeScript Tuples
  • TypeScript Arrays
  • TypeScript Numbers
  • TypeScript Literal Types
  • TypeScript class
  • TypeScript Optional Parameters
  • TypeScript Map
  • TypeScript Object Types
  • TypeScript Mapped Types
  • TypeScript Assertions Type
  • Rest Parameters in TypeScript
  • Interfaces in TypeScript
  • TypeScript Generic Types
  • Next.js TypeScript
  • TypeScript in operator narrowing Type
  • How to calculate the number of days between two dates in JavaScript ?
  • Convert a String to an Integer in JavaScript
  • How to append HTML code to a div using JavaScript ?
  • How to Open URL in New Tab using JavaScript ?
  • Difference between var and let in JavaScript
  • How do you run JavaScript script through the Terminal?
  • Remove elements from a JavaScript Array
  • How to read a local text file using JavaScript?
  • JavaScript console.log() Method
  • JavaScript Number toString() Method

TypeScript operators are symbols or keywords that perform operations on one or more operands. In this article, we are going to learn various types of TypeScript Operators.

Below are the different TypeScript Operators:

Table of Content

TypeScript Arithmetic operators

Typescript logical operators, typescript relational operators, typescript bitwise operators, typescript assignment operators, typescript ternary/conditional operator, typescript type operators, typescript string operators.

In TypeScript, arithmetic operators are used to perform mathematical calculations.

In TypeScript, logical operators are used to perform logical operations on Boolean values.

In TypeScript, relational operators are used to compare two values and determine the relationship between them.

In TypeScript, bitwise operators perform operations on the binary representation of numeric values.

In TypeScript, assignment operators are used to assign values to variables and modify their values based on arithmetic or bitwise operations.

In TypeScript, the ternary operator, also known as the conditional operator, is a concise way to write conditional statements. It allows you to express a simple if-else statement in a single line.

In TypeScript, type operators are constructs that allow you to perform operations on types. These operators provide powerful mechanisms for defining and manipulating types in a flexible and expressive manner.

In TypeScript, string operators and features are used for manipulating and working with string values.

Please Login to comment...

Similar reads.

  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Simplifying Conditional Logic in TypeScript: The Power of Logical Operators and Nullish Coalescing

  • Acquisition
  • Code Review
  • Customer Stories
  • Engineering
  • Productivity

In the realm of software development, writing clean, efficient, and easily readable code is as crucial as the functionality it provides. TypeScript , a superset of JavaScript, brings strong typing and some syntactic sugar to the table, making our code more understandable and maintainable. Among the myriad of techniques to enhance code readability and efficiency, the use of logical operators ( && , || ) and the nullish coalescing operator ( ?? ) stands out. These operators not only simplify conditional expressions but also make the intention behind the code clearer to fellow developers. In this blog post, we will delve into how replacing traditional code branches with these operators can lead to more streamlined and expressive code in TypeScript.

The Basics: Logical Operators

Logical operators are commonly used for boolean logic, but in TypeScript, they do more than just compare boolean values. They can be used to replace certain if-else structures, making the code more concise and readable.

Truthy vs Falsy vs Nullish

The concepts of “truthy” and “falsy” play a significant role in conditional logic and control flow. A “truthy” value is any value that translates to true when evaluated in a boolean context, allowing for more flexible and concise conditional expressions. Conversely, a “falsy” value is one that evaluates to false in the same contexts. The set of falsy values in TypeScript includes 0 , -0 , null , undefined , false , NaN , '' (the empty string), and document.all , a holdover for historical web compatibility reasons. Every other value is considered “truthy,” including all objects and arrays, even if they are empty. This distinction allows developers to write more succinct conditional checks and assignments, leveraging the fact that expressions like if (value) or value || defaultValue will behave predictably based on the truthiness or falsiness of value .

The concept of “nullish” in TypeScript refers specifically to the values null and undefined , representing the absence of any value or an uninitialized state, respectively. This is where the nullish coalescing operator ( ?? ) comes into play, offering a more precise alternative to the logical OR ( || ) operator for default assignments. The ?? operator will only consider expressions to the left as “defaulted” if they are exactly null or undefined , ignoring other falsy values like 0 or '' that might be valid in certain contexts. This distinction is particularly important for handling optional properties or variables that might legitimately hold falsy values while still needing a default when genuinely unset. By using ?? , TypeScript developers can ensure that only truly “nullish” values are replaced, making code logic clearer and preventing unintended behaviors associated with the broader category of falsy values.

Using && for Conditional Execution

The && operator can be used to execute code only if a certain condition is truthy. It evaluates expressions from left to right, and if all values are truthy, it returns the last value. If any value is falsy, it returns the first falsy value without evaluating the rest.

In this example, console.log(message) is only executed if isTrue is true . This replaces the need for a more verbose if statement.

Using || for Default Values

Similarly, the || operator is often used to provide a default value for variables that might be falsy. It returns the first truthy value it encounters or the last value if all are falsy.

This function will greet the name provided or default to “Guest” if name is undefined or an empty string (and thus falsy).

Elevating the Game with Nullish Coalescing Operator ( ?? )

While the || operator is great for providing default values, it has a pitfall: it considers any falsy value (e.g., 0 , '' , false , null , undefined ) as a trigger to return the second value. This is where the nullish coalescing operator ( ?? ) shines, as it only considers null or undefined as triggers to return the second value.

This is particularly useful when dealing with numeric values, where 0 might be a valid, intended value but would be treated as falsy by the || operator.

Practical Example: Streamlining Code with Logical and Nullish Coalescing Operators

Consider a scenario where we have a function that fetches user data. This data may or may not include a preferences object, and we want to apply defaults for any missing preferences.

In this example, the use of ?. (optional chaining) combined with ?? allows us to succinctly apply default values for potentially undefined properties, making the code cleaner and more resilient to missing data.

The strategic use of logical operators ( && , || ) and the nullish coalescing operator ( ?? ) in TypeScript can significantly enhance code readability and reduce line counts. By replacing traditional conditional branches with these operators, developers can write more expressive, concise, and maintainable code. Remember, the goal of using these techniques is not just to reduce the number of lines of code, but to make the code more intuitive and easier to understand for others (and your future self). Embrace these operators in your TypeScript projects and watch your codebase transform into a model of clarity.

Share this post

About pullrequest.

HackerOne PullRequest is a platform for code review, built for teams of all sizes. We have a network of expert engineers enhanced by AI , to help you ship secure code, faster. Learn more about PullRequest

by PullRequest

April 2, 2024

Definite Assignment Assertions (!)

The Definite Assignment Assertions or also called non-null assertion operator tells the TypeScript compiler that a value typed cannot be null or undefined which is a way to override the compiler's analysis and inform it that a variable will be assigned a value before it is used.

Logical AND assignment (&&=)

The logical AND assignment ( x &&= y ) operator only assigns if x is truthy .

Description

Short-circuit evaluation.

The logical AND operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule:

(some falsy expression) && expr is short-circuit evaluated to the falsy expression;

Short circuit means that the expr part above is not evaluated , hence any side effects of doing so do not take effect (e.g., if expr is a function call, the calling never takes place).

Logical AND assignment short-circuits as well meaning that x &&= y is equivalent to:

And not equivalent to the following which would always perform an assignment:

Using logical AND assignment

Specifications, browser compatibility.

  • Logical AND (&&)
  • The nullish coalescing operator ( ?? )
  • Bitwise AND assignment ( &= )

© 2005–2021 MDN contributors. Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND_assignment

Short Circuiting Assignment Operators in Typescript 4.0 & Angular 11

Using Short Circuiting Assignment Operators in Angular

Angular 11 supports only Typescript 4.0 version .

Typescript 4.0 has some cool features that can be used in Angular 11. 

One such feature is short-circuiting assignment operators .

JavaScript and other languages, supports compound assignment operators .

Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand as shown below.

But we cannot use logical and (&&), logical or (||), and nullish coalescing (??) operators for compound assignment.

Typescript 4.0 supports now these three operators for compound assignment.

We can replace the above statment with single line logical OR compound assignment a ||= b .

With this shorthand notation we can lazily initialize values, only if they needed.

The logical assignment operators work differently when compare to other mathematical assignment operators.

Mathematical assignment operators always trigger a set operation.

But logical assignment operators uses its short-circuiting semantics and avoids set operation if possible.

We won’t be getting much performance benefit, but calling set operation unnecessarily has it’s side effects.

In the following example, if the.innerHTML setter was invoked unnecessarily, it might result in the loss of state (such as focus) that is not serialized in HTML:

Arunkumar Gudelli

Logical Operators and Assignment

Logical Operators e Assignment são novas funcionalidades do JavaScript para 2020. Esses são um conjunto de operadores novos que editam um objeto JavaScript. Seu objetivo é reutilizar o conceito de operadores matemáticos (Ex: += -= *=) porém usando lógica. interface User { id?: number name: string location: { postalCode?: string } } function updateUser(user: User) { // Pode-se trocar esse código: if (!user.id) user.id = 1 // Ou esse código: user.id = user.id || 1 // Por esse código: user.id ||= 1 } // Esses conjuntos de operadores podem lidar com encadeamento profundo podendo poupar uma boa quantidade de código repetido. declare const user: User user.location.postalCode ||= "90210" // São três novos operadores: ||= mostrado acima &&= que usa a lógica do 'and' ao invés da 'or' ??= que se baseia no example:nullish-coalescing para oferecer uma versão mais rigorosa do || que usa === no lugar. Para mais informações da proposta, veja: https://github.com/tc39/proposal-logical-assignment

IMAGES

  1. What is TypeScript and When to Use It

    typescript logical and assignment

  2. TypeScript Function Types: A Beginner's Guide

    typescript logical and assignment

  3. TypeScript Tutorial

    typescript logical and assignment

  4. What is TypeScript and why should you care?

    typescript logical and assignment

  5. A beginner’s guide to TypeScript (with some history of the TypeScript

    typescript logical and assignment

  6. expressFlow

    typescript logical and assignment

VIDEO

  1. Assignment Operators in Typescript

  2. Zoom Class 02 07 Aug 2023 Basics of Typescript Operators

  3. GI-AIWMD

  4. Typescript Type System explained by Anders Hejlsberg

  5. Typescript

  6. have you used Logical Or Assignment (||=) ? #coding #javascript #tutorial #shorts

COMMENTS

  1. TypeScript: Playground Example

    Logical Operators and Assignment are new features in JavaScript for 2020. These are a suite of new operators which edit a JavaScript object. Their goal is to re-use the concept of mathematical operators (e.g. += -= *=) but with logic instead. Site Colours: Code Font:

  2. Why are logical assignment (&=) operators disallowed in Typescript

    Your variable is a boolean and these values are combined using && (logical AND). In TypeScript you could conceivably create an &&= operator but the && operator uses short-circuit evaluation where evaluation stops as soon the result is known which means that the semantic of x &&= y becomes a bit clouded. edited Jul 31, 2017 at 14:51.

  3. Logical AND assignment (&&=)

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

  4. Logical Operators in Typescript

    boolean data type, truthy & falsy. The logical operators convert the operand to the boolean is a primitive type. The boolean represents a simple true/false value.. Every possible value in Typescript can be converted to true & false.For Example, converting 100 to boolean will result in a true.And 0 becomes false.. Those values, which converts to false are known as falsy.

  5. Logical Operators

    TypeScript Express. 1 Types. 1.1 Primitive Types. 1.2 Object Types. 1.3 Nullability. 1.4 Checking Types. 2 Syntax. 2.1 Variables. 2.2 Equality. 2.3 Logical Operators. 2.4 Iteration. 2.5 Spread. ... When using logical operators, the operands will be coerced to booleans before being compared. Values coerced to true are called truthy values; ...

  6. Typescript 4 enhances the compound assignment operators

    Hi there, Tom here! As of writing, Typescript 4's stable release is imminent (August 2020) and with it are some very nice changes to come. Typescript 4 ahead. One of those is the addition of logical assignment operators, which allow to use the logical operators with an assignment. As a reminder, here are the logical operators being used for the ...

  7. TypeScript Operators Tutorial

    TypeScript supports the typical arithmetic, assignment, comparison (relational) and logical (conditional) operators. Typescript also supports the negation, concatenation, typeof and ternary operators. Some operators have greater importance than others and we change operator precedence with parentheses.

  8. Logical AND (&&)

    The logical AND ( &&) (logical conjunction) operator for a set of boolean operands will be true if and only if all the operands are true. Otherwise it will be false. More generally, the operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

  9. TypeScript Operators

    Below are the different TypeScript Operators: Table of Content. TypeScript Arithmetic operators. TypeScript Logical operators. TypeScript Relational operators. TypeScript Bitwise operators. TypeScript Assignment operators. TypeScript Ternary/conditional operator. TypeScript Type Operators.

  10. TypeScript: Documentation

    Conditional Types. At the heart of most useful programs, we have to make decisions based on input. JavaScript programs are no different, but given the fact that values can be easily introspected, those decisions are also based on the types of the inputs. Conditional types help describe the relation between the types of inputs and outputs.

  11. Simplifying Conditional Logic in TypeScript: The Power of Logical

    In this blog post, we will delve into how replacing traditional code branches with these operators can lead to more streamlined and expressive code in TypeScript. The Basics: Logical Operators. Logical operators are commonly used for boolean logic, but in TypeScript, they do more than just compare boolean values.

  12. Typescript switch case with logical and

    For your scenario it will always evaluate to the 2nd integer in the logical and &&. (More information about Logical Operators) Logical AND (&&) expr1 && expr2. Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.

  13. TypeScript: Playground Example

    Nullish Coalescing. The nullish coalescing operator is an alternative to || which returns the right-side expression if the left-side is null or undefined. In contrast, || uses falsy checks, meaning an empty string or the number 0 would be considered false. A good example for this feature is dealing with partial objects which have defaults when ...

  14. Assignment Operators in TypeScript

    TypeScript Tutorial. An assignment operator requires two operands. The value of the right operand is assigned to the left operand. The sign = denotes the simple assignment operator. The typescript also has several compound assignment operators, which is actually shorthand for other operators. List of all such operators are listed below.

  15. Definite Assignment Assertions (!)

    Definite Assignment Assertions (!) The Definite Assignment Assertions or also called non-null assertion operator tells the TypeScript compiler that a value typed cannot be null or undefined which is a way to override the compiler's analysis and inform it that a variable will be assigned a value before it is used. type Person = {. name: string; };

  16. Logical AND assignment

    Logical AND assignment (&&=) The logical AND assignment (x &&= y) operator only assigns if x is truthy. Syntax expr1 &&= expr2 Description Short-circuit evaluation The logical AND operator is evaluated left to right, it is tested for possible short-circuit evaluation using the following rule: (some falsy expression) && expr is short-circuit evaluated to the falsy expression; Short circuit ...

  17. Typescript literal types and addition assignment operators

    2) d = d + b; This expression will be interpreted by the compiler as following: Assignment Expression: left side: d. token (operator): =. right side: d + b. In order to check the types on both sides, the compiler deducts the type for the right and left expression. In case of the left side its simple. For the right side it will be number.

  18. Short Circuiting Assignment Operators in Typescript 4.0 & Angular 11

    Typescript 4.0 has some cool features that can be used in Angular 11. One such feature is short-circuiting assignment operators. JavaScript and other languages, supports compound assignment operators. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand as shown below.

  19. JavaScript OR (||) variable assignment explanation

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

  20. TypeScript: Playground Example

    Logical Operators and Assignment. Logical Operators e Assignment são novas funcionalidades do JavaScript para 2020. Esses são um conjunto de operadores novos que editam um objeto JavaScript. Seu objetivo é reutilizar o conceito de operadores matemáticos (Ex: += -= *=) porém usando lógica. Site Colours: Code Font:

  21. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...