ES6 Object Literal Property Value Shorthand in JavaScript

In JavaScript, we are used to constructing an object by using the literal syntax {...} where each key-value pair is defined explicitly. We usually use the same object key names as the existing variables used as values.

Let us look at the following example:

As you can see above, the properties have the same names as the variables. The object literal property value shorthand was introduced in ES6 to shorten the object initialization.

It allows us to define an object whose keys have the same names as the variables passed in as properties by simply passing the variables:

The property value shorthand syntax automatically converts each variable to a key-value pair with the variable name as a property key and the variable value as a property value.

You can also combine both regular properties and shorthands in the same object. This is especially useful when you want to assign a different key name to a property than the variable name:

✌️ Like this article? Follow me on Twitter and LinkedIn . You can also subscribe to RSS Feed .

You might also like...

  • Get the length of a Map in JavaScript
  • Delete an element from a Map in JavaScript
  • Get the first element of a Map in JavaScript
  • Get an element from a Map using JavaScript
  • Update an element in a Map using JavaScript
  • Add an element to a Map in JavaScript

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.

  • JavaScript, Node.js & Spring Boot
  • In-depth tutorials
  • Super-handy protips
  • Cool stuff around the web
  • 1-click unsubscribe
  • No spam, free-forever!

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

Javascript Topics

Popular articles.

  • Jsx: Markup Expressions In Javascript (Apr 27, 2024)
  • The Tostring() Method (Apr 22, 2024)
  • Understanding The Reflect Api In Javascript (Apr 22, 2024)
  • Proxy Invariants And Usage Guidelines (Apr 22, 2024)
  • Methods For Performing Meta-Level Operations On Objects (Apr 22, 2024)

Shorthand Properties

Table of Contents

Introduction to Shorthand Properties in JavaScript

Understanding the traditional object syntax, the need for enhanced object syntax, exploring shorthand property initializers, shorthand method syntax, computed property names, benefits of using shorthand properties, practical examples and use cases of shorthand properties, common mistakes and how to avoid them, best practices for using shorthand properties.

Shorthand properties in JavaScript are a feature introduced in ES6 (ECMAScript 6) as part of the enhanced object syntax. They are a more concise way of initializing object properties, making your code cleaner and easier to read. Traditionally, when creating an object, you would have to define each property and its value separately.

However, with shorthand properties, if the property name and the variable name are the same, you can simply write the name once. This not only reduces redundancy but also makes your code more efficient. This introduction to shorthand properties will set the stage for a deeper exploration into this powerful feature of JavaScript.

Before diving into shorthand properties, it's crucial to understand the traditional way of defining objects in JavaScript. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In the traditional object syntax, properties are assigned values upon object creation. The property name and its corresponding value are separated by a colon, and multiple properties are separated by commas. Here's an example:

In this example, 'student' is an object with properties 'name', 'age', and 'greet'. The 'greet' property is a method that logs a greeting message to the console.

  • Each property and its value are explicitly defined.
  • The property name and value are separated by a colon.
  • Properties are separated by commas.

This traditional syntax works well but can become verbose and repetitive, especially when dealing with many properties or complex objects. This is where the enhanced object syntax, including shorthand properties, comes into play, offering a more concise and efficient way to define object properties.

As JavaScript applications grow in complexity, the traditional object syntax can become verbose and repetitive, leading to code that is harder to read and maintain. This is especially true when you're dealing with objects that have many properties or when the property values are derived from variables with the same names. Consider the following example:

In this example, the property names in the 'student' object are the same as the variable names. This redundancy can make your code longer and more difficult to manage, especially in larger codebases.

The enhanced object syntax introduced in ES6 addresses these issues by providing a more concise and efficient way to define object properties. It includes features like shorthand properties, shorthand method syntax, and computed property names, which we will explore in the following sections.

  • Shorthand properties allow you to initialize properties with variables of the same name in a more concise way.
  • Shorthand method syntax lets you define methods more succinctly.
  • Computed property names enable you to dynamically compute property names.

