Michael Wanyoike

25+ JavaScript Shorthand Coding Techniques

Share this article

Child between piles of books

1. The Ternary Operator

2. short-circuit evaluation shorthand, 3. declaring variables shorthand, 4. if presence shorthand, 5. javascript for loop shorthand, 6. short-circuit evaluation, 7. decimal base exponents, 8. object property shorthand, 9. arrow functions shorthand, 10. implicit return shorthand, 11. default parameter values, 12. template literals, 13. destructuring assignment shorthand, 14. multi-line string shorthand, 15. spread operator shorthand, 16. mandatory parameter shorthand, 17. array.find shorthand, 18. object [key] shorthand, 19. double bitwise not shorthand, 20. exponent power shorthand, 21. converting a string into a number, 22. object property assignment, 23. bitwise indexof shorthand, 24. object.entries(), 25. object.values(), 26. suggest one, faqs about javascript shorthand coding techniques.

This really is a must read for any JavaScript developer. We’ve written this guide to shorthand JavaScript coding techniques that we’ve picked up over the years. To help you understand what is going on, we’ve included the longhand versions to give some coding perspective.

If you want to learn more about ES6 and beyond, check out JavaScript: Novice to Ninja, 2nd Edition .

This is a great code saver when you want to write an if..else statement in just one line.

You can also nest your if statement like this:

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

Don’t believe me? Test it yourself (paste the following code in es6console ):

Do note that if you set variable1 to false or 0 , the value bar will be assigned.

It’s good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.

This might be trivial, but worth a mention. When doing “ if checks”, assignment operators can sometimes be omitted.

Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value .

Here is another example. If a is NOT equal to true, then do something.

This little tip is really useful if you want plain JavaScript and don’t want to rely on external libraries such as jQuery or lodash.

If you just wanted to access the index, do:

This also works if you want to access keys in a literal object:

Shorthand for Array.forEach:

Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.

You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000.

Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation.

Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.

It’s important to note that the value of this inside an arrow function is determined differently than for longhand functions, so the two examples are not strictly equivalent. See this article on arrow function syntax for more details.

Return is a keyword we use often to return the final result of a function. An arrow function with a single statement will implicitly return the result its evaluation (the function must omit the braces ( {} ) in order to omit the return keyword).

To return a multi-line statement (such as an object literal), it’s necessary to use () instead of {} to wrap your function body. This ensures the code is evaluated as a single statement.

You can use the if statement to define default values for function parameters. In ES6, you can define the default values in the function declaration itself.

Aren’t you tired of using ' + ' to concatenate multiple variables into a string? Isn’t there a much easier way of doing this? If you are able to use ES6, then you are in luck. All you need to do is use is the backtick, and ${} to enclose your variables.

If you are working with any popular web framework, there are high chances you will be using arrays or data in the form of object literals to pass information between components and APIs. Once the data object reaches a component, you’ll need to unpack it.

You can even assign your own variable names:

If you have ever found yourself in need of writing multi-line strings in code, this is how you would write it:

But there is an easier way. Just use backticks.

The spread operator , introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.

Unlike the concat() function, you can use the spread operator to insert an array anywhere inside another array.

You can also combine the spread operator with ES6 destructuring notation:

By default, JavaScript will set function parameters to undefined if they are not passed a value. Some other languages will throw a warning or error. To enforce parameter assignment, you can use an if statement to throw an error if undefined , or you can take advantage of the ‘Mandatory parameter shorthand’.

If you have ever been tasked with writing a find function in plain JavaScript, you would probably have used a for loop. In ES6, a new array function named find() was introduced.

Did you know that Foo.bar can also be written as Foo['bar'] ? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing re-usable code.

Consider this simplified example of a validation function:

This function does its job perfectly. However, consider a scenario where you have very many forms where you need to apply the validation but with different fields and rules. Wouldn’t it be nice to build a generic validation function that can be configured at runtime?

Now we have a validate function we can reuse in all forms without needing to write a custom validation function for each.

Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Besides, who wants to work with ones and zeroes if you are not dealing with binary?

There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor() . The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here .

Shorthand for a Math exponent power function:

There are times when your code receives data that comes in String format but needs to processed in Numerical format. It’s not a big deal, we can perform a quick conversion.

Consider the following piece of code:

How would you merge them into one object? One way is to write a function that copies data from the second object onto the first one. Unfortunately, this might not be what you want — you may need to create an entirely new object without mutating any of the existing objects. The easiest way is to use the Object.assign function introduced in ES6:

You can also use the object destruction notation introduced in ES8:

There is no limit to the number of object properties you can merge. If you do have objects with identical property names, values will be overwritten in the order they were merged.

When performing a lookup using an array, the indexOf() function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1 is returned. In JavaScript, 0 is considered ‘falsy’, while numbers greater or lesser than 0 are considered ‘truthy’. As a result, one has to write the correct code like this.

The bitwise(~) operator will return a truthy value for anything but -1 . Negating it is as simple as doing !~ . Alternatively, we can also use the includes() function:

This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array. See the example below:

This is also a new feature introduced in ES8 that performs a similar function to Object.entries() , but without the key part:

I really do love these and would love to find more, so please leave a comment if you know of one!

What are some of the most common shorthand techniques in JavaScript?

JavaScript shorthand techniques are a way to write more efficient and cleaner code. Some of the most common shorthand techniques include the Ternary Operator, which is a shorter way of writing an if-else statement, and the Nullish Coalescing Operator, which returns the first argument if it’s not null or undefined. Other common shorthand techniques include the Optional Chaining Operator, which allows you to access deeply nested object properties without checking if each property exists, and the Logical OR Assignment (||=), which assigns a value to a variable only if the variable is nullish.

