Logical Operators and Assignment

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. interface User { id?: number name: string location: { postalCode?: string } } function updateUser(user: User) { // This code can be replaced if (!user.id) user.id = 1 // Or this code: user.id = user.id || 1 // With this code: user.id ||= 1 } // The suites of operators can handle deeply nesting, which can save on quite a lot of boilerplate code too. declare const user: User user.location.postalCode ||= "90210" // There are three new operators: ||= shown above &&= which uses 'and' logic instead of 'or' ??= which builds on example:nullish-coalescing to offer a stricter version of || which uses === instead For more info on the proposal, see: https://github.com/tc39/proposal-logical-assignment

  • 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
  • How to get Argument Types from Function in TypeScript ?
  • What is the Record Type in TypeScript ?
  • TypeScript | Array unshift() Method
  • Typescript Awaited<Type> Utility Type
  • TypeScript String padEnd() method
  • How to Flatten Array of Arrays in TypeScript ?
  • How to define Singleton in TypeScript?
  • How do I dynamically assign properties to an object in TypeScript?
  • Typescript Partial<Type> Utility Type
  • TypeScript | String slice() Method with example
  • TypeScript | String search() Method
  • TypeScript Interview Questions and Answers (2024)
  • Typescript Record<Keys, Type> Utility Type
  • Classes in TypeScript
  • TypeScript Instanceof Operator
  • TypeScript Array Object.values() Method
  • TypeScript String
  • What is namespace in Typescript ?
  • TypeScript Indexed Access Types

TypeScript Operators

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
  • 10 Best Free Note-Taking Apps for Android - 2024
  • 10 Best VLC Media Player Alternatives in 2024 (Free)
  • 10 Best Free Time Management and Productivity Apps for Android - 2024
  • 10 Best Adobe Illustrator Alternatives in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

MarketSplash

Getting To Know Typescript Operators In Depth

Dive deep into TypeScript operators, the building blocks that enhance code efficiency and readability. From arithmetic to relational, get a grasp on how each operator functions and elevates your coding prowess. Join us on this coding journey!

💡 KEY INSIGHTS

  • The 'in' operator in TypeScript is crucial for checking property existence in objects, enhancing code reliability and error handling.
  • It is particularly useful in interfaces and dynamic property checking , ensuring objects conform to expected structures.
  • The article points out common pitfalls, like confusing property existence with truthy values and overlooking the prototype chain.
  • It also compares 'in' with other operators, highlighting its unique functionality in TypeScript.

Typescript operators play a pivotal role in shaping the way we handle data and logic in our applications. As a cornerstone of the language, understanding these operators is essential for efficient coding. This knowledge not only streamlines development but also enhances code readability and maintainability. Let's explore the nuances of these operators to elevate our Typescript proficiency.

typescript or operator assignment

Basics Of Typescript Operators

Arithmetic operators in typescript, logical operators: true or false, relational operators: comparing values, bitwise operators: manipulating bits, assignment operators: setting values, ternary operator: conditional expressions, type operators: defining types, spread and rest operators: working with arrays and objects, frequently asked questions, arithmetic operators, logical operators, bitwise operators, relational operators, assignment operators, ternary operator, concatenation operator, type operators.

typescript or operator assignment

Arithmetic operators like + , - , * , and / allow us to perform basic mathematical operations.

With logical operators such as && , || , and ! , we can establish conditions and logic flows.

Bitwise operators like & , | , and ^ operate on individual bits of numbers.

Relational operators, including == , != , > , and < , help us compare values.

Assignment operators, such as = , += , and -= , assign values to variables.

The ternary operator ? : provides a shorthand way to perform conditional operations.

In Typescript, the + operator can also concatenate strings.

Type operators like typeof and instanceof help in determining the type of a variable or checking its instance.

Arithmetic operators in Typescript are essential for performing mathematical operations on numbers. They're the basic tools that allow us to add, subtract, multiply, and more.

Addition Operator

Subtraction operator, multiplication operator, division operator, modulus operator, increment and decrement, exponentiation operator.

The + operator adds two numbers together.

The - operator subtracts one number from another.

With the * operator, we can multiply two numbers.

The / operator divides one number by another.

The % operator returns the remainder of a division.

The ++ and -- operators increase or decrease a number by one, respectively.

The ** operator raises a number to the power of another number.

Logical operators in Typescript are used to determine the truthiness of conditions. They play a crucial role in decision-making structures, allowing us to evaluate multiple conditions.

AND Operator

Or operator, not operator.

The && operator returns true if both conditions are true.

The || operator returns true if at least one of the conditions is true.

The ! operator inverts the truthiness of a condition.

While not purely logical, the ternary ? : operator allows for concise conditional checks.

The exclamation mark ( ! ) operator following node.parent caught attention. An initial attempt to compile the file using TypeScript version 1.5.3 resulted in an error pinpointing the exact location of this operator. However, after upgrading to TypeScript 2.1.6, the code compiled seamlessly. Interestingly, the transpiled JavaScript omitted the exclamation mark:

This operator is known as the non-null assertion operator . It serves as a directive to the compiler, indicating that "the expression at this location is neither null nor undefined." There are instances where the type checker might not deduce this on its own.

Relational operators in Typescript are pivotal for comparing values. They help determine relationships between variables, enabling us to make decisions based on these comparisons.

Not Equal To

Greater than and less than, greater than or equal to, less than or equal to.

The == operator checks if two values are equal.

The != operator checks if two values are not equal.

The > and < operators compare the magnitude of values.

The >= and <= operators offer inclusive comparisons.

Bitwise operators in Typescript allow for direct manipulation of individual bits within numbers. These operators are especially useful in low-level programming, offering precise control over data at the bit level.

Bitwise AND

Bitwise xor, bitwise not, left and right shift.

The & operator performs a bitwise AND operation.

The | operator performs a bitwise OR operation.

The ^ operator is used for the bitwise XOR operation.

The ~ operator inverts all bits.

The << and >> operators shift bits to the left or right, respectively.

Assignment operators in Typescript are fundamental tools that allow us to assign values to variables. They not only set values but can also perform operations during the assignment, streamlining our code.

Basic Assignment

Addition assignment, subtraction assignment, multiplication and division assignment, modulus and exponentiation assignment.

The = operator assigns a value to a variable.

The += operator adds a value to a variable and then assigns the result to that variable.

The -= operator subtracts a value from a variable and then assigns the result.

The *= and /= operators multiply or divide a variable's value, respectively, and then assign the result.

The %= and **= operators assign the remainder of a division or the result of an exponentiation to a variable.

The ternary operator in Typescript offers a concise way to perform conditional checks. It's a shorthand for the if-else statement, allowing developers to write cleaner and more readable code.

Basic Usage

Nested ternary, using with functions.

The ternary operator is represented by ? : and is used to evaluate a condition, returning one value if the condition is true and another if it's false.

Ternary operators can be nested for multiple conditions, though it's essential to ensure readability.

The ternary operator can also be combined with functions to execute specific tasks based on conditions.

In Typescript , type operators play a crucial role in ensuring type safety. They allow developers to define, check, and manipulate types, ensuring that variables adhere to the expected data structures.

typeof Operator

Instanceof operator, custom type guards, type assertions.

The typeof operator returns a string indicating the type of a variable.

The instanceof operator checks if an object is an instance of a particular class or constructor.

Typescript allows developers to create custom type guards using the is keyword, ensuring more refined type checks.

Type assertions, using <Type> or as Type , allow developers to specify the type of an object explicitly.

In Typescript , the spread ( ... ) and rest ( ... ) operators provide powerful ways to work with arrays and objects. They offer concise syntax for expanding and collecting elements, making data manipulation more efficient.

Spread Operator

Rest operator.

The spread operator allows for the expansion of array elements or object properties.

For objects:

The rest operator is used to collect the remaining elements into an array or object properties into an object.

For function parameters:

Can TypeScript operators be overloaded like in some other languages?

No, TypeScript does not support operator overloading. The behavior of operators is fixed and cannot be changed for user-defined types. However, you can define custom methods for classes to achieve similar functionality.

How does the in operator work in TypeScript?

The in operator is used to determine if an object has a specific property. It returns true if the property is in the object (or its prototype chain) and false otherwise. For example, "name" in person would check if the person object has a property named "name".

What's the difference between == and === operators in TypeScript?

Both == and === are comparison operators, but they work differently. The == operator performs type coercion if the variables being compared are of different types, meaning it might convert one type to another for the comparison. On the other hand, === is a strict equality operator that checks both value and type, ensuring no type coercion occurs.

typescript or operator assignment

How can I use the instanceof operator with custom classes in TypeScript?

The instanceof operator in TypeScript works similarly to JavaScript. It checks if an object is an instance of a particular class or constructor. For custom classes, you can use it like: let isStudent = person instanceof Student; , where Student is a user-defined class. If person is an instance of the Student class, isStudent will be true .

Let's see what you learned!

Which Operator Is Used In TypeScript To Specify An Optional Property?

Continue learning with these typescript guides.

  • How To Utilize TypeScript Decorators Effectively
  • How To Use TypeScript Extend Type Effectively
  • TypeScript Generics: A Path To Scalable Code
  • How To Use TypeScript Instanceof Effectively
  • How To Use The TypeScript Constructor Efficiently

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

TypeScript Operator

Switch to English

Introduction Understanding TypeScript operators is a fundamental part of learning TypeScript. TypeScript operators are symbols used to perform operations on operands. An operand can be a variable, a value, or a literal.

  • Types of TypeScript Operators

Table of Contents

Arithmetic Operators

Logical operators, relational operators, bitwise operators, assignment operators, ternary/conditional operators, string operators, type operators, tips and common error-prone cases.

  • Ternary/conditional Operators
  • Always use '===' instead of '==' for comparisons to avoid type coercion.
  • Remember that the '&&' and '||' operators return a value of one of the operands, not necessarily a boolean.
  • Be careful when using bitwise operators as they can lead to unexpected results due to JavaScript's internal number representation.
  • Use parentheses to ensure correct order of operations when combining operators in complex expressions.
  • Remember that the '+' operator behaves differently with strings, leading to unexpected results.
  • Python (302)
  • Javascript (658)
  • HTML5 (534)
  • Object-oriented Programming (120)
  • React (280)
  • Node.js (264)
  • Data Structure (172)
  • WordPress (226)
  • jQuery (326)
  • Angular (306)
  • Google Ads (172)
  • Django (253)
  • Digital Marketing (196)
  • TypeScript (288)
  • Redux (268)
  • Kotlin (290)
  • MongoDB (262)
  • Laravel (252)
  • Swift (172)
  • Cloud Computing (286)
  • Agile/Scrum (208)
  • ASP.NET (254)
  • UI/UX Design (170)
  • Analytics (258)
  • Linux (252)
  • Search Engine Optimization (936)
  • Github (240)
  • Bootstrap (264)
  • Machine Learning (237)
  • Project Management (244)
  • REST API (270)
  • Oracle (264)
  • Excel (276)
  • Adobe Photoshop (232)
  • Data Science (235)
  • Artificial Intelligence (262)
  • Vue.js (280)
  • Hadoop (244)
  • GoLang (266)
  • Scala (262)
  • Solidity (252)
  • Ruby on Rails (246)
  • Augmented Reality (218)
  • VidGenesis (1317)
  • Virtual Reality (88)
  • Unreal Engine (78)

Popular Articles

  • Typescript Unknown Vs Any (Dec 06, 2023)
  • Typescript Undefined (Dec 06, 2023)
  • Typescript Type Definition (Dec 06, 2023)
  • Typescript Splice (Dec 06, 2023)
  • Typescript Return Type Of Function (Dec 06, 2023)
  • 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.

TypeScript Operators

An operator is a special symbol that operates on operands by defining a function that is called upon whenever the operator is invoked. Each operator has a unique symbol used to invoke that operator. Since TypeScript is a strongly typed superset of JavaScript, TypeScript supports all the standard operators supported by JavaScript.

Types of Operators Based on Number of Operands

The operator operates on operands. There are 3 types of operators based on the number of operands :

Unary operator : These operators require only one operand.

Binary operator : These operators require two operands. Most operators that are available in TypeScript are binary operators.

Ternary operator : These operators require three operands where the first operand is conditional. TypeScript has a ternary operator ?

Therefore, all typescript operators can be classified as one of the three : unary , binary , or ternary based on the number of operands it receives.

Introduction

TypeScript operators can be classified into one of the following categories :

  • Arithmetic operators
  • Relational/Comparision operators
  • Logical operators
  • Bitwise operators
  • Assignment operators
  • Ternary/Conditional operators
  • Concatenation operators
  • Type operators

Below we will see all the operators that are present in TypeScript along with some examples.

Operators in TypeScript

1. arithmetic operators.

Operators who take numeric values as operand(s) and perform some action on the operands to return a single numeric value are generally placed in the category of Arithmetic operators.

In TypeScript, there are 7 arithmetic operators :

+ operator or Addition operator :

- operator or Subtraction operator :

/ operator or Division operator :

* operator or Multiplication operator :

% operator or Modulus operator :

++ operator or Increment operator :

-- operator or Decrement operator :

2. Comparison (Relational) Operators

Operators which are used to compare or to define the relationship between two operands and return a boolean value (True or False) are generally placed in the category of Comparision / Relational operators.

In TypeScript, there are 8 relational / comparision operators :

== operator or Is equal to the operator :

=== operator or Is identical to the operator :

!= operator or Not equal to the operator :

!== operator or Not identical to the operator :

> operator or Greater than operator :

>= operator or Greater than or equal to the operator :

< operator or Less than operator :

<= operator or Less than or equal to the operator :

3. Logical Operators

Operators which are used to combine two or more conditions into a single expression that returns a boolean value (True or False) are generally placed in the category of Logical operators.

In TypeScript, there are 3 logical operators :

&& operator or Logical AND operator :

|| operator or Logical OR operator :

! operator or Logical NOT operator :

4. Bitwise Operators

Operators which are used to perform bit manipulation and bitwise operations on operand(s) are generally placed in the category of Bitwise operators :

In TypeScript, there are 7 bitwise operators :

& operator or Bitwise AND operator :

| operator or Bitwise OR operator :

^ operator or Bitwise XOR operator :

~ operator or Bitwise NOT operator :

>> operator or Bitwise Right Shift operator :

<< operator or Bitwise Left Shift operator :

>>> operator or Bitwise Right Shift With Zero operator :

5. Assignment Operators

Operators which are used to assign values to the operands or variables are generally placed in the category of Assignment operators.

In TypeScript, there are 6 Assignment operators :

= operator or Assign operator :

+= operator or Add and assign operator :

-= operator or Subtract and assign operator :

*= operator or Multiply and assign operator :

/= operator or Divide and assign operator :

%= operator or Modulus and assign operator :

6. Ternary/conditional Operator

This operator requires three operands and returns a boolean value based on the condition.

It is a shorthand way of writing an if-else statement

here, expression is the conditional statement and based on its value either expression1 (when expression is True ) will be executed or expression2 (when expression is False )

7. Concatenation Operator

The concatenation operator is used to join two or more strings into one single string.

8. Type Operator

Operators which are used with objects or assist in working with objects such as typeof , instanceof , in , or delete are generally placed in the category of Type operators.

In TypeScript, there are 4 type operators :

in operator :

typeof operator :

instanceof operator :

delete operator :

  • TypeScript supports all the standard operators supported by JavaScript
  • TypeScript operators can be generally divided into the following categories: Arithmetic, Logical, Bitwise, Relational, Assignment, Ternary, Concatenation, and Type Operators.
  • there are 7 arithmetic operators in TypeScript : + , - , / , * , % , ++ , and --
  • there are 8 relational operators in TypeScript : > , < , >= , <= , == , === and != , !==
  • there are 3 logical operators in TypeScript : && , || , and !
  • there are 7 bitwise operators in TypeScript : & , | , ^ , ~ , >> , << and >>>
  • there are 6 assignment operators in TypeScript : = , += , -= , *= , /= , and %= .

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

TekTutorialsHub-Logo

  • Typescript Operators

Typescript operators perform some operation on one or more operands and produce a result. The operand is the data or value on which an operation is to be done. For Example, in the expression 10+2 + is an operator, while 10 & 2 are the operands.

Table of Contents

Binary Operators

Unary operatos, the ternary operator, arithmetic operators, logical operators, relational operators, bitwise operators, assignment operators, miscellaneous operators, type operators.

  • Operator Precedence

The Operators perform an operation on operands. There can be one, two, or three operands. The operators that require only one operand are unary  operators. Those who take two operands are binary operators. The Typescript also have one ternary operator, which takes three operand

A binary operator has one operand (Left operand) before the operator and one after the operator (right operand)

The unary operator operates on a single operand. The operand can be either before or after the operator.

The Typescript also has one special ternary conditional operator , which takes three operands.

List of Typescript Operators

The Typescript operators can be classified broadly based on their functions as follows.

  • Type Operator

The arithmetic operators take numerical values as operands, operates on them and return the result as a single numerical value.

The operator precedence along with their associativity determines how Typescript evaluates an expression when there are multiple operators present in the expression. Each Typescript operators have certain precedence. The Typescript evaluates the operators with higher precedence first. If a group of operators has the same Precedence, then it evaluates them either  left to right  or  right to left , depending on the operator’s associativity.

Click to read more about Operator Precedence

  • Expressions & Operators
  • Precedence & Associativity
  • Complete Typescript Tutorial
  • Arithmetic Operators
  • Unary plus / Unary minus Operators
  • Increment/Decrement Operators
  • Comparison / Relational Operators
  • Equality Operator / Strict Equality Operators
  • Ternary Conditional Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Nullish coalescing operator
  • Comma Operator in Typescript

Related Posts

What is TypeScript An Introduction

Introduction to Typescript. What is TypeScript

Installing TypeScript

Typescript Installation & environment setup

Leave a comment cancel reply.

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed .

TypeScript Tutorial

  • TypeScript Tutorial
  • TypeScript - Home
  • TypeScript - Overview
  • TypeScript - Environment Setup
  • TypeScript - Basic Syntax
  • TypeScript - Types
  • TypeScript - Variables
  • TypeScript - Operators
  • TypeScript - Decision Making
  • TypeScript - Loops
  • TypeScript - Functions
  • TypeScript - Numbers
  • TypeScript - Strings
  • TypeScript - Arrays
  • TypeScript - Tuples
  • TypeScript - Union
  • TypeScript - Interfaces
  • TypeScript - Classes
  • TypeScript - Objects
  • TypeScript - Namespaces
  • TypeScript - Modules
  • TypeScript - Ambients
  • TypeScript Useful Resources
  • TypeScript - Quick Guide
  • TypeScript - Useful Resources
  • TypeScript - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

TypeScript - Assignment Operators Examples

Note − Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |= and ^=.

On compiling, it will generate the following JavaScript code −

It will produce the following output −

  • TS Introduction
  • TS Operators
  • TS Control Flow
  • TS Data structures
  • TS Adv. Concepts
  • TS Adv. Programming
  • TS Essentials

Assignment Operators in TypeScript

TypeScript assignment operators are used to assign values to variables and expressions. They are the fundamental building blocks for manipulating data and updating the state of your program.

List of Assignment Operators

Here are the different assignment operators available in TypeScript:

  • Simple assignment (=): Assigns the right operand value to the left operand.
  • Addition assignment (+=): Adds the right operand to the left operand and assigns the result to the left operand.
  • Subtraction assignment (-=): Subtracts the right operand from the left operand and assigns the result to the left operand.
  • Multiplication assignment (*=): Multiplies the right operand with the left operand and assigns the result to the left operand.
  • Division assignment (/=): Divides the left operand by the right operand and assigns the result to the left operand.
  • Modulo assignment (%=): Finds the remainder of dividing the left operand by the right operand and assigns the result to the left operand.
  • Exponential assignment (**=): Raises the left operand to the power of the right operand and assigns the result to the left operand.
  • Left shift assignment ( Shifts the left operand bitwise to the left by the number of bits specified by the right operand and assigns the result to the left operand.
  • Right shift assignment (>>=): Shifts the left operand bitwise to the right by the number of bits specified by the right operand and assigns the result to the left operand.
  • Unsigned right shift assignment (>>>=): Shifts the left operand bitwise to the right by the number of bits specified by the right operand, treating the left operand as an unsigned integer, and assigns the result to the left operand.

Assignment (=) Operator

The basic assignment operator (=) is used to assign a value to a variable.

Compound Assignment Operators

Compound assignment operators combine an assignment with another operation, making it more concise. They include:

Addition Assignment (+=)

Subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), modulus assignment (%=).

These compound assignment operators perform the specified operation and then assign the result back to the variable.

Exponentiation Assignment (**=)

The exponentiation assignment operator (**=) raises the left operand to the power of the right operand and assigns the result to the left operand.

Type Safety

TypeScript assignment operators ensure type safety by restricting assignments to compatible data types. This prevents errors and unexpected behavior due to mismatched types.

Operator Precedence

Assignment operators have a specific order of precedence within expressions. Understanding this order is crucial for accurate evaluation and avoiding ambiguity in your code.

Chaining Assignments

You can chain multiple assignment operators together to perform multiple operations with concise syntax.

TypeScript assignment operators, including the basic assignment (=) and compound assignments (+=, -=, *=, /=, %=), provide a concise way to assign values and perform compound operations on variables. These operators enhance code readability and efficiency by combining assignment with arithmetic or modulus operations in a single step.

  • TypeScript Arithmetic Operators
  • TypeScript Comparison Operators
  • TypeScript Logical Operators
  • TypeScript Unary operators
  • TypeScript Bitwise operators

Marius Schulz

Nullish Coalescing: The ?? Operator in TypeScript

TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator . We can use this operator to provide a fallback value for a value that might be null or undefined .

# Truthy and Falsy Values in JavaScript

Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy or falsy : when coerced to a Boolean, a value can either produce the value true or false . In JavaScript, the following values are considered to be falsy:

All other JavaScript values will produce the value true when coerced to a Boolean and are thus considered truthy.

# Providing Fallback Values with the ?? Operator

The ?? operator can be used to provide a fallback value in case another value is null or undefined . It takes two operands and is written like this:

If the left operand is null or undefined , the ?? expression evaluates to the right operand:

Otherwise, the ?? expression evaluates to the left operand:

Notice that all left operands above are falsy values. If we had used the || operator instead of the ?? operator, all of these expressions would've evaluated to their respective right operands:

This behavior is why you shouldn't use the || operator to provide a fallback value for a nullable value. For falsy values, the result might not be the one you wanted or expected. Consider this example:

The expression options.prettyPrint ?? true lets us provide the default value true in case that the prettyPrint property contains the value null or undefined . If prettyPrint contains the value false , the expression false ?? true still evaluates to false , which is exactly the behavior we want here.

Note that using the || operator here would lead to incorrect results. options.prettyPrint || true would evaluate to true for the values null and undefined , but also for the value false . This would clearly not be intended. I've seen this happen in practice a handful of times, so make sure to keep this case in mind and use towards the ?? operator instead.

# Compiled Output: ES2020 and Newer

The nullish coalescing operator has reached Stage 4 ("Finished") of the TC39 process and is now officially part of ES2020 . Therefore, the TypeScript compiler will emit the ?? operator as is without any downleveling when you're targeting "ES2020" (or a newer language version) or "ESNext" in your tsconfig.json file:

So, this simple expression will be emitted unchanged:

If you're planning on using the ?? operator while targeting "ES2020" or a newer language version, head over to caniuse.com and node.green and make sure that all the JavaScript engines you need to support have implemented the operator.

# Compiled JavaScript Output: ES2019 and Older

If you're targeting "ES2019" or an older language version in your tsconfig.json file, the TypeScript compiler will rewrite the nullish coalescing operator into a conditional expression. That way, we can start using the ?? operator in our code today and still have the compiled code successfully parse and execute in older JavaScript engines.

Let's look at the same simple ?? expression again:

Assuming we're targeting "ES2019" or a lower language version, the TypeScript compiler will emit the following JavaScript code:

The value variable is compared against both null and undefined (the result of the expression void 0 ). If both comparisons produce the value false , the entire expression evaluates to value ; otherwise, it evaluates to fallbackValue .

Now, let's look at a slightly more complex example. Instead of a simple value variable, we're going to use a getValue() call expression as the left operand of the ?? operator:

In this case, the compiler will emit the following JavaScript code (modulo whitespace differences):

You can see that the compiler generated an intermediate variable _a to store the return value of the getValue() call. The _a variable is then compared against null and void 0 and (potentially) used as the resulting value of the entire expression. This intermediate variable is necessary so that the getValue function is only called once.

# Compiled Output: Checking for null and undefined

You might be wondering why the compiler emits the following expression to check the value variable against null and undefined :

Couldn't the compiler emit the following shorter check instead?

Unfortunately, it can't do that without sacrificing correctness. For almost all values in JavaScript, the comparison value == null is equivalent to value === null || value === undefined . For those values, the negation value != null is equivalent to value !== null && value !== undefined . However, there is one value for which these two checks aren't equivalent, and that value is document.all :

The value document.all is not considered to be strictly equal to either null or undefined , but it is considered to be loosely equal to both null and undefined . Because of this anomaly, the TypeScript compiler can't emit value != null as a check because it would produce incorrect results for document.all .

You can read more about this curious behavior in an answer to the Why is document.all falsy? question on Stack Overflow. Oh, the things we do for web compatibility.

This article and 44 others are part of the TypeScript Evolution series. Have a look!

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

TypeScript is a programming language that adds static type checking to JavaScript.

TypeScript is a superset of JavaScript, meaning that everything available in JavaScript is also available in TypeScript, and that every JavaScript program is a syntactically legal TypeScript program. Also, the runtime behavior of TypeScript and JavaScript is identical.

However, TypeScript adds compile time type checking, implementing rules about how different types can be used and combined. This catches a wide variety of programming errors that in JavaScript are only encountered at runtime.

Some typing rules are inferred from JavaScript. For example, in the code below, TypeScript infers that myVariable is a string, and will not allow it to be reassigned to a different type:

TypeScript also enables the programmer to annotate their code, to indicate, for example, the types of parameters to a function or the properties of an object:

After compilation, type annotations are removed, making the compiled output just JavaScript, meaning it can be executed in any JavaScript runtime.

  • TypeScript website

IMAGES

  1. TypeScript Operators

    typescript or operator assignment

  2. Ternary Operator in TypeScript

    typescript or operator assignment

  3. #3 TypeScript Tutorial for Beginners

    typescript or operator assignment

  4. TypeScript `satisfies` operator

    typescript or operator assignment

  5. Typescript

    typescript or operator assignment

  6. TypeScript for JavaScript Developers Part 2: Configuration and Spread

    typescript or operator assignment

VIDEO

  1. operators in C||arithmetic operator||assignment operator||increment & decrement operator||part-1

  2. typescript and Node Js Assignment Exercise no 3 I Governor IT Course

  3. Typescript Q no 8 solved

  4. 45 Assignment Q6 solved Typescript ND JavaScript

  5. Assignment & Relational Operator

  6. IN operator in TypeScript... 'IN' operator; typescript in operator

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. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

  3. Logical OR assignment (||=)

    Description. Logical OR 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 falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  4. TypeScript Operators

    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. Obtains the type of a variable, function, or property. Obtains the keys (property names) of a type.

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

  6. Getting To Know Typescript Operators In Depth

    Basics Of Typescript Operators. 🧷. Operators in Typescript are symbols used to perform specific operations on one or more operands. They are the building blocks that allow us to create logic within our Typescript applications. Arithmetic Operators. Logical Operators. Bitwise Operators. Relational Operators. Assignment Operators.

  7. Understanding TypeScript Operators

    A detailed guide on the various types of TypeScript operators including arithmetic, logical, relational, bitwise, assignment, ternary/conditional, string, and type operators. Plus, tips and common error-prone cases.

  8. TypeScript Operators Tutorial

    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.

  9. TypeScript Operators

    Therefore, all typescript operators can be classified as one of the three : unary, binary, or ternary based on the number of operands it receives. Introduction. TypeScript operators can be classified into one of the following categories : Arithmetic operators; Relational/Comparision operators; Logical operators; Bitwise operators; Assignment ...

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

  11. TypeScript Tutorial

    This video is about Assignment Operators which are generally used in TypeScript.🔴TypeScript Tutorial : Beginner to Advanced🔴https://www.youtube.com/watch?v...

  12. Typescript Operators

    TypeScript Tutorial. Arithmetic Operators. A Typescript operators performs some operation on one or more operands and produces a result. The operand is the data or value on which an operation is to be done. For Example, in the expression 10+2 + is an operator, while 10 & 2 are the operands.

  13. Does Typescript support the ?. operator? (And, what's it called?)

    Yes. As of TypeScript 3.7 (released on November 5, 2019 ), this feature is supported and is called Optional Chaining: At its core, optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined.

  14. TypeScript

    Operator. Description. Example. = (Simple Assignment) Assigns values from the right side operand to the left side operand. C = A + B will assign the value of A + B into C. += (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. C += A is equivalent to C = C + A.

  15. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  16. Assignment Operators in TypeScript

    TypeScript assignment operators, including the basic assignment (=) and compound assignments (+=, -=, *=, /=, %=), provide a concise way to assign values and perform compound operations on variables. These operators enhance code readability and efficiency by combining assignment with arithmetic or modulus operations in a single step.

  17. What is the difference Between '!:' and '?:' in TypeScript object

    It's sort of a declaration-level version of the non-null assertion operator, but used on a property (can also be used on variables) rather than on an expression. There are two — or arguably three — errors in that example: Class should be class; JavaScript and TypeScript are case-sensitive.

  18. Nullish Coalescing: The ?? Operator in TypeScript

    Nullish Coalescing: The ?? Operator in TypeScript August 6, 2020. TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator.We can use this operator to provide a fallback value for a value that might be null or undefined. #Truthy and Falsy Values in JavaScript Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy ...

  19. Typescript literal types and addition assignment operators

    1) c += b; and a += a; are, in relation to the type checking process equal. The explanation whats going on could be found in 4). 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 ...

  20. TypeScript

    TypeScript. TypeScript is a programming language that adds static type checking to JavaScript. TypeScript is a superset of JavaScript, meaning that everything available in JavaScript is also available in TypeScript, and that every JavaScript program is a syntactically legal TypeScript program. Also, the runtime behavior of TypeScript and ...

  21. Assignment operator overloading in TypeScript

    how to use Addition assignment operator in typescript? 3. Typescript assignment chaining. Hot Network Questions Password change delay Who is the main manufacturer of jelly bean parts? How to identify small molecules in a structure without bonds If a I rent a car in Zurich, Switzerland, can I return the car in Lauterbrunnen? ...