By using these features, you can write cleaner, more readable code, making your JavaScript applications easier to understand and maintain.

Shorthand property initializers are a feature of the enhanced object syntax in ES6 that allow for more concise and readable code. They come in handy when you want to create an object that includes properties with the same names as the variables you have in scope. Consider the following example:

In the second 'student' object, the property names are the same as the variable names. Instead of writing 'name: name' and 'age: age', you can simply write 'name' and 'age'. The JavaScript engine will understand that the property names should be the same as the variable names and assign the corresponding values. Here are some key points to remember:

  • Shorthand property initializers can make your code more concise and readable.
  • They are particularly useful when the property names in an object are the same as the variable names in scope.
  • They are part of the enhanced object syntax introduced in ES6, which includes other features like shorthand method syntax and computed property names.

By using shorthand property initializers, you can write cleaner, more efficient code, improving the readability and maintainability of your JavaScript applications.

In addition to shorthand property initializers, ES6 also introduced a shorthand method syntax. This feature allows you to define methods in an object without the need for the 'function' keyword, making your code more concise and readable. Consider the following example:

In the second 'student' object, the 'greet' method is defined using the shorthand method syntax. Instead of writing 'greet: function()', you can simply write 'greet()'. The JavaScript engine will understand that 'greet' is a method and assign the corresponding function as its value. Here are some key points to remember:

  • Shorthand method syntax can make your code more concise and readable.
  • It allows you to define methods in an object without the need for the 'function' keyword.
  • It is part of the enhanced object syntax introduced in ES6, which includes other features like shorthand property initializers and computed property names.

By using shorthand method syntax, you can write cleaner, more efficient code, improving the readability and maintainability of your JavaScript applications.

Computed property names are another feature of the enhanced object syntax in ES6. They allow you to dynamically compute property names of an object at runtime. This can be particularly useful when you need to create property names based on certain conditions or variables. Consider the following example:

In this example, the property names 'name' and 'id_1234' are computed at runtime. The square brackets [] around the property names indicate that they are computed properties. The JavaScript engine will evaluate the expressions inside the brackets and use the results as the property names. Here are some key points to remember:

  • Computed property names allow you to dynamically compute property names of an object at runtime.
  • They can be particularly useful when you need to create property names based on certain conditions or variables.
  • They are part of the enhanced object syntax introduced in ES6, which includes other features like shorthand property initializers and shorthand method syntax.

By using computed property names, you can create more dynamic and flexible objects, enhancing the power and versatility of your JavaScript code.

Shorthand properties, as part of the enhanced object syntax in ES6, offer several benefits that can significantly improve your JavaScript coding experience.

1. Conciseness and Readability: Shorthand properties make your code more concise and easier to read. By eliminating the need to repeat property names and values when they are the same, your code becomes cleaner and more straightforward.

2. Efficiency: Shorthand properties can make your code more efficient. By reducing the amount of code you have to write, you can save time and effort, especially in larger codebases.

3. Consistency: Using shorthand properties can lead to more consistent code. When all developers on a team use the same syntax, it can make the codebase easier to understand and maintain.

4. Modern JavaScript Practices: Shorthand properties are part of modern JavaScript practices. By using them, you're keeping your skills up to date and making your code more compatible with recent developments in the language.

5. Compatibility with Destructuring: Shorthand properties work well with other ES6 features like destructuring, making it easier to extract data from arrays or objects.

In conclusion, shorthand properties are a powerful tool that can help you write cleaner, more efficient, and more modern JavaScript code. By understanding and using this feature, you can improve the quality of your code and become a more effective JavaScript developer.

Shorthand properties can be used in a variety of practical scenarios in JavaScript development. Here are a few examples and use cases:

1. Creating Objects from Variables: When you have variables and want to create an object with properties that match those variable names, shorthand properties can make your code more concise.

2. Returning Objects from Functions: When a function returns an object, shorthand properties can simplify the return statement.