How can shorthand techniques save time when coding in JavaScript?

Shorthand techniques can significantly reduce the amount of code you need to write, making your code more readable and easier to maintain. They can also make your code run faster, as less code means less processing time. Additionally, shorthand techniques can help prevent errors, as they often include built-in error checking.

Are there any drawbacks to using shorthand techniques in JavaScript?

While shorthand techniques can make your code more efficient and easier to read, they can also make it more difficult for beginners to understand. If you’re working on a team with less experienced developers, you may need to spend extra time explaining how these techniques work. Additionally, some shorthand techniques may not be supported in older browsers, so you’ll need to make sure your code is compatible with the browsers your audience is using.

Can you provide some examples of how to use shorthand techniques in JavaScript?

Sure, here are a few examples. To use the Ternary Operator, you could write `let result = (a > b) ? ‘a is greater’ : ‘b is greater’;` instead of using a full if-else statement. To use the Nullish Coalescing Operator, you could write `let result = a ?? ‘default’;` to assign a default value to a variable if it’s null or undefined.

What are some resources for learning more about shorthand techniques in JavaScript?

There are many online resources for learning about JavaScript shorthand techniques. The Mozilla Developer Network (MDN) has comprehensive documentation on JavaScript, including a section on shorthand techniques. You can also find tutorials and articles on websites like SitePoint, Plain English, and Geeks for Geeks.

How can I practice using shorthand techniques in JavaScript?

The best way to practice using shorthand techniques is to incorporate them into your own code. Try rewriting some of your existing code using these techniques, and see how it affects the readability and efficiency of your code. You can also try solving coding challenges on websites like HackerRank or LeetCode, which can help you get comfortable with these techniques in a variety of contexts.

Are shorthand techniques used in other programming languages?

Yes, shorthand techniques are used in many other programming languages, including Python, Ruby, and C++. While the specific techniques and syntax may vary, the underlying principles are the same: to write more efficient, readable code.

How can I remember all the different shorthand techniques in JavaScript?

It can be challenging to remember all the different shorthand techniques, especially if you’re new to JavaScript. One strategy is to focus on learning one technique at a time, and practice using it until it becomes second nature. You can also keep a cheat sheet handy for quick reference.

Can shorthand techniques affect the performance of my JavaScript code?

Yes, shorthand techniques can improve the performance of your code by reducing the amount of code that needs to be processed. However, the impact on performance is usually minimal, and it’s more important to focus on writing clear, maintainable code.

Are there any shorthand techniques that are considered bad practice?

While most shorthand techniques are considered good practice, there are a few that can be confusing or lead to unexpected behavior. For example, using the ‘==’ operator for equality checks can lead to unexpected type coercion, so it’s generally recommended to use the ‘===’ operator instead. Similarly, using the ‘&&’ operator for conditional execution can be confusing if you’re not familiar with how it works. It’s always important to understand how a shorthand technique works before using it in your code.

I write clean, readable and modular code. I love learning new technologies that bring efficiencies and increased productivity to my workflow.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

SitePoint Premium

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

shorthand assignment js

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.

shorthand assignment js

Over 200k developers use LogRocket to create better digital experiences

shorthand assignment js

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

shorthand assignment js

Stop guessing about your digital experience with LogRocket

Recent posts:.

Comparing Mutative Vs Immer Vs Reducers For Data Handling In React

Comparing React state tools: Mutative vs. Immer vs. reducers

Mutative processes data with better performance than both Immer and native reducers. Let’s compare these data handling options in React.

shorthand assignment js

Radix UI adoption guide: Overview, examples, and alternatives

Radix UI is quickly rising in popularity and has become an excellent go-to solution for building modern design systems and websites.

shorthand assignment js

Understanding the CSS revert-layer keyword

In this article, we’ll explore CSS cascade layers — and, specifically, the revert-layer keyword — to help you refine your styling strategy.

shorthand assignment js

Exploring Nushell, a Rust-powered, cross-platform shell

Nushell is a modern, performant, extensible shell built with Rust. Explore its pros, cons, and how to install and get started with it.

shorthand assignment js

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

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript assignment, javascript assignment operators.

Assignment operators assign values to JavaScript variables.

Shift Assignment Operators

Bitwise assignment operators, logical assignment operators, the = operator.

The Simple Assignment Operator assigns a value to a variable.

Simple Assignment Examples

The += operator.

The Addition Assignment Operator adds a value to a variable.

Addition Assignment Examples

The -= operator.

The Subtraction Assignment Operator subtracts a value from a variable.

Subtraction Assignment Example

The *= operator.

The Multiplication Assignment Operator multiplies a variable.

Multiplication Assignment Example

The **= operator.

The Exponentiation Assignment Operator raises a variable to the power of the operand.

Exponentiation Assignment Example

The /= operator.

The Division Assignment Operator divides a variable.

Division Assignment Example

The %= operator.

The Remainder Assignment Operator assigns a remainder to a variable.

Remainder Assignment Example

Advertisement

The <<= Operator

The Left Shift Assignment Operator left shifts a variable.

Left Shift Assignment Example

The >>= operator.

The Right Shift Assignment Operator right shifts a variable (signed).

Right Shift Assignment Example

The >>>= operator.

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

Unsigned Right Shift Assignment Example

The &= operator.

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.

Bitwise AND Assignment Example

The |= operator.

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

Bitwise OR Assignment Example

The ^= operator.

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

Bitwise XOR Assignment Example

