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
  • TypeScript String toString() Method
  • TypeScript Pick<Type, Keys> Utility Type
  • TypeScript Array some() Method
  • TypeScript String matchAll() Method
  • TypeScript String split() Method
  • TypeScript Array.isArray() Method
  • How to Convert a Set to an Array in TypeScript ?
  • TypeScript Accessor
  • Optional Property Class in TypeScript
  • TypeScript String codePointAt() Method
  • TypeScript Array flat() Method
  • TypeScript Extract<Type, Union> Utility Type
  • How to Restrict a Number to a Certain Range in TypeScript ?
  • How to Create String Literal Union Type From Enum ?
  • TypeScript Array keys() Method
  • TypeScript | Array sort() Method
  • TypeScript | toPrecision() Function
  • TypeScript | toLocaleString() Function
  • Difference Between Const and Readonly in TypeScript

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

  • Web Technologies
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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 (935)
  • 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 (1191)
  • Virtual Reality (44)
  • Unreal Engine (39)

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)
  • 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

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 −

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.

assignment operator typescript

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.

assignment operator typescript

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.

assignment operator typescript

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

IMAGES

  1. TypeScript Tutorial

    assignment operator typescript

  2. TypeScript Operators

    assignment operator typescript

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

    assignment operator typescript

  4. C/C++ 中的赋值运算符

    assignment operator typescript

  5. Assignment Operators in C++

    assignment operator typescript

  6. Typescript For Beginners

    assignment operator typescript

VIDEO

  1. typescript and Node Js Assignment Exercise no 4 & 5 I Governor IT Course

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

  3. Q no 10 Typescript Assignment 45

  4. Typescript Q no 8 solved

  5. Typescript exercise assignment 1,2 and 3 Governor Sindh IT course

  6. Core

COMMENTS

  1. TypeScript: Playground Example - Logical Operators and Assignment

    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. Site Colours:

  2. Assignment Operators in TypeScript - TekTutorialsHub

    An assignment operators 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.

  3. TypeScript Operators - GeeksforGeeks

    In TypeScript, logical operators are used to perform logical operations on Boolean values. Name. Description. Syntax. Logical AND (&&) Returns true if both operands are true. result = operand1 && operand2; Logical OR (||) Returns true if at least one of the operands is true.

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

  5. Understanding TypeScript Operators - A Comprehensive Guide

    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.

  6. Assignment Operators in TypeScript - net-informations.com

    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.

  7. TypeScript - Assignment Operators Examples

    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.

  8. Getting To Know Typescript Operators In Depth - MarketSplash

    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.