3. Object Destructuring: Shorthand properties work well with object destructuring, a feature that allows you to unpack properties from an object into distinct variables.

4. Defining Methods in Objects: Shorthand method syntax can make your object methods more concise.

These examples demonstrate the versatility and practicality of shorthand properties in JavaScript. By using them in your code, you can make your JavaScript development more efficient and your code more readable and maintainable.

While shorthand properties in JavaScript can make your code more concise and readable, there are some common mistakes that developers often make when using them. Here are a few of these mistakes and how to avoid them:

1. Using Shorthand Properties with Different Variable and Property Names: Shorthand properties are only useful when the property name and the variable name are the same. If they are different, you need to use the traditional syntax.

2. Using Shorthand Properties in Older Browsers: Shorthand properties are part of ES6, which is not supported in older browsers. If you need to support older browsers, you should transpile your code using a tool like Babel.

3. Confusing Shorthand Method Syntax with Regular Functions: The shorthand method syntax is for defining methods within an object. It should not be confused with the syntax for regular functions.

By being aware of these common mistakes and understanding how to avoid them, you can use shorthand properties effectively and avoid potential errors in your JavaScript code.

When using shorthand properties in JavaScript, there are several best practices that can help you write cleaner, more efficient code:

1. Use Shorthand Properties When Variable and Property Names Match: Shorthand properties are most effective when the property name and the variable name are the same. In such cases, use the shorthand syntax to make your code more concise.

2. Combine Shorthand Properties with Other ES6 Features: Shorthand properties can be effectively combined with other ES6 features like destructuring and spread operator for more powerful and concise code.

3. Use Shorthand Method Syntax for Object Methods: When defining methods within an object, use the shorthand method syntax to make your code more readable.

4. Transpile Your Code for Older Browsers: If you need to support older browsers that do not support ES6, make sure to transpile your code using a tool like Babel.

By following these best practices, you can make the most of shorthand properties and write more efficient, readable, and modern JavaScript code.

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

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

javascript object assignment shorthand

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.

javascript object assignment shorthand

Over 200k developers use LogRocket to create better digital experiences

javascript object assignment shorthand

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

javascript object assignment shorthand

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.

javascript object assignment shorthand

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.

javascript object assignment shorthand

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.

javascript object assignment shorthand

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.

javascript object assignment shorthand

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

  • 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

Shorthand Syntax for Object Property Value in ES6

  • How to add a property to a JavaScript object using a variable as the name?
  • How to throw an error when using a property of an object ?
  • HTML | DOM Input Text value Property
  • How to Get an Object Value By Key in TypeScript
  • JavaScript Object.prototype.constructor Property
  • How to get all property values of a JavaScript Object (without knowing the keys) ?
  • Which property is used as shorthand to specify a number of other font properties in CSS ?
  • How to read properties of an Object in JavaScript ?
  • How to copy properties from one object to another in ES6 ?
  • JavaScript Object.prototype.valueOf() Method
  • How to Detect an Undefined Object Property in JavaScript ?
  • JavaScript Handler defineProperty() Method
  • How to remove a property from JavaScript object ?
  • CSS | Shorthand Properties
  • How to create object properties in JavaScript ?
  • JavaScript Symbol description Property
  • TypeScript Object Type Excess Property Checks
  • HTML | DOM Output value Property
  • HTML DOM Button value Property
  • How to calculate the number of days between two dates in JavaScript ?
  • Convert a String to an Integer in JavaScript
  • How to append HTML code to a div using JavaScript ?
  • How to Open URL in New Tab using JavaScript ?
  • Difference between var and let in JavaScript
  • How do you run JavaScript script through the Terminal?
  • Remove elements from a JavaScript Array
  • How to read a local text file using JavaScript?
  • JavaScript console.log() Method
  • JavaScript Number toString() Method

Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types).

The shorthand syntax for object property value is very popular and widely used nowadays. The code looks cleaner and easy to read. The shorthand property makes the code size smaller and simpler.