The &&= operator.

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned.

Logical AND Assignment Example

The &&= operator is an ES2020 feature .

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

Logical OR Assignment Example

The ||= operator is an ES2020 feature .

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

Nullish Coalescing Assignment Example

The ??= operator is an ES2020 feature .

Test Yourself With Exercises

Use the correct assignment operator that will result in x being 15 (same as x = x + y ).

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Web Development

JavaScript Shorthand Coding Techniques

  • Daniyal Hamid
  • 31 May, 2020
  • 12 min read

This article includes a round-up of some popular JavaScript shorthand coding techniques for beginners, which can be good for code optimization or minification purposes.

Assignment Operators Shorthand

Boolean comparison shorthand.

The conventional way:

The shortcut way:

Get a Character From String Shorthand

Create a link shorthand.

Although, the link() method has good browser support, still you should use it with caution as it is not a part of the standards, and may not work as expected in all browsers.

Create an Array Shorthand

Create an object shorthand.

Please note that leaving a trailing comma before the closing curly brace can cause a problem in IE when declaring object properties.

Regular Expressions Testing Shorthand

Shorthand using the comma operator.

The comma operator evaluates each of its operands (from left-to-right) and returns the value of the last operand. This means that the following (and much more) is possible:

Consider another example where we process operands before returning. As stated, only the last operand will be returned but all others are going to be evaluated as well.

Using the Ternary (conditional) Operator

Common usage:.

The ternary operator is usually used as a shortcut for if else statement.

Other Usage:

Ternary operator can be used to shorten function calling. For example, conventionally if we do:

This can be re-written in a shorter way as:

Similarly, we can use the same technique with objects to dynamically select a specific object property based on a condition, for example:

Ternary evaluations can also be used to perform different operations, for example:

More than one operation can be evaluated as well for each case by grouping operations using () (brackets) and separating each one with a , (comma operator), like so:

Remember that the comma operator evaluates all operands but returns only the last.

Shorthand Coding With Truthy and Falsy

In JavaScript, all values are truthy unless they are defined as falsy :

Truthy (values that evaluate to true ):

Falsy (values that evaluate to false ):.

Please note that there are a few other values (that are not very commonly used) that are considered falsy in JavaScript. If you wish to learn more about falsy values in JavaScript, then check out another post dedicated to that topic .

With that information, code like the following is possible:

indexOf() Shorthand

String contains:, string does not contain:.

This works because ~ is a bitwise negation operator which inverts the binary digits of an operand. To make things simple, bitwise NOT-ing any number n yields -(n + 1) . For example, ~5 yields -6 . That means when indexOf returns -1 the bitwise negation of that ( ~-1 ) equals 0 which is falsy value in JavaScript, which makes the boolean evaluation equal false . This also means that all non-zero values would be truthy.

Type Casting Shorthands

Converting to boolean:.

By converting a value into strict Boolean data type, we can check whether it evaluates to truthy or falsy. A quick way to do this is to use the negation operator ( ! ):

Similarly, if we wanted to check if a value is non-falsy (or truthy), we could use the negation operator twice, like so:

Converting to Number:

The unary plus ( + ) operator precedes its operand and evaluates it, but attempts to convert it into a number if it isn't already. Although unary negation ( - ) can also convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values such as true , false , and null .

Converting to String:

It can convert integers and floats, as well as the non-string values such as 0 , true , false , null , undefined , and NaN .

Self-Calling Anonymous Functions

Also known as Immediately Invoked Function Expression (IIEF), these are self-calling anonymous functions that execute automatically when the code is parsed by the browser for the first time. It has the following syntax:

These anonymous functions can be useful to encapsulate code in its own namespace and protect code against variable name clashes.

This style of anonymous function wrapping is especially useful when working with multiple JavaScript libraries to avoid conflicting code. Consider the following example for jQuery JavaScript library:

We pass the jQuery JavaScript object as an argument to the anonymous function, which allows us to use $ within the function expression without raising any potential conflicts with other code elsewhere in the document.

Other Syntax:

There are other ways to evaluate and directly call the function expression which, while different in syntax, behave the same way.

Shorthand Coding by Short-Circuiting Evaluations

The boolean operators && (AND) and || (OR) perform short-circuited evaluation, which means when evaluating boolean operators, only as many arguments are evaluated as necessary to determine the outcome of a boolean expression.

As logical expressions are evaluated left-to-right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && (anything) is short-circuit evaluated to false .
  • true || (anything) is short-circuit evaluated to true .

For example, in the conjunction x && y , if x evaluates to false , the whole expression will be false , regardless of what the other argument evaluates to. Similarly, for a disjunction x || y , if the first argument evaluates to true , the whole expression will be true , regardless of what the other argument evaluates to. The following truth table illustrates this AND and OR boolean logic:

With that knowledge, consider the following conventional code:

That can be re-written in a shorter way as such:

Keep in mind that the && and || logical operators in JavaScript themselves do not return a boolean value ( true or false ), but instead the value of the last operand they evaluate.

Therefore, the shorthand code above evaluates to 1 because count is null which is a falsy value, so the || (OR) logical operator moves to evaluate the second operand which is a truthy value 1 .

Specifying Default Values:

Using short-circuiting technique can be a good way for specifying default values to variables:

You should note though, that all falsy values (which includes the number 0 ) will be evaluated as false . So, if in the code above, value of b was passed as the number 0 it would return the string "hello world" instead which might not be the result you expect in some cases.

Set Value If Truthy:

The variable b would only be of type string if a is a truthy value. Consider the case below where a is undefined (falsy):

