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

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

18 JavaScript and TypeScript shorthands to know

typescript logical or assignment

Editor’s note: This guide to the most useful JavaScript and TypeScript shorthands was last updated on 3 January 2023 to address errors in the code and include information about the satisfies operator introduced in TypeScript v4.9.

18 JavaScript and TypeScript Shorthands to Know

JavaScript and TypeScript share a number of useful shorthand alternatives for common code concepts. Shorthand code alternatives can help reduce lines of code, which is something we typically strive for.

In this article, we will review 18 common JavaScript and TypeScript and shorthands. We will also explore examples of how to use these shorthands.

Read through these useful JavaScript and TypeScript shorthands or navigate to the one you’re looking for in the list below.

Jump ahead:

JavaScript and TypeScript shorthands

Ternary operator, short-circuit evaluation, nullish coalescing operator, template literals, object property assignment shorthand, optional chaining, object destructuring, spread operator, object loop shorthand, array.indexof shorthand using the bitwise operator, casting values to boolean with , arrow/lambda function expression, implicit return using arrow function expressions, double bitwise not operator, exponent power shorthand, typescript constructor shorthand, typescript satisfies operator.

Using shorthand code is not always the right decision when writing clean and scalable code . Concise code can sometimes be more confusing to read and update. So, it is important that your code is legible and conveys meaning and context to other developers.

Our decision to use shorthands must not be detrimental to other desirable code characteristics. Keep this in mind when using the following shorthands for expressions and operators in JavaScript and TypeScript.

All shorthands available in JavaScript are available in the same syntax in TypeScript. The only slight differences are in specifying the type in TypeScript, and the TypeScript constructor shorthand is exclusive to TypeScript.

The ternary operator is one of the most popular shorthands in JavaScript and TypeScript. It replaces the traditional if…else statement. Its syntax is as follows:

The following example demonstrates a traditional if…else statement and its shorthand equivalent using the ternary operator:

The ternary operator is great when you have single-line operations like assigning a value to a variable or returning a value based on two possible conditions. Once there are more than two outcomes to your condition, using if/else blocks are much easier to read.

Another way to replace an if…else statement is with short-circuit evaluation. This shorthand uses the logical OR operator || to assign a default value to a variable when the intended value is falsy.

The following example demonstrates how to use short-circuit evaluation:

This shorthand is best used when you have a single-line operation and your condition depends on the falseness or non-falseness of a value/statement.

The nullish coalescing operator ?? is similar to short-circuit evaluation in that it assigns a variable a default value. However, the nullish coalescing operator only uses the default value when the intended value is also nullish.

In other words, if the intended value is falsy but not nullish, it will not use the default value.

Here are two examples of the nullish coalescing operator:

Example one

Example two, logical nullish assignment operator.

This is similar to the nullish coalescing operator by checking that a value is nullish and has added the ability to assign a value following the null check.

The example below demonstrates how we would check and assign in longhand and shorthand using the logical nullish assignment:

JavaScript has several other assignment shorthands like addition assignment += , multiplication assignment *= , division assignment /= , remainder assignment %= , and several others. You can find a full list of assignment operators here .

Template literals, which was introduced as part of JavaScript’s powerful ES6 features , can be used instead of + to concatenate multiple variables within a string. To use template literals, wrap your strings in `` and variables in ${} within those strings.

The example below demonstrates how to use template literals to perform string interpolation:

You can also use template literals to build multi-line strings without using \n . For example:

Using template literals is helpful for adding strings whose values may change into a larger string, like HTML templates. They are also useful for creating multi-line string because string wrapped in template literals retain all white spacing and indentation.

In JavaScript and TypeScript, you can assign a property to an object in shorthand by mentioning the variable in the object literal. To do this, the variable must be named with the intended key.

See an example of the object property assignment shorthand below:

Dot notation allows us to access the keys or values of an object. With optional chaining , we can go a step further and read keys or values even when we are not sure whether they exist or are set.