Example: This example displaying the details of object using shorthand Syntax for object property value in ES6.

Output of above command

Example: This example displaying the details of the object without using shorthand Syntax for object property value.

Please Login to comment...

Similar reads.

author

  • JavaScript-Misc
  • Web Technologies

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

object-shorthand

Require or disallow method and property shorthand syntax for object literals

Some problems reported by this rule are automatically fixable by the --fix command line option

ECMAScript 6 provides a concise form for defining object literal methods and properties. This syntax can make defining complex object literals much cleaner.

Here are a few common examples using the ES5 syntax:

Now here are ES6 equivalents:

Rule Details

This rule enforces the use of the shorthand syntax. This applies to all methods (including generators) defined in object literals and any properties defined where the key name matches name of the assigned variable.

Each of the following properties would warn:

In that case the expected syntax would have been:

This rule does not flag arrow functions inside of object literals. The following will not warn:

The rule takes an option which specifies when it should be applied. It can be set to one of the following values:

  • "always" (default) expects that the shorthand will be used whenever possible.
  • "methods" ensures the method shorthand is used (also applies to generators).
  • "properties" ensures the property shorthand is used (where the key and variable name match).
  • "never" ensures that no property or method shorthand is used in any object literal.
  • "consistent" ensures that either all shorthand or all long-form will be used in an object literal.
  • "consistent-as-needed" ensures that either all shorthand or all long-form will be used in an object literal, but ensures all shorthand whenever possible.

You can set the option in configuration like this:

Additionally, the rule takes an optional object configuration:

  • "avoidQuotes": true indicates that long-form syntax is preferred whenever the object key is a string literal (default: false ). Note that this option can only be enabled when the string option is set to "always" , "methods" , or "properties" .
  • "ignoreConstructors": true can be used to prevent the rule from reporting errors for constructor functions. (By default, the rule treats constructors the same way as other functions.) Note that this option can only be enabled when the string option is set to "always" or "methods" .
  • "methodsIgnorePattern" ( string ) for methods whose names match this regex pattern, the method shorthand will not be enforced. Note that this option can only be used when the string option is set to "always" or "methods" .
  • "avoidExplicitReturnArrows": true indicates that methods are preferred over explicit-return arrow functions for function properties. (By default, the rule allows either of these.) Note that this option can only be enabled when the string option is set to "always" or "methods" .

avoidQuotes

Example of incorrect code for this rule with the "always", { "avoidQuotes": true } option:

Example of correct code for this rule with the "always", { "avoidQuotes": true } option:

ignoreConstructors

Example of correct code for this rule with the "always", { "ignoreConstructors": true } option:

methodsIgnorePattern

Example of correct code for this rule with the "always", { "methodsIgnorePattern": "^bar$" } option:

avoidExplicitReturnArrows

Example of incorrect code for this rule with the "always", { "avoidExplicitReturnArrows": true } option:

Example of correct code for this rule with the "always", { "avoidExplicitReturnArrows": true } option:

Example of incorrect code for this rule with the "consistent" option:

Examples of correct code for this rule with the "consistent" option:

Example of incorrect code with the "consistent-as-needed" option, which is very similar to "consistent" :

When Not To Use It

Anyone not yet in an ES6 environment would not want to apply this rule. Others may find the terseness of the shorthand syntax harder to read and may not want to encourage it with this rule.

Related Rules

  • no-useless-rename

This rule was introduced in ESLint v0.20.0.

Further Reading

Avatar image for developer.mozilla.org

  • Rule source
  • Tests source
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Optional chaining (?.)

The optional chaining ( ?. ) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null , the expression short circuits and evaluates to undefined instead of throwing an error.

Description

The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish ( null or undefined ), the expression short-circuits with a return value of undefined . When used with function calls, it returns undefined if the given function does not exist.

This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

The value of obj.first is confirmed to be non- null (and non- undefined ) before accessing the value of obj.first.second . This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first .