Eager (Non-Short-Circuited) Evaluations

There may be some instances where we may want to have non-short-circuited or eager evaluation, i.e. we would like to continue evaluating operands even if the first operand in the boolean conjunction x && y evaluates to false , or conversely the first boolean operand in the disjunction x || y evaluates to true .

In JavaScript, we could use the bitwise operators & and | which are eager, and yield identical truth tables:

In the table you'll notice that & and | bitwise operators yield identical truth tables to the && and || logical operators, with the exception being that the result of short-circuited evaluation produces boolean values ( true or false ) while the result of the eager evaluation produces integer values ( 0 or 1 ).

The important difference to notice here is that the bitwise operators return 1 or 0 . In order to conduct boolean evaluations, we need to convert them into strict boolean types. This is possible since the result of the bit-wise operators is identical to the truth tables of && and || logical operators. Therefore, we can simply type cast these into strict boolean types by using double not ( !! ) which would yield the following truth table:

So, the main difference here is & and | do not do short-circuit evaluation in boolean expressions, which means:

  • While && will stop evaluating if the first operand is false , & won't.
  • While || will stop evaluating if the first operand is true , | won't.

This could be very useful, especially in cases where we want to evaluate all operands regardless of their boolean outcome. One such instance could be form validation, where we may not want to stop after encountering the first invalid field (which is what may happen in a short-circuited evaluation). We may instead want to validate all fields to highlight to the user all the invalid ones. Consider the following jQuery example:

The eager evaluation code helps us evaluate all fields and accordingly adds or removes the invalid class on all invalid fields. The form is only submitted when the conjunction is true .

The same example in short-circuited evaluation would have stopped after the first invalid field.

This post was published 31 May, 2015 (and was last revised 31 May, 2020 ) by Daniyal Hamid . Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post .

  • Skip to main content
  • Select language
  • Skip to search
  • Expressions and operators
  • Operator precedence

Left-hand-side expressions

« Previous Next »

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

A complete and detailed list of operators and expressions is also available in the reference .

JavaScript has the following types of operators. This section describes the operators and contains information about operator precedence.

  • Assignment operators
  • Comparison operators
  • Arithmetic operators
  • Bitwise operators

Logical operators

String operators, conditional (ternary) operator.

  • Comma operator

Unary operators

  • Relational operator

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3+4 or x*y .

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x .

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Note:  ( => ) is not an operator, but the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations (+, -, * /), JavaScript provides the arithmetic operators listed in the following table:

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer: Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation).

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

The shift operators are listed in the following table.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

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

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) simply evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

The fourth form is legal only within a with statement, to delete a property from an object.

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

If the delete operator succeeds, it sets the property or element to undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

When you delete an array element, the array length is not affected. For example, if you delete a[3] , a[4] is still a[4] and a[3] is undefined.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete . However, trees[3] is still addressable and returns undefined .

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined , but the array element still exists:

The typeof operator is used in either of the following ways:

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator is used in either of the following ways:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined , which has no effect in JavaScript.

The following code creates a hypertext link that submits a form when the user clicks it.

Relational operators

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

The following table describes the precedence of operators, from highest to lowest.

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference .

  • Expressions

An expression is any valid unit of code that resolves to a value.

Every syntactically valid expression resolves to some value but conceptually, there are two types of expressions: with side effects (for example: those that assign value to a variable) and those that in some sense evaluates and therefore resolves to value.

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to seven.

The code 3 + 4 is an example of the second expression type. This expression uses the + operator to add three and four together without assigning the result, seven, to a variable. JavaScript has the following expression categories:

  • Arithmetic: evaluates to a number, for example 3.14159. (Generally uses arithmetic operators .)
  • String: evaluates to a character string, for example, "Fred" or "234". (Generally uses string operators .)
  • Logical: evaluates to true or false. (Often involves logical operators .)
  • Primary expressions: Basic keywords and general expressions in JavaScript.
  • Left-hand-side expressions: Left values are the destination of an assignment.

Primary expressions

Basic keywords and general expressions in JavaScript.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

  • Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

Comprehensions

Comprehensions are an experimental JavaScript feature, targeted to be included in a future ECMAScript version. There are two versions of comprehensions:

Comprehensions exist in many programming languages and allow you to quickly assemble a new array based on an existing one, for example.

Left values are the destination of an assignment.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

Spread operator

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

Example: Today if you have an array and want to create a new array with the existing one being part of it, the array literal syntax is no longer sufficient and you have to fall back to imperative code, using a combination of push , splice , concat , etc. With spread syntax this becomes much more succinct:

Similarly, the spread operator works with function calls:

Document Tags and Contributors

  • l10n:priority
  • JavaScript basics
  • JavaScript first steps
  • JavaScript building blocks
  • Introducing JavaScript objects
  • Introduction
  • Grammar and types
  • Control flow and error handling
  • Loops and iteration
  • Numbers and dates
  • Text formatting
  • Regular expressions
  • Indexed collections
  • Keyed collections
  • Working with objects
  • Details of the object model
  • Iterators and generators
  • Meta programming
  • A re-introduction to JavaScript
  • JavaScript data structures
  • Equality comparisons and sameness
  • Inheritance and the prototype chain
  • Strict mode
  • JavaScript typed arrays
  • Memory Management
  • Concurrency model and Event Loop
  • References:
  • ArrayBuffer
  • AsyncFunction
  • Float32Array
  • Float64Array
  • GeneratorFunction
  • InternalError
  • Intl.Collator
  • Intl.DateTimeFormat
  • Intl.NumberFormat
  • ParallelArray
  • ReferenceError
  • SIMD.Bool16x8
  • SIMD.Bool32x4
  • SIMD.Bool64x2
  • SIMD.Bool8x16
  • SIMD.Float32x4
  • SIMD.Float64x2
  • SIMD.Int16x8
  • SIMD.Int32x4
  • SIMD.Int8x16
  • SIMD.Uint16x8
  • SIMD.Uint32x4
  • SIMD.Uint8x16
  • SharedArrayBuffer
  • StopIteration
  • SyntaxError
  • Uint16Array
  • Uint32Array
  • Uint8ClampedArray
  • WebAssembly
  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • parseFloat()
  • Array comprehensions
  • Conditional (ternary) Operator
  • Destructuring assignment
  • Expression closures
  • Generator comprehensions
  • Legacy generator function expression
  • Logical Operators
  • Object initializer
  • Property accessors
  • Spread syntax
  • async function expression
  • class expression
  • delete operator
  • function expression
  • function* expression
  • in operator
  • new operator
  • void operator
  • Legacy generator function
  • async function
  • for each...in
  • function declaration
  • try...catch
  • Arguments object
  • Arrow functions
  • Default parameters
  • Method definitions
  • Rest parameters
  • constructor
  • element loaded from a different domain for which you violated the same-origin policy.">Error: Permission denied to access property "x"
  • InternalError: too much recursion
  • RangeError: argument is not a valid code point
  • RangeError: invalid array length
  • RangeError: invalid date
  • RangeError: precision is out of range
  • RangeError: radix must be an integer
  • RangeError: repeat count must be less than infinity
  • RangeError: repeat count must be non-negative
  • ReferenceError: "x" is not defined
  • ReferenceError: assignment to undeclared variable "x"
  • ReferenceError: can't access lexical declaration`X' before initialization
  • ReferenceError: deprecated caller or arguments usage
  • ReferenceError: invalid assignment left-hand side
  • ReferenceError: reference to undefined property "x"
  • SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
  • SyntaxError: "use strict" not allowed in function with non-simple parameters
  • SyntaxError: "x" is a reserved identifier
  • SyntaxError: JSON.parse: bad parsing
  • SyntaxError: Malformed formal parameter
  • SyntaxError: Unexpected token
  • SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
  • SyntaxError: a declaration in the head of a for-of loop can't have an initializer
  • SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
  • SyntaxError: for-in loop head declarations may not have initializers
  • SyntaxError: function statement requires a name
  • SyntaxError: identifier starts immediately after numeric literal
  • SyntaxError: illegal character
  • SyntaxError: invalid regular expression flag "x"
  • SyntaxError: missing ) after argument list
  • SyntaxError: missing ) after condition
  • SyntaxError: missing : after property id
  • SyntaxError: missing ; before statement
  • SyntaxError: missing = in const declaration
  • SyntaxError: missing ] after element list
  • SyntaxError: missing formal parameter
  • SyntaxError: missing name after . operator
  • SyntaxError: missing variable name
  • SyntaxError: missing } after function body
  • SyntaxError: missing } after property list
  • SyntaxError: redeclaration of formal parameter "x"
  • SyntaxError: return not in function
  • SyntaxError: test for equality (==) mistyped as assignment (=)?
  • SyntaxError: unterminated string literal
  • TypeError: "x" has no properties
  • TypeError: "x" is (not) "y"
  • TypeError: "x" is not a constructor
  • TypeError: "x" is not a function
  • TypeError: "x" is not a non-null object
  • TypeError: "x" is read-only
  • TypeError: More arguments needed
  • TypeError: can't access dead object
  • TypeError: can't define property "x": "obj" is not extensible
  • TypeError: can't delete non-configurable array element
  • TypeError: can't redefine non-configurable property "x"
  • TypeError: cyclic object value
  • TypeError: invalid 'in' operand "x"
  • TypeError: invalid Array.prototype.sort argument
  • TypeError: invalid arguments
  • TypeError: invalid assignment to const "x"
  • TypeError: property "x" is non-configurable and can't be deleted
  • TypeError: setting getter-only property "x"
  • TypeError: variable "x" redeclares argument
  • URIError: malformed URI sequence
  • Warning: -file- is being assigned a //# sourceMappingURL, but already has one
  • Warning: 08/09 is not a legal ECMA-262 octal constant
  • Warning: Date.prototype.toLocaleFormat is deprecated
  • Warning: JavaScript 1.6's for-each-in loops are deprecated
  • Warning: String.x is deprecated; use String.prototype.x instead
  • Warning: expression closures are deprecated
  • Warning: unreachable code after return statement
  • JavaScript technologies overview
  • Lexical grammar
  • Enumerability and ownership of properties
  • Iteration protocols
  • Transitioning to strict mode
  • Template literals
  • Deprecated features
  • ECMAScript 2015 support in Mozilla
  • ECMAScript 5 support in Mozilla
  • ECMAScript Next support in Mozilla
  • Firefox JavaScript changelog
  • New in JavaScript 1.1
  • New in JavaScript 1.2
  • New in JavaScript 1.3
  • New in JavaScript 1.4
  • New in JavaScript 1.5
  • New in JavaScript 1.6
  • New in JavaScript 1.7
  • New in JavaScript 1.8
  • New in JavaScript 1.8.1
  • New in JavaScript 1.8.5
  • Documentation:
  • All pages index
  • Methods index
  • Properties index
  • Pages tagged "JavaScript"
  • JavaScript doc status
  • The MDN project

shorthand assignment js

JavaScript — Shorthand Variable Assignment