When the key does not exist, the value from optional chaining is undefined . This helps us avoid unneeded if/else check conditions when reading values from objects and unnecessary try/catch to handle errors thrown from trying to access object keys that don’t exist.

See an example of optional chaining in action below:

Besides the traditional dot notation, another way to read the values of an object is by destructuring the object’s values into their own variables.

typescript logical or assignment

Over 200k developers use LogRocket to create better digital experiences

typescript logical or assignment

The following example demonstrates how to read the values of an object using the traditional dot notation compared to the shorthand method using object destructuring:

The spread operator … is used to access the content of arrays and objects. You can use the spread operator to replace array functions , like concat , and object functions, like object.assign .

Review the examples below to see how the spread operator can replace longhand array and object functions:

The traditional JavaScript for loop syntax is as follows:

We can use this loop syntax to iterate through arrays by referencing the array length for the iterator. There are three for loop shorthands that offer different ways to iterate through an array object:

  • for…of : To access the array entries
  • for…in : To access the indexes of an array and the keys when used on an object literal
  • Array.forEach : To perform operations on the array elements and their indexes using a callback function

Please note, Array.forEach callbacks have three possible arguments, which are called in this order:

  • The element of the array for the ongoing iteration
  • The element’s index
  • A full copy of the array

The examples below demonstrate these object loop shorthands in action:

We can look up the existence of an item in an array using the Array.indexOf method. This method returns the index position of the item if it exists in the array and returns -1 if it does not.

In JavaScript, 0 is a falsy value, while numbers less than or greater than 0 are considered truthy. Typically, this means we need to use an if…else statement to determine if the item exists using the returned index.

Using the bitwise operator ~ instead of an if…else statement allows us to get a truthy value for anything greater than or equal to 0 .

The example below demonstrates the Array.indexOf shorthand using the bitwise operator instead of an if…else statement:

In JavaScript, we can cast variables of any type to a Boolean value using the !![variable] shorthand.

See an example of using the !! [variable] shorthand to cast values to Boolean :

Functions in JavaScript can be written using arrow function syntax instead of the traditional expression that explicitly uses the function keyword. Arrow functions are similar to lambda functions in other languages .

Take a look at this example of writing a function in shorthand using an arrow function expression:

In JavaScript, we typically use the return keyword to return a value from a function. When we define our function using arrow function syntax, we can implicitly return a value by excluding braces {} .

For multi-line statements, such as expressions, we can wrap our return expression in parentheses () . The example below demonstrates the shorthand code for implicitly returning a value from a function using an arrow function expression:

In JavaScript, we typically access mathematical functions and constants using the built-in Math object. Some of those functions are Math.floor() , Math.round() , Math.trunc() , and many others.

The Math.trunc() (available in ES6) returns the integer part. For example, number(s) before the decimal of a given number achieves this same result using the Double bitwise NOT operator ~~ .

Review the example below to see how to use the Double bitwise NOT operator as a Math.trunc() shorthand:

It is important to note that the Double bitwise NOT operator ~~ is not an official shorthand for Math.trunc because some edge cases do not return the same result. More details on this are available here .

Another mathematical function with a useful shorthand is the Math.pow() function. The alternative to using the built-in Math object is the ** shorthand.

The example below demonstrates this exponent power shorthand in action:

There is a shorthand for creating a class and assigning values to class properties via the constructor in TypeScript . When using this method, TypeScript will automatically create and set the class properties . This shorthand is exclusive to TypeScript alone and not available in JavaScript class definitions.

Take a look at the example below to see the TypeScript constructor shorthand in action:

The satisfies operator gives some flexibility from the constraints of setting a type with the error handling covering having explicit types.

It is best used when a value has multiple possible types. For example, it can be a string or an array; with this operator, we don’t have to add any checks. Here’s an example:

In the longhand version of our example above, we had to do a typeof check to make sure palette.red was of the type RGB and that we could read its first property with at .