This is an idiomatic pattern in JavaScript, but it gets verbose when the chain is long, and it's not safe. For example, if obj.first is a Falsy value that's not null or undefined , such as 0 , it would still short-circuit and make nestedProp become 0 , which may not be desirable.

With the optional chaining operator ( ?. ), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second :

By using the ?. operator instead of just . , JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second . If obj.first is null or undefined , the expression automatically short-circuits, returning undefined .

This is equivalent to the following, except that the temporary variable is in fact not created:

Optional chaining cannot be used on a non-declared root object, but can be used with a root object with value undefined .

Optional chaining with function calls

You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device.

Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found:

However, if there is a property with such a name which is not a function, using ?. will still raise a TypeError exception "someInterface.customMethod is not a function".

Note: If someInterface itself is null or undefined , a TypeError exception will still be raised ("someInterface is null"). If you expect that someInterface itself may be null or undefined , you have to use ?. at this position as well: someInterface?.customMethod?.() .

eval?.() is the shortest way to enter indirect eval mode.

Optional chaining with expressions

You can also use the optional chaining operator with bracket notation , which allows passing an expression as the property name:

This is particularly useful for arrays, since array indices must be accessed with square brackets.

Optional chaining not valid on the left-hand side of an assignment

It is invalid to try to assign to the result of an optional chaining expression:

Short-circuiting

When using optional chaining with expressions, if the left operand is null or undefined , the expression will not be evaluated. For instance:

Subsequent property accesses will not be evaluated either.

This is equivalent to:

However, this short-circuiting behavior only happens along one continuous "chain" of property accesses. If you group one part of the chain, then subsequent property accesses will still be evaluated.

Except the temp variable isn't created.

Basic example

This example looks for the value of the name property for the member bar in a map when there is no such member. The result is therefore undefined .

Dealing with optional callbacks or event handlers

If you use callbacks or fetch methods from an object with a destructuring assignment , you may have non-existent values that you cannot call as functions unless you have tested their existence. Using ?. , you can avoid this extra test:

Stacking the optional chaining operator

With nested structures, it is possible to use optional chaining multiple times:

Combining with the nullish coalescing operator

The nullish coalescing operator may be used after optional chaining in order to build a default value when none was found:

Specifications

Browser compatibility.

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

  • Nullish coalescing operator ( ?? )

Dot Net Tutorials

Object Property Initializer Shorthand in JavaScript

Back to: JavaScript Tutorial For Beginners and Professionals

Object Property Initializer Shorthand in JavaScript with Examples

In this article, I am going to discuss Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables in JavaScript with Examples. Please read our previous article where we discussed How to Find the Length of a JavaScript Object .

Before ES6, an object literal is a list of name-value pairs comma-separated inside of curly braces. In ES6 Whenever we assign a property value that matches a property name, we can omit the property value, it’s implicit (automatic) in ES6.

As ES6 allows to remove the duplication when a property value of an object is the same as the variable name/property name by including the name without the colon and value.

When using the same name for properties, the second property will overwrite the first one. This is called duplicate property name removal features of object literals. Objects’ properties are often created from variables with the same name. it is called Object Initialization from variables.

Example: JavaScript Object Literal-Property Shorthand

Output: Now run the above code and open the browser developer tool and select the Console tab and you will see the following output.

JavaScript Object Literal-Property Shorthand

Computed Property Names/Dynamic Property Keys in JavaScript

Prior to ES6 in ES5 and earlier, we could not use a variable as a property name inside an object literal. The only way we had was to create the object literal then assign the variable property name with value and pass the resulting object to the animate method.

ES6 defines ‘ComputedPropertyName’ as part of the object literals, which helps use a variable for an object key. Object keys can be dynamically assigned in ES6 by placing an expression in square brackets [ ].

Computed property names allow us to write an expression enclosed in square brackets [ ] instead of the regular property name. Whatever the expression is it will be computed and will be used as the property name.