A three minute introduction into shorthand variable assignment.

Brandon Morelli

Brandon Morelli

This article will take a (very) quick look at shorthand variable assignment in JavaScript.

Assigning Variables to Other Variables

As you’re probably aware, you can assign values to variables separately, like this:

However, if all variables are being assigned equal values, you can shorthand and assign the variables like this:

The assignment operator = in JavaScript has right-to-left associativity. This means that it works from the right of the line, to the left of the line. In this example, here is the order of operation:

  • 1 — First, c is set to 1 .
  • 2 — Next, b is set equal to c which is already equal to 1 . Therefor, b is set to 1 .
  • 3 — Finally, a is set equal to b which is already equal to 1 . Therefor, a is set to 1 .

As you can now see, the shorthand above results in a , b , and c all being set to 1 .

However, this is not a recommended way to assign variables. That’s because in the shorthand variable assignment shown above, we actually never end up declaring variables b or c . Because of this, b and c wont be locally scoped to the current block of code. Both variables b and c will instead be globally scoped and end up polluting the global namespace.

Using Commas When Assigning Variables

Lets look at a new example. Consider the following variable declarations and assignments:

We can shorthand this code using commas:

As you see, we are separating each variable assignment with a comma which allows us to assign different values to each variable.

For ease of reading, most coders who prefer using the comma method will structure their variable assignments like this:

Best of all, in the shorthand variable assignment shown above, we are declaring all three variables: d , e , and f . Because of this, all variables will be locally scoped and we’re able to avoid any scoping problems.

Want to Learn More Shorthands?

Check out my other articles on shorthand coding techniques in JavaScript:

  • JavaScript — The Conditional (Ternary) Operator Explained
  • JavaScript — Short Circuit Conditionals
  • JavaScript — Short Circuit Evaluation

Closing Notes:

Thanks for reading! If you’re ready to finally learn Web Development, check out: The Ultimate Guide to Learning Full Stack Web Development in 6 months .

If you’re working towards becoming a better JavaScript Developer, check out: Ace Your Javascript Interview — Learn Algorithms + Data Structures .

I publish 4 articles on web development each week. Please consider entering your email here if you’d like to be added to my once-weekly email list, or follow me on Twitter .

If this post was helpful, please click the clap 👏 button below a few times to show your support! ⬇⬇

Brandon Morelli

Written by Brandon Morelli

Creator of @codeburstio — Frequently posting web development tutorials & articles. Follow me on Twitter too: @BrandonMorelli

More from Brandon Morelli and codeburst

10 Awesome Web Developer Portfolios

10 Awesome Web Developer Portfolios

Get inspired with these 10 web developer portfolios..

How To Create Horizontal Scrolling Containers

How To Create Horizontal Scrolling Containers

As a front end developer, more and more frequently i am given designs that include a horizontal scrolling component. this has become….

Top 50 Java Interview Questions for Beginners and Junior Developers

Top 50 Java Interview Questions for Beginners and Junior Developers

A list of frequently asked java questions and answers from programming job interviews of java developers of different experience..

JavaScript ES 2017: Learn Async/Await by Example

JavaScript ES 2017: Learn Async/Await by Example

Async/await explained through a clear example., recommended from medium.

Advice From a Software Engineer With 8 Years of Experience

Benoit Ruiz

Better Programming

Advice From a Software Engineer With 8 Years of Experience

Practical tips for those who want to advance in their careers.

Programming Principles They Don’t Teach You In School

Nishant Aanjaney Jalan

Programming Principles They Don’t Teach You In School

Introduction to important principles you should know — dry, kiss, solid.

shorthand assignment js

General Coding Knowledge

shorthand assignment js

Stories to Help You Grow as a Software Developer

shorthand assignment js

Coding & Development

shorthand assignment js

ChatGPT prompts

Stop Using localStorage

Julien Etienne

Stop Using localStorage

Bid farewell to localstorage embrace indexeddb for speed, type-safe storage, and non-blocking data transactions. #indexeddb #webdev.

I Built an App in 6 Hours that Makes $1,500/Mo

Artturi Jalli

I Built an App in 6 Hours that Makes $1,500/Mo

Copy my strategy.

Top 30 JavaScript Interview Questions and Answers for 2024

Ravi Sharma

Top 30 JavaScript Interview Questions and Answers for 2024

Prepare for your next javascript interview with confidence.

Mastering JavaScript Callbacks with These 5 Practical Exercises

Francesco Saviano

Mastering JavaScript Callbacks with These 5 Practical Exercises

Introduction.

Text to speech

Jscurious.com Logo

Web Development Blog

20+ JavaScript tips and tricks that you should know

Let’s discuss some of the shorthand techniques and other tips & tricks of JavaScript one by one.

1. Assigning values to multiple variables

We can assign values to multiple variables in one line with array destructuring.

2. The Ternary operator

We can save 5 lines of code here with the ternary (conditional) operator.

3. Assigning a default value

We can use OR(||) short circuit evaluation to assign a default value to a variable in case the expected value is found falsy.

4. Remove duplicates from an Array

The Set object stores only unique elements. Therefore, we can create a Set from the given array of elements and then, convert the Set back to an array to get all unique elements.

Reference: JavaScript Set object to store unique values

5. AND(&&) Short circuit evaluation

If you are calling a function only if a variable is true, then you can use the AND(&&) short circuit as an alternative for this.

The AND(&&) short circuit shorthand is more useful in React when you want to conditionally render a component. For example:

6. Swap two variables

To swap two variables, we often use a third variable. We can swap two variables easily with array destructuring assignment.