While in our shorthand version, using satisfies , we don’t have the type restriction of palette.red being string , but we can still tell the compiler to make sure palette and its properties have the correct shape.

The Array.property.at() i.e., at() method, accepts an integer and returns the item at that index. Array.at requires ES2022 target, which is available from TypeScript v4.6 onwards. More information is available here .

These are just a few of the most commonly used JavaScript and TypeScript shorthands.

JavaScript and TypeScript longhand and shorthand code typically work the same way under the hood, so choosing shorthand usually just means writing less lines of code. Remember, using shorthand code is not always the best option. What is most important is writing clean and understandable code that other developers can read easily.

What are your favorite JavaScript or TypeScript shorthands? Share them with us in the comments!

LogRocket : Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #typescript
  • #vanilla javascript

typescript logical or assignment

Stop guessing about your digital experience with LogRocket

Recent posts:.

Justin Kitagawa Leader Spotlight

Leader Spotlight: Riding the rocket ship of scale, with Justin Kitagawa

We sit down with Justin Kitagawa to learn more about his leadership style and approach for handling the complexities that come with scaling fast.

typescript logical or assignment

Nx adoption guide: Overview, examples, and alternatives

Let’s explore Nx features, use cases, alternatives, and more to help you assess whether it’s the right tool for your needs.

typescript logical or assignment

Understanding security in React Native applications

Explore the various security threats facing React Native mobile applications and how to mitigate them.

typescript logical or assignment

A guide to better state management with Preact Signals

Signals is a performant state management library with a set of reactive primitives for managing the application state.

typescript logical or assignment

8 Replies to "18 JavaScript and TypeScript shorthands to know"

Thanks you for your article, I learn a lot with it.

But I think that I found a mistake in short circuit evaluation. When you show the traditional version with if…else statement you use logical && operator but I think you wanted use logical || operator.

I think that is just a wrting error but i prefer tell it to you.

Have a good day

Hi Romain thank you for spotting that! I’ll fix it right away

I was avoiding using logical OR to make clear the explanation of short circuit evaluation, so the if statement should be confirming “str” has a valid value. I have switched the assignment statements in the condition so it is correct now.

I think there is an error in the renamed variable of destructured object. Shouldn’t the line const {x: myVar} = object be: const {x: myVar} = obj

This code doesn’t work in Typescript? // for object literals const obj2 = { a: 1, b: 2, c: 3 }

for (let keyLetter in obj2) { console.log(`key: ${keyLetter} value: ${obj2[keyLetter]}`);

Gets error: error: TS7053 [ERROR]: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ 0: number; 1: number; 2: number; }’. No index signature with a parameter of type ‘string’ was found on type ‘{ 0: number; 1: number; 2: number; }’. console.log(`key: ${keyLetter} value: ${obj2[keyLetter]}`);

Awesome information, thanks for sharing!!! 🚀🚀🚀

Good List of useful operators

~~x is not the same as Math.floor(x) : try it on negative numbers. You’ll find that ~~ is the same as Math.trunc(x) instead.

Leave a Reply Cancel reply

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

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

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

DEV Community

DEV Community

Emmanuel Fordjour  Kumah

Posted on Feb 6, 2022

What you should know about the Logical Assignment Operators in JavaScript

Hello World, every year, new features get added to the JavaScript language.This enables developers write better code which translates into awesome products.

In 2021, the Logical assignment operators were added to the language. Its main objective is to assign values to variables. In this post, we will learn how to effectively utilize the logical assignment operators. Let's get started.

The Logical assignment operators

ES2021 introduced three logical assignment operators:

  • Logical OR assignment operator ( ||= )
  • Logical AND assignment operator ( &&= )
  • Nullish coalesing assignment operator ( ??= )

The Logical assignment operators combine the logical operators and assignment expression. If you have forgotten what Logical operators are, here is my post on Logical Operators to help refresh your mind.