Property names that are not valid identifiers cannot be accessed as an object name dot (.) property but can be accessed and set the property name with the array-like notation (“[]”).

The limitation of computed property names is that we won’t be able to use the shorthand expression with it. Other types are automatically converted to strings.

Computed Property Names/Dynamic Property Keys in JavaScript

A dynamic key can be used for methods as well as properties.

Example1: JavaScript Object Literal-Computed Property Names

Any expression can be used to create a key. For example, below sample code no-4 elaborate.

Example2: JavaScript Object Literal-Computed Property Names

JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names. We can also access the object properties by using a string value that is stored in a variable.

Use Variable as Object Key/ Computed Property Names in JavaScript

Similarly, if we have a variable const tutorial = ‘course’ and try to create an object with the variable as the object key

The lecture object’s key would be ‘tutorial’ , not ‘course ‘. What we discussed above is given in the below example.

Example: JavaScript Object, using a variable as the object key

Best Tip: JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names. Using the above example, we could write const tutorial = ‘course’

Pretty cool, isn’t it? What we discussed above is given in the below example.

Example: JavaScript Object, wrap the key in square brackets to use the variable as the object key

We can also access the object properties by using a string value that is stored in a variable. What we discussed above is given in the below example.

Example: JavaScript Object, access the object properties by using a string value that is stored in a variable

In the above example, sample code1 and sample code2 we are creating the object one with literal syntax and the other with key-value pair syntax which we learned already.

In the above when we try to access the object properties i.e.: [tutorial]: ‘JavaScript’, by using a string value(course) that is stored in a variable i.e.: const tutorial = ‘course’; with both bracket notation i.e.: lecture[‘course’] as well as dot notation i.e.: lecture.course it returns the value assigned to it which is JavaScript.

Next, when we try to access the variable(tutorial) i.e.: const tutorial = ‘course’ which is set as object key i.e.: [tutorial]: ‘JavaScript’, with bracket notation i.e.: lecture[tutorial] its returns JavaScript this is because its variable use as object property name.

Whereas when we try to access the normal property name i.e.: version: ‘ES6’, with bracket notation i.e.: lecture[version] it throws an Uncaught ReferenceError: version is not defined

Note that when we try to access the variable(tutorial) i.e.: const tutorial = ‘course’ which is set as object key i.e.: [tutorial]: ‘JavaScript’, with bracket notation having property name quoted i.e.: lecture[‘tutorial’] it’s returns undefined . This is because it is a variable that is set as an object key and we are trying to access it like normal property with quoted property name using bracket notation hence it gives undefined.

Whereas when we try to access the normal property name i.e.: version: ‘ES6’, with bracket notation having property name quoted i.e.: lecture[‘version’] it returns ES6.

Similarly, when we try to access the variable(tutorial) which is set as the object key, with dot notation i.e.: lecture.tutorial its returns undefined . Because of a variable that is set as an object key and we are trying to access it with dot notation in turn it gives undefined.

We already learned in earlier chapter Object creation using object literal that JavaScript ES6 provides a way to use variables as object keys — we have to wrap the key in square brackets ([]) also called Computed property names.

The square bracket notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime) this is possible by using a variable as an object key and wrapping that key in a square bracket [].

Example: Objects creation in JavaScript, by Using new Object() method, wrap the key in square brackets to use a variable as object key called Computed property names

In the above-given example, we are using a variable as an object key. So, in order to use a variable as an object key, we have to wrap the object key in square brackets [] which is also called Computed property name/dynamically determined.

Note that all the object keys wrapped in the square bracket notation are cast/converted to string unless they are symbols. That we can see in the above sample where typeof every object key wrapped in a square bracket is a string.

Also, above we are using property names/key data created for myObj object that contains a space i.e.: myObj[‘date created’], we need to use quotes around the property name. That can only be accessed using square bracket notation [].