7. Arrow Function

Reference : JavaScript Arrow function

8. Template Literals

We normally use the + operator to concatenate string values with variables. With ES6 template literals, we can do it in a more simple way.

9. Multi-line String

For multiline strings, we normally use + operator with a new line escape sequence ( \n ). We can do it in an easier way by using backticks ( ` ).

10. Multiple condition checking

For multiple value matching, we can put all values in an array and use indexOf() method.

11. Object Property Assignment

If the variable name and object key name are the same then we can just mention the variable name in object literals instead of both key and value. JavaScript will automatically set the key same as the variable name and assign the value as the variable value.

12. String into a Number

There are built-in methods like parseInt and parseFloat available to convert a string to a number. We can also do this by simply providing a unary operator ( + ) in front of the string value.

13. Repeat a string multiple times

To repeat a string a specific number of times you can use a for loop. But using the repeat() method we can do it in a single line.

14. Exponent Power

We can use Math.pow() method to find the power of a number. There is a shorter syntax to do it with a double asterisk ( ** ).

15. Double NOT bitwise operator (~~)

The double NOT bitwise operator is a substitute for Math.floor() method.

The double NOT bitwise operator approach only works for 32 bit integers i.e (2**31)-1 = 2147483647. So for any number higher than 2147483647 and less than 0, bitwise operator (~~) will give wrong results, so recommended to use  Math.floor()  in such case.

16. Find the max and min numbers in an array

We can use for loop to loop through each value of the array and find the max or min value. We can also use the Array.reduce() method to find the max and min number in the array.

But using the spread operator we can do it in a single line.

17. For loop

To loop through an array we normally use the traditional for loop. We can make use of the for…of loop to iterate through arrays. To access the index of each value we can use for…in loop.

We can also loop through object properties using for…in loop.

Reference : Different ways to iterate through objects and arrays in JavaScript

18. Merging of arrays

19. remove properties from an object.

To remove a property from an object we can use the delete operator, but to remove multiple properties at a time, we can use the Rest parameter with destructuring assignment .

20. Get character from string

21. remove falsy values from array.

Zero (0) is considered to be a falsy value so it will be removed in both the cases. You can add an extra check for zero to keep it.

22. Create a random string token

Some of these shorthand techniques may not seem relevant to use in a project but it’s not bad to know some extra techniques. Happy coding!

Amitav Mishra

Web Developer by Profession, Blogger by Passion. JavaScript | React | Next |  Angular | Vue | HTML | CSS

3 thoughts on “ 20+ JavaScript tips and tricks that you should know ”

Hi there! I could have sworn I’ve visited your blog before but after browsing through many of the articles I realized it’s new to me. Nonetheless, I’m definitely pleased I discovered it and I’ll be book-marking it and checking back regularly!

I don’t even know how I ended up here, but I thought this post was good. I don’t know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers! 0mniartist asmr

Thanks for finally writing about > 20 JavaScript Shorthand Techniques that will save your time – JS Curious < Loved it!

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

Shorthand Property and Method Names in JavaScript | ES6

Tyler mcginnis updated september 15, 2019 1 minute read.

ES6 introduced two new features to make objects more concise - Shorthand Properties and Shorthand Method Names.

Shorthand Properties

With Shorthand Properties, whenever you have a variable which is the same name as a property on an object, when constructing the object, you can omit the property name.

What that means is that code that used to look like this,

can now look like this.

Shorthand Method Names

Now, what if one of those properties was a function?

A function that is a property on an object is called a method. With ES6's Shorthand Method Names, you can omit the function keyword completely. What that means is that code that used to look like this,

can now look like this

Both Shorthand Properties and Shorthand Method Names are just syntactic sugar over the previous ways we used to add properties to an object. However, because they're such common tasks, even the smallest improvements eventually add up.

Before you leave

I know, another newsletter pitch - but hear me out. Most JavaScript newsletters are terrible. When’s the last time you actually looked forward to getting one? Even worse, when’s the last time you actually read one? We wanted to change that.

We call it Bytes , but others call it their favorite newsletter .

Delivered to 209,432 developers every Monday and Thursday

Avatar for @sduduzo_g

@ sduduzo_g

This is the first ever newsletter that I open a music playlist for and maximize my browser window just to read it in peace. Kudos to @uidotdev for great weekly content.

Avatar for @flybayer

Brandon Bayer

The Bytes newsletter is a work of art! It’s the only dev newsletter I’m subscribed too. They somehow take semi boring stuff and infuse it with just the right amount of comedy to make you chuckle.

Avatar for @johnhawly

John Hawley

@ johnhawly

Bytes has been my favorite newsletter since its inception. It’s my favorite thing I look forward to on Mondays. Goes great with a hot cup of coffee!

Avatar for @garrettgreen

Garrett Green

@ garrettgreen

I subscribe to A LOT of dev (especially JS/TS/Node) newsletters and Bytes by @uidotdev is always such a welcomed, enjoyable change of pace to most (funny, lighthearted, etc) but still comprehensive/useful.

Avatar for @mhashim6_

@ mhashim6_

Literally the only newsletter I’m waiting for every week.

Avatar for @graysonhicks

Grayson Hicks

@ graysonhicks

Bytes is the developer newsletter I most look forward to each week. Great balance of content and context! Thanks @uidotdev.

Avatar for @mitchellbwright

Mitchell Wright

@ mitchellbwright

I know I’ve said it before, but @tylermcginnis doesn’t miss with the Bytes email. If you’re a developer, you really need to subscribe

Avatar for @aspittel

Ali Spittel

Can I just say that I giggle every time I get the @uidotdev email each week? You should definitely subscribe.

Avatar for @thefinnomenon

@ thefinnomenon

Every JavaScript programmer should be subscribed to the newsletter from @uidotdev. Not only do they manage to succinctly cover the hot news in the JavaScript world for the week but it they manage to add a refreshing humor to it all.

IMAGES

  1. Top JavaScript Shorthand Techniques

    shorthand assignment js

  2. 20 JavaScript Shorthand Techniques that will save your time

    shorthand assignment js

  3. JavaScript Shorthand Techniques

    shorthand assignment js

  4. Code Faster with JavaScript Shorthands

    shorthand assignment js

  5. Shorthand Property and Method Names in JavaScript

    shorthand assignment js

  6. Assignment Operator (Shorthand) in JavaScript Tutorial

    shorthand assignment js

VIDEO

  1. CRPF Typing Test

  2. FEBRUARY 2011 SHORTHAND ENGLISH SENIOR SPEED DICTATION

  3. शब्द चिन्ह ऋषि प्रणाली Ex. 19+20

  4. Shorthand cricket #shorthandcricket #cricketlover

  5. RAJ PASWAN 🔥 2 Sixes in an Over । MAHISHADAL MLA CUP 2024

  6. Statistics 2 Week 9 Graded Assignment Solution // IITM BS Online Degree Program || Foundation

COMMENTS

  1. 25+ JavaScript Shorthand Coding Techniques

    It's good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the ...

  2. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  3. 18 JavaScript and TypeScript shorthands to know

    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 }

  4. JavaScript Assignment

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  5. JavaScript

    Now, here's what the shorthand code to do this looks like: let x = 1, y = 2; x += y; console.log(x); // 3. Instead of using x = x + y, we can write x += y. Both of these code bits do the exact same thing — add x + y, then assign the resulting value to x. Other Shorthands. Best of all, this pattern can be followed for other assignment operators.

  6. 15+ JavaScript Shorthand Coding Techniques for Beginners

    This article includes a round-up of some popular JavaScript shorthand coding techniques for beginners, which can be good for code optimization or minification purposes. Assignment Operators Shorthand Name Shorthand operator Meaning Addition Assignment x += y x = x + y Subtraction Assignment x -= y x = x - y Multiplication Assignment x *= y x ...

  7. Expressions and operators

    The shorthand assignment operator += can also be used to concatenate strings. For example, var mystring = 'alpha'; mystring += 'bet'; // evaluates to "alphabet" and assigns this value to mystring. Conditional (ternary) operator. The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two ...

  8. 12 Good JavaScript Shorthand Techniques

    let z = 3; Shorthand: let x, y, z=3; 5. Assignment Operators Shorthand. Assignment operators are used to assign values to JavaScript variables and no doubt you use arithmetic everyday without ...

  9. JavaScript

    However, if all variables are being assigned equal values, you can shorthand and assign the variables like this: var a = b = c = 1; The assignment operator = in JavaScript has right-to-left associativity. This means that it works from the right of the line, to the left of the line. In this example, here is the order of operation: 1 — First, c ...

  10. Mastering JavaScript Shorthand: Declaring Variables, Assignment

    Become a JavaScript pro with shorthand techniques! Learn concise variable declarations, assignment ops & template literals for efficient coding. Master the shortcuts JavaScript is a versatile and…

  11. 20+ JavaScript tips and tricks that you should know

    Let's discuss some of the shorthand techniques and other tips & tricks of JavaScript one by one. 1. Assigning values to multiple variables. We can assign values to multiple variables in one line with array destructuring. let a, b, c; a = 5; b = 8; c = 12; let [a, b, c] = [5, 8, 12];

  12. Object initializer

    Object initializer. An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ). Objects can also be initialized using Object.create() or by invoking a constructor function with the new operator.

  13. Shorthand if/else statement Javascript

    Even then, this makes the code overly complex, since in JavaScript, default assignments can just be expressed with the || operator as @Nemesarial commented in OP or with the ternary operator in accepted answer - vassiliskrikonis. Apr 4, 2020 at 11:21 ... JavaScript shorthand if statement, without the else portion. 1. javascript shorthand ...

  14. Shorthand Property and Method Names in JavaScript

    ES6 introduced two new features to make objects more concise - Shorthand Properties and Shorthand Method Names. With Shorthand Properties, whenever you have a variable which is the same name as a property on an object, when constructing the object, you can omit the property name. What that means is that code that used to look like this,

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

  16. Conditional (ternary) operator

    The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if ...

  17. Destructuring assignment

    The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... The destructuring assignment uses similar syntax but uses it on the left-hand side of the assignment instead. It defines which values to unpack from the sourced variable. js.

  18. Javascript shorthand if + shorthand assignment

    You can use the AND && operator: // if value is undefined, null, or empty then it stays the same. // otherwise add append the element value. value = (value && value + element.value); although this isnt much more readable than your original. // if value is undefined, null, or empty then it stays the same.

  19. javascript

    An assignment is just an expression in javascript, and yields the right-hand-side value. So your snippet is parsed as. (apple = (banana = (orange = (true)))); and has (approximately 1) the same effect as. orange = true; banana = true; apple = true; // (since the literal `true` has no side effects when being evaluated)

  20. What is JavaScript shorthand property?

    With ES6, you can use shorthand property names which allow you to write something like this. var s = 'abc'; var n = 1; var o = { s, n }; // This is equivalent to { s: s, n: n } In your case, prop = [1,2,3] was parsed as one shorthand property (s and n in the example above), but it was not a proper property name.