Alright, now let's discuss the Logical OR assignment operator ( ||= )

What is the logical OR assignment operator

The logical OR assignment operator (||=) accepts two operands and assigns the right operand to the left operand if the left operand is falsy

The syntax is as below

In the syntax, the ||= will only assign the value of y to x if x is falsy.

Let's take a look at the || operator first. The Logical OR operator || returns the * first * truthy value in an expression.

Consider an example below

The output will be Guest .

  • In the example above, the firstName variable is an empty string "" , and the noName variable is a string ( a string stores a sequence of characters).
  • Empty strings "" are considered falsy values while non-empty strings(eg. "emma" ) are truthy values.
  • Because the || operator returns the first truthy value , the value stored in the noName variable (ie. Guest ) will logged to the console.

Note that : 0 , null , undefined , NaN and "" are classified as falsy values.

Assigning a value to a variable using the ||= operator.

Consider a situation where you want to assign a truthy value to a variable storing a falsy value

Let's see how you can achieve that using the logical OR assignment operator ( ||= )

You can do this (long method)

Let's understand the code above

  • The expression on the right : firstName || noName is evaluated first.
  • Since the || operator returns the first truthy value, it will return the value Guest
  • Using the = (assignment operator), the value Guest is then assigned to the firstName variable which has a falsy value
  • Now, anytime we console.log(firstName) , we get the value Guest

The example above can be simplified using the logical OR assignment operator ( ||= ).

The output will be

-The truthy value of 28 will be assigned to the age variable which has a falsy value

  • The age now has a value of 28

You can also assign a truthy value to a property in an object if the property is falsy . Take a look at the code below

In the example above

  • The || operator evaluates the expression and returns the firsty truthy value ( "emma" )
  • The truthy value is now assigned to the userDetails.username property since userDetails.username is falsy

If the first operand is a truthy value, the logical OR assignment operator ( ||= ) will** not assign the value of the second operand to the first. **

Consider the code below

  • Because the userDetails.userName property is truthy , the second operand was not evaluated

In summary, the x ||= y will assign the value of y to x if x is falsy .

Using the Logical AND assignment operator ( &&= )

Sometimes you may want to assign a value to a variable even if the initial variable has a value. This is where the logical AND assignment operator ( &&= ) comes in.

What is the logical AND assignment operator ?

The logical AND assignment operator only assigns y to x if x is truthy

* The syntax is as below *

  • if the operand on the left side is truthy , the value of y is then assigned to x

Let's see how this was done previously

The output will be efk .

  • The if evaluates the condition in the parenthesis ()
  • If the condition is true then the expression inside the curly braces {} gets evaluated
  • Because the firstName is truthy , we assign the value of userName to firstName .

Using &&= in the same example as above

  • Because firstName is a truthy value, the value of userName is now assigned to firstName

The &&= operator is very useful for changing values. Consider the example below

  • userDetails.lastName is a truthy value hence the right operand Fordjour is assigned to it.

In the code below, we given an object, and our task is to change the id to a random number between 1 and 10.

Let's see how that can be done using the &&=

The output will vary depending on the random number returned, here is an example.

In summary, the &&= operator assigns the value of the right operand to the left operand if the left operand is truthy

The nullish coalescing assignment operator ( ??= )

The nullish coalescing assignment operator only assigns y to x if x is null or undefined .

Let's see how to use the nullish coalescing assignment operator

  • The firstName variable is undefined
  • We now assign the value of the right operand to firstName
  • firstName now has the value of Emmanuel .

Adding a missing property to an object

  • The userDetails.userName is undefined hence nullish
  • The nullish coalescing assignment operator ??= then assigns the string Guest to the userDetails.userName
  • Now the userDetails object has property userName .
  • The logical OR assignment (x ||= y) operator only assigns y to x if x is falsy .
  • The logical AND assignment (x &&=y) operator will assign y to x if x is truthy
  • The nullish coalescing assignment operator will assign y to x if x is undefined or null .