In this article, I am going to discuss JavaScript Object Property flags and descriptors /Object properties configuration  with Examples. Here, in this article, I try to explain Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables with Examples and I hope you enjoy this Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables article.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Leave a Reply Cancel reply

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

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.

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.

COMMENTS

  1. Object initializer

    The object literal syntax is not the same as the JavaScript Object Notation ().Although they look similar, there are differences between them: JSON only permits property definition using the "property": value syntax. The property name must be double-quoted, and the definition cannot be a shorthand.

  2. javascript

    As per your given snippet you just need to change the option in Object.assign(). this.props = Object.assign(this.props, this.options); This should be work for you.

  3. ES6 Object Literal Property Value Shorthand in JavaScript

    The object literal property value shorthand was introduced in ES6 to shorten the object initialization. It allows us to define an object whose keys have the same names as the variables passed in as properties by simply passing the variables: The property value shorthand syntax automatically converts each variable to a key-value pair with the ...

  4. 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. Try it. Syntax. js. ... As for object assignment, the destructuring syntax allows for the new variable to have the same name or a different name than the original property, and ...

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

  6. Mastering Shorthand Properties in Enhanced Object Syntax with

    Benefits of Using Shorthand Properties. Shorthand properties, as part of the enhanced object syntax in ES6, offer several benefits that can significantly improve your JavaScript coding experience. 1. **Conciseness and Readability**: Shorthand properties make your code more concise and easier to read.

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

  8. Learn JavaScript: Objects Cheatsheet

    The JavaScript destructuring assignment is a shorthand syntax that allows object properties to be extracted into specific variable values. It uses a pair of curly braces ({}) with property names on the left-hand side of an assignment to extract values from objects. The number of variables can be less than the total properties of an object.

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

  10. Shorthand Syntax for Object Property Value in ES6

    Objects in JavaScript are the most important data-type and forms the building blocks for modern JavaScript. These objects are quite different from JavaScript primitive data-types (Number, String, Boolean, null, undefined, and symbol) in the sense that while these primitive data-types all store a single value each (depending on their types).

  11. object-shorthand

    "methods" ensures the method shorthand is used (also applies to generators). "properties" ensures the property shorthand is used (where the key and variable name match). "never" ensures that no property or method shorthand is used in any object literal. "consistent" ensures that either all shorthand or all long-form will be used in an object ...

  12. Optional chaining (?.)

    You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the ...

  13. Learn JavaScript Syntax: Objects

    The JavaScript destructuring assignment is a shorthand syntax that allows object properties to be extracted into specific variable values. It uses a pair of curly braces ( {}) with property names on the left-hand side of an assignment to extract values from objects. The number of variables can be less than the total properties of an object.

  14. Object Property Initializer Shorthand in JavaScript

    In the above-given example, we are using a variable as an object key. So, in order to use a variable as an object key, we have to wrap the object key in square brackets [] which is also called Computed property name/dynamically determined.. Note that all the object keys wrapped in the square bracket notation are cast/converted to string unless they are symbols.

  15. JavaScript Assignment

    JS Objects Object Definitions Object Properties Object Methods Object Display Object Accessors Object Constructors Object Prototypes Object Management Object Protection ... JavaScript Assignment Operators. Assignment operators assign values to JavaScript variables. Operator Example Same As = x = y: x = y += x += y: x = x + y-= x -= y: x = x - y ...

  16. Learn JavaScript: Objects

    The JavaScript destructuring assignment is a shorthand syntax that allows object properties to be extracted into specific variable values. It uses a pair of curly braces ({}) with property names on the left-hand side of an assignment to extract values from objects. The number of variables can be less than the total properties of an object.

  17. JavaScript: Object Property Value Shorthand for nested assignment

    and I want to assign some of the values to a key with the same name in another object. objTar = {. name: obj.name, age: obj.age. } Is there a shorthand for the above "nested" assignment? I know there's a shorthand for flat assignments; eg., objTar = { name, age } given name and age are available in the lexical scope.

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

    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.

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