I trust you have learnt something valuable to add to your coding repository. Is there anything that wasn't clear to you ? I would love to read your feedback on the article.

Writing with love from Ghana. Me daa se (Thank you)

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

leemeganj profile image

Using react-to-print to generate a printable document

Megan Lee - Mar 28

akchauhan2 profile image

Getting Started with React: A Beginner's Guide

Ajay Chauhan - Mar 27

robsonmuniz16 profile image

Mastering Animated Navigation with JavaScript | Web Development Tutorial for Beginners

Robson Muniz - Mar 27

kinxyzz profile image

React UseEffect

kinxyzz - Mar 23

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Nullish coalescing assignment (??=)

The nullish coalescing assignment ( ??= ) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ).

Description

Nullish coalescing 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 nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

In fact, if x is not nullish, y is not evaluated at all.

Using nullish coalescing assignment

You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values , ??= also applies the default value if the property has value null .

Specifications

Browser compatibility.

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

  • Nullish coalescing operator ( ?? )

Common TypeScript Issues NÂş 1: assignments within sub-expressions

Blog Author Phil Nash

Developer Advocate JS/TS

typescript logical or assignment

We've been counting down our top 5 issues that SonarLint catches in TypeScript projects, and we've reached the top of the list. This issue is outstanding in its simplicity and potential to cause very hard-to-spot bugs.

Grab your editor and install SonarLint if you don't already have it. You can then copy and paste the example code below to try these for yourself. This particular issue applies to JavaScript codebases as well as TypeScript. 

.css-1s68n4h{position:absolute;top:-150px;} NÂş 1: assignments within sub-expressions .css-5cm1aq{color:#000000;} .css-h4dt40{margin-left:10px;margin-top:-1px;display:inline-block;fill:#5F656D;margin-top:-2px;height:16px;width:16px;}.css-h4dt40:hover{fill:#290042;}

Have you ever written a conditional and then tested it out to find that it was not behaving how you'd expected it to? Whether or not the expression in the conditional is true or false, the code inside the conditional is still running. You go back to the code, checking every part of the expression and tracing the values back through the code. You verify everything is correct about it. You take one last look at it, ready to bang your head against the desk, close your laptop and go home for the day.

Finally, you spot it. The bug. There it is:

Inside the expression lies a single equals sign, the assignment operator. The sub-expression isn't checking whether the two variables are equal, it is assigning one to the other, and the conditional is being evaluated based on whether theOtherThing is a truthy value. 

The expression is missing an = (or perhaps two). It's a pain of a bug to figure out, it can take a long time to spot the last mistake you'd thought you'd make, and when you do find it, you kick yourself.

It's easy to spot in an isolated example like this but consider a more fully formed function:

It's not so obvious that the function above reassigns the method variable to the string GET and will always make a GET request regardless of the method supplied.

That's why assignment within sub-expressions is our number one issue discovered by SonarLint in TypeScript projects. Thankfully there aren't too many of these bugs in the wild, because they get caught by testing, linting, or by tooling like SonarLint. But between hunting for the bug or it being flagged in my editor as soon as I make the mistake, I know which I'd prefer.

Other causes .css-1jw8ybl{margin-left:10px;margin-top:-1px;display:inline-block;fill:#5F656D;margin-left:14px;}.css-1jw8ybl:hover{fill:#290042;}

Assigning inside a conditional is normally a bug, but there are other sub-expressions that assignments can crop up in. In these cases, the issue is less about correctness and more about readability.

Consider an example like this calculator class:

You can use it like so:

Each time you use the add or subtract methods the object returns the result, but also sets that result in an instance variable. In both functions, this is done in one line, conflating returning the value with storing it.

There is no bug here, the object works as expected, but this issue lies in the readability of the functions. It is unexpected to find an assignment in a return statement, and when you do you then need to read over the assignment in order to see the actual return value. This might be useful if you are trying to golf your code, but things are much more readable if you assign in one statement and then return the value in another.

While this is a relatively simple example, I have seen plenty of versions of this in real codebases where assigning and returning make reading the result much harder. In each of these cases, it is possible to make the assignment on one line and then return the result on the next line. It's more explicit and thus clearer to someone else reading the code.

Install SonarLint in your editor and you'll get notified if you accidentally assign inside of a conditional , avoiding those bugs, or if you're affecting readability by assigning within another expression .

That's a wrap

That's our countdown of the top 5 common issues we've found in TypeScript projects with SonarLint. Over this series we've covered:

5. Optional property declarations

4. Creating and dropping objects immediately

3. Unused local variables and functions

2. Non-empty statements

and, finally, today's issue

1. Assignments within sub-expressions 

I hope this has been an interesting trip through some of the issues you might have encountered in your own TypeScript, and hopefully cleared up before you commit. Check out the full set of TypeScript rules to see what other issues SonarLint can help you avoid. And if there are any rules you think should have made this top 5, let us know on Twitter at @SonarSource or in the community .

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

IMAGES

  1. Logical Operators in TypeScript

    typescript logical or assignment

  2. TypeScript Function Types: A Beginner's Guide

    typescript logical or assignment

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

    typescript logical or assignment

  4. TypeScript Tutorial

    typescript logical or assignment

  5. How to Use TypeScript with React Components

    typescript logical or assignment

  6. What is TypeScript? A Comprehensive Guide

    typescript logical or assignment

VIDEO

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

  2. Typescript Type System explained by Anders Hejlsberg

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

  4. Typescript Q no 8 solved

  5. GI-AIWMD

  6. Logical

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

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

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

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

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

  7. 18 JavaScript and TypeScript shorthands to know

    Object property assignment shorthand. In JavaScript and TypeScript, you can assign a property to an object in shorthand by mentioning the variable in the object literal. To do this, the variable must be named with the intended key. See an example of the object property assignment shorthand below: // Longhand const obj = { x: 1, y: 2, z: 3 }

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

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

  10. Logical Operators in Typescript

    Bitwise Operators. The Logical operators operate on a set of operands and return one of the operands as a return value. It is typically used on boolean operands, in which case the return value is a boolean. If the operands and not boolean values, then logical operators may return a non-boolean value. The Typescript has four logical operators.

  11. Logical OR (||)

    The logical OR (||) (logical disjunction) operator for a set of operands is true if and only if one or more of its operands is true. It is typically used with boolean (logical) values. When it is, it returns a Boolean value. However, the || operator actually returns the value of one of the specified operands, so if this operator is used with non-Boolean values, it will return a non-Boolean value.

  12. Typescript assigning value to variable with logical operators

    1 Answer. Whilst your code is using Typescript, this question actually concerns JavaScript. will cause the expression to be evalauted. this will evaluate to false causing the expression to not be evaulated. Hence in your constructor, if obj is truthy (e.g. neither null or undefined) the expression will be evaluated, in this case accessing the ...

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

  14. Assignment Operators in TypeScript

    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.

  15. What you should know about the Logical Assignment Operators in

    Hello World, every year, new features get added to the JavaScript language.This enables developers write better code which translates into awesome products. In 2021, the Logical assignment operators were added to the language. Its main objective is to assign values to variables. In this post, we will learn how to effectively utilize the logical ...

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

  17. Common TypeScript issues No.1: assignments within sub-expressions

    That's a wrap. That's our countdown of the top 5 common issues we've found in TypeScript projects with SonarLint. Over this series we've covered: 5. Optional property declarations. 4. Creating and dropping objects immediately. 3. Unused local variables and functions.

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

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

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

  21. javascript

    Typescript assigning a variable's value through logical operator uses only latter type. Ask Question Asked 4 years, 1 month ago. Modified 4 years, ... otherwise to defaultNotification, hence I use the logical OR operator in assignment, as: const notification = customNotification || notificationDefault; ...