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!

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

Actix Web Adoption Guide: Overview, Examples, And Alternatives

Actix Web adoption guide: Overview, examples, and alternatives

Actix Web is definitely a compelling option to consider, whether you are starting a new project or considering a framework switch.

javascript object assignment shorthand

Getting started with NativeWind: Tailwind for React Native

Explore the integration of Tailwind CSS with React Native through NativeWind for responsive mobile design.

javascript object assignment shorthand

Developing a cross-platform TV app with React Native

The react-tv-space-navigation library offers a comprehensive solution for developing a cross-platform TV app with React Native.

javascript object assignment shorthand

Essential tools for implementing React panel layouts

Explore some of the best tools in the React ecosystem for creating dynamic panel layouts, including react-resizable-layout and react-resizable-panels.

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

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 object assignment shorthand

Enhanced Object Literal Value Shorthand: JavaScript ES6 Feature Series (Pt 6)

Paige Niedringhaus

Paige Niedringhaus

Because typing the same thing twice in an object is crazy

Introduction.

T he inspiration behind these posts is simple: there are still plenty of developers for whom, JavaScript doesn’t make a whole lot of sense — or at the very least, is perplexing at times.

According to Wikipedia, JavaScript powers just under 95% of the 10 million most popular web pages, as of May 2017.

Since JS powers so much of the web, I wanted to provide a slew of articles and examples of ES6+ features that I use regularly, for other developers to reference.

The aim is for these articles to be short, in-depth explanations about various improvements to the language, that I hope will inspire you to write some really cool stuff using JS. Who knows, you might even learn something new along the way. 😄

My sixth post in this series will be about the new object property and method value shorthands introduced by ES2015, the most concise ways yet to initialize object properties from variables and define functions.

Objects: Everything in JavaScript is one

When it comes to JavaScript, you may have heard the phrase thrown around that “everything in JavaScript is an object.” Functions, strings, arrays, objects — they’re all objects. It can also be something else, but except for primitives, everything else is also an object in JS.

This article, however, concerns itself with object objects; the ones commonly initialized using the new Object() , Object.create() or literal notation initializers.

Let’s look at them before we get to the new changes courtesy of ES2015.

Object initializer examples: new Object()

This first example shows how to create an object using the new Object() keywords. First, an object constructor called Pet is defined, which takes in a number of parameters, and even has its own method, sayHello() attached to it.

Then, the variable pet1 is declared and new Pet() is called with the appropriate parameters passed to it. Voilà — a new object named pet1 now exists when you call it or its method, pet1.sayHello() .

Object initializer examples: Object.create()

The second example above demonstrates using the Object.create() initializer. This option requires an already existing object exist as the prototype for the newly created object.

In this instance, pet2 takes pet1 from the first example as its prototype. Then, pet2 assigns all the properties from pet1 with new values, and it also inherits the method sayHello() from pet1 as well.

So when pet2.sayHello() is called, it prints out "Rufus says 'hello' as woof" . Simple as that.

Object initializer examples: object literals {}

This final object initialization is the most frequently used one in day-to-day coding, by far: object literal initialization.

It can be done two ways:

  • By declaring the object and assigning all its properties and methods at the same time its initialized: like pet3 .
  • By declaring any variables and functions ahead of time, then assigning those to a new object, like pet4 .

However you choose to do it, both ways are perfectly acceptable, and frequently used.

Object literals, in particular, are what ECMAScript 2015 improves dramatically upon, let’s see how.

Shorthand Property Names

The first thing ES2015 improved upon regarding object literals is the abbreviated initialization of a property within an object, provided that the property key matches an existing variable name. This is known by most as: shorthand property names .

Traditional syntax for assigning variables to an object’s properties

Above is the traditional way to assign variables to an object’s properties. Seems a lot of extra typing in creating exoticPet when the properties already match the variable names doesn’t it?

Let’s fix that redundancy in the next example.

ES2015 shorthand example of assigning like-named variables to an object’s properties

As you can see, the syntax for exoticPet2 is much cleaner than the previous example. Since exoticPet2 ’s property names match the variables declared above: otherBreed , firstName , and so on, you can simply declare the property names once and ES2015 understands how to insert the variables of the same name into the object.

Pretty neat trick, huh? I do so appreciate this particular nicety of the ES6 improvements. I use it frequently.

Note: Beware of using the same name for your properties, the second property will overwrite the first.

Beware: Duplicate properties assume the last value assignment

Shorthand Method Definitions

Next up in our improvements to object literals courtesy of ES2015: method shorthand definitions . Method definition shorthand syntax omits the function keyword and colon, just like with the property assignments.

Traditional syntax to create methods (functions) in an object

In traditional JavaScript, methods (functions attached to objects), similar to normal object properties, are declared on an object with a property name like play or swim , and then assigned values with the traditional anonymous function declaration syntax of function() { /* ...do something here */ }; .

Then, the object’s method can be called just like its properties are: person.play() or person.swim() . Nothing too earth shattering there.

But does anyone really like anonymous functions much? Nah. It doesn’t seem to add much except unnecessary code, and if we have concise arrow function expressions now for traditional functions, why not make something similar for object methods too?

ES2015 shorthand to create methods (functions) in an object

Introducing ES2015 method shorthands for object literal notation. The person2 object has two methods similar to person1 , play() and swim() , and as you also see, the declarations on the the object itself lack the function keyword, instead taking the property name and making that the function name instead.

Cleaner, more succinct, and to be honest, it makes more sense to me when I read the code written this way than with the anonymous functions of old.

Ok, time to move to the last ES2015 object literal improvement: computed property names.

Computed Property Names

Starting with ECMAScript 2015, the object initializer syntax supports computed property names. This feature allows you to put an expression in brackets [] , that will be computed and used as the property name.

ES2015 shorthand for computing property keys / names via bracket notation

To be honest, I haven’t used this computed property names functionality once in daily life, but it’s nice to know it’s there if the situation should call for it, right?

And that’s it. That’s what you need to know about object literals in JavaScript as of ES2015.

All JS developers have gotten familiar with the language’s many quirks and gotchas over time, but lately, each year the ECMAScript committee releases new updates to the JavaScript language designed to make our lives easier. Some updated syntax changes look more foreign that others, but I’m happy to say the improvements to how we work with object literals are more similar to the older syntax than most.

Happily, the changes result in concise objects that can be more easily assigned variables, methods and even new, computed property names. It’s pretty great.

My aim with this blog series is to dive into some of my favorite parts of the JavaScript and ES6 syntax in use today, and show you how to use the best bits to maximum effect.

Check back in a few weeks, I’ll be writing about more JavaScript and ES6 or something else related to web development.

Thanks for reading, I hope you’re able to use this new object literal shorthand to make your own JavaScript objects more compact and manageable in the future.

If you enjoyed reading this, you may also enjoy some of my other blogs:

  • String Template Literals: JavaScript ES6 Feature Series (Pt 5)
  • Spread & Rest Parameters: JavaScript ES6 Feature Series (Pt 4)
  • Default Function Parameter Values: JavaScript ES6 Feature Series (Pt 3)

References and Further Resources:

  • Object literal notation, MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
  • Object property definitions shorthand, MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions
  • Object method definitions shorthand, MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions

Paige Niedringhaus

Written by Paige Niedringhaus

Staff Software Engineer at Blues, previously a digital marketer. Technical writer & speaker. Co-host of Front-end Fire & LogRocket podcasts

More from Paige Niedringhaus and ITNEXT

Polling in React using the useInterval Custom Hook

Bits and Pieces

Polling in React using the useInterval Custom Hook

Useinterval is a custom hook that’s certain to make intervals simpler in your app..

Modern Git Commands and Features You Should Be Using

Martin Heinz

Modern Git Commands and Features You Should Be Using

It’s not 2005 anymore and git offers more than just add, commit, push and pull. let’s explore all the new, modern git commands, that you….

PWAs Are Now Officially Dead On iOS In The EU

Danny Moerkerke

PWAs Are Now Officially Dead On iOS In The EU

Apple gives developers, customers and regulators the finger..

VS Code’s REST Client Plugin is All You Need to Make API Calls

VS Code’s REST Client Plugin is All You Need to Make API Calls

Why leave the ide to test new endpoints now you don’t have to., recommended from medium.

Exploring Call, Apply, and Bind Methods in JavaScript

Rabail Zaheer

Exploring Call, Apply, and Bind Methods in JavaScript

Functions are the building blocks of javascript, empowering developers to create reusable and modular code. they play a pivotal role in….

Shallow and Deep Copy in JavaScript: A Guide with Lodash, structuredClone, and JSON Methods

Navneet Singh

Shallow and Deep Copy in JavaScript: A Guide with Lodash, structuredClone, and JSON Methods

When working with javascript objects and arrays, understanding the concepts of shallow copy and deep copy is crucial. in this article….

javascript object assignment shorthand

General Coding Knowledge

javascript object assignment shorthand

Coding & Development

javascript object assignment shorthand

Stories to Help You Grow as a Software Developer

javascript object assignment shorthand

Mark Worachote

Best Practices for Developing with TypeScript in 2023

Typescript has quickly become one of the most popular languages for front-end development. with its optional static typing, rich feature….

A Guide to ES6 Import and Export Usage in Node.js

Stackademic

A Guide to ES6 Import and Export Usage in Node.js

As the world of web development is constantly evolving, a solid knowledge of modern javascript is essential. one of the fundamental aspects….

Let’s Build a Custom JavaScript Framework

Lyron Foster

Let’s Build a Custom JavaScript Framework

1. the most import question.

How to Master JavaScript in 2024?

Roman Sypchenko

How to Master JavaScript in 2024?

Things you wish you learned about javascript.

Text to speech

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
  • 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
  • Solve Coding Problems
  • ES6 Debugging
  • ES6 Image Map
  • What are decorators and how are they used in JavaScript ?
  • Motivation to bring symbols in ES6
  • Difference Between Angular and Knockout
  • How to calculate Width and Height of the Window using JavaScript ?
  • ES6 Tutorial
  • Prototypal Inheritance using __proto__ in JavaScript
  • Ways to capture the backspace and delete on the onkeydown event
  • Difference between PUT and DELETE request in Vanilla JavaScript
  • Introduction to ES6
  • Reference and Copy Variables in JavaScript
  • How to check two objects have same data using JavaScript ?
  • Remove the Chrome's "No file chosen option" from a file input using JavaScript
  • Gaussian/banker's rounding in JavaScript
  • ES6 Top features and syntax
  • How to declare variables in different ways in JavaScript?
  • Introduction to Mocha
  • How to solve the issue that arise while using performance.now() method in javaScript?

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

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

author

  • JavaScript-Misc
  • Web Technologies
  • What Is Trunk-Or-Treat?
  • 10 Best AI Tools for Lawyers (Free + Paid)
  • Fireflies AI vs Gong: Which AI Tool is best in 2024?
  • Top 10 Alternatives to Snapseed in 2024 [Free + Paid]
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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

javascript object assignment shorthand

JavaScript — Shorthand Assignment Operators

A three minute introduction into shorthand assignment operators.

Brandon Morelli

Brandon Morelli

If you’re adding, subtracting, multiplying, dividing, or remaindering two values, there’s no need to type out the entire equation. Use these shorthands to save time and code:

Adding Two Values

As an example, we’ll look at the addition of two variables. Here’s how you might write that code in JavaScript:

Hopefully the above code is pretty straight forward. We’ve declared our variables x , and y , and assigned them values of 1 and 2 respectively. We then set x equal to x + y . When we log out x , we get 3 !

Now, here’s what the shorthand code to do this looks like:

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. Here’s a cheat sheet which shows longhand on the left and shorthand on the right:

Want to Learn More Shorthands?

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

  • JavaScript — Shorthand Variable Assignment
  • 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..

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

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

JavaScript — WTF is ES6, ES8, ES 2017, ECMAScript… ?

JavaScript — WTF is ES6, ES8, ES 2017, ECMAScript… ?

Learn javascript and ecmascript history and naming conventions is this javascript quickie, recommended from medium.

Exploring Call, Apply, and Bind Methods in JavaScript

Rabail Zaheer

Exploring Call, Apply, and Bind Methods in JavaScript

Functions are the building blocks of javascript, empowering developers to create reusable and modular code. they play a pivotal role in….

Shallow and Deep Copy in JavaScript: A Guide with Lodash, structuredClone, and JSON Methods

Navneet Singh

Shallow and Deep Copy in JavaScript: A Guide with Lodash, structuredClone, and JSON Methods

When working with javascript objects and arrays, understanding the concepts of shallow copy and deep copy is crucial. in this article….

javascript object assignment shorthand

General Coding Knowledge

javascript object assignment shorthand

Stories to Help You Grow as a Software Developer

javascript object assignment shorthand

Coding & Development

javascript object assignment shorthand

ChatGPT prompts

LeetCode Problem 2620 Counter — LeetCode: 30 Days of JavaScript

Evan Roberts

LeetCode Problem 2620 Counter — LeetCode: 30 Days of JavaScript

Solving leetcode 30 days of javascript study plan problems.

The Complete Guide To JavaScript Functions

Ekaterine Mitagvaria

The Complete Guide To JavaScript Functions

Functions are the building block of javascript. this guide covers functions from basic to advanced level….

Interviewer: Can sessionStorage Share Data Between Multiple Tabs?

JavaScript in Plain English

Interviewer: Can sessionStorage Share Data Between Multiple Tabs?

The question that most front-end developers don’t know the answer.

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.

Text to speech

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

JavaScript Object Literal-Computed Property Names Example

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

Example2: JavaScript Object Literal-Computed Property Names

Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables in JavaScript with Examples

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

Use Variable as Object Key/ Computed Property Names in JavaScript

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

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’

Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables in JavaScript with Examples

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

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

Object Property Initializer Shorthand / Short Properties / Property Value Shorthand’s /Duplicate Property Names /Object Initialization from Variables in JavaScript with Examples

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

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

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

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.

dotnettutorials 1280x720

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 *

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

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.

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

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.

Similarly, you can destructure objects on the left-hand side of the assignment.

This capability is similar to features present in languages such as Perl and Python.

For features specific to array or object destructuring, refer to the individual examples below.

Binding and assignment

For both object and array destructuring, there are two kinds of destructuring patterns: binding pattern and assignment pattern , with slightly different syntaxes.

In binding patterns, the pattern starts with a declaration keyword ( var , let , or const ). Then, each individual property must either be bound to a variable or further destructured.

All variables share the same declaration, so if you want some variables to be re-assignable but others to be read-only, you may have to destructure twice — once with let , once with const .

In many other syntaxes where the language binds a variable for you, you can use a binding destructuring pattern. These include:

  • The looping variable of for...in for...of , and for await...of loops;
  • Function parameters;
  • The catch binding variable.

In assignment patterns, the pattern does not start with a keyword. Each destructured property is assigned to a target of assignment — which may either be declared beforehand with var or let , or is a property of another object — in general, anything that can appear on the left-hand side of an assignment expression.

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{ a, b } = { a: 1, b: 2 } is not valid stand-alone syntax, as the { a, b } on the left-hand side is considered a block and not an object literal according to the rules of expression statements . However, ({ a, b } = { a: 1, b: 2 }) is valid, as is const { a, b } = { a: 1, b: 2 } .

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

Note that the equivalent binding pattern of the code above is not valid syntax:

You can only use assignment patterns as the left-hand side of the assignment operator. You cannot use them with compound assignment operators such as += or *= .

Default value

Each destructured property can have a default value . The default value is used when the property is not present, or has value undefined . It is not used if the property has value null .

The default value can be any expression. It will only be evaluated when necessary.

Rest property

You can end a destructuring pattern with a rest property ...rest . This pattern will store all remaining properties of the object or array into a new object or array.

The rest property must be the last in the pattern, and must not have a trailing comma.

Array destructuring

Basic variable assignment, destructuring with more elements than the source.

In an array destructuring from an array of length N specified on the right-hand side of the assignment, if the number of variables specified on the left-hand side of the assignment is greater than N , only the first N variables are assigned values. The values of the remaining variables will be undefined.

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick ).

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.

Ignoring some returned values

You can ignore return values that you're not interested in:

You can also ignore all returned values:

Using a binding pattern as the rest property

The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after collecting the rest elements, so you cannot access any properties present on the original iterable in this way.

These binding patterns can even be nested, as long as each rest property is the last in the list.

On the other hand, object destructuring can only have an identifier as the rest property.

Unpacking values from a regular expression match

When the regular expression exec() method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

Using array destructuring on any iterable

Array destructuring calls the iterable protocol of the right-hand side. Therefore, any iterable, not necessarily arrays, can be destructured.

Non-iterables cannot be destructured as arrays.

Iterables are only iterated until all bindings are assigned.

The rest binding is eagerly evaluated and creates a new array, instead of using the old iterable.

Object destructuring

Basic assignment, assigning to new variable names.

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

Here, for example, const { p: foo } = o takes from the object o the property named p and assigns it to a local variable named foo .

Assigning to new variable names and providing default values

A property can be both

  • Unpacked from an object and assigned to a variable with a different name.
  • Assigned a default value in case the unpacked value is undefined .

Unpacking properties from objects passed as a function parameter

Objects passed into function parameters can also be unpacked into variables, which may then be accessed within the function body. 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 to assign default values for the case when the original object does not define the property.

Consider this object, which contains information about a user.

Here we show how to unpack a property of the passed object into a variable with the same name. The parameter value { id } indicates that the id property of the object passed to the function should be unpacked into a variable with the same name, which can then be used within the function.

You can define the name of the unpacked variable. Here we unpack the property named displayName , and rename it to dname for use within the function body.

Nested objects can also be unpacked. The example below shows the property fullname.firstName being unpacked into a variable called name .

Setting a function parameter's default value

Default values can be specified using = , and will be used as variable values if a specified property does not exist in the passed object.

Below we show a function where the default size is 'big' , default co-ordinates are x: 0, y: 0 and default radius is 25.

In the function signature for drawChart above, the destructured left-hand side has a default value of an empty object = {} .

You could have also written the function without that default. However, if you leave out that default value, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can call drawChart() without supplying any parameters. Otherwise, you need to at least supply an empty object literal.

For more information, see Default parameters > Destructured parameter with default value assignment .

Nested object and array destructuring

For of iteration and destructuring, computed object property names and destructuring.

Computed property names, like on object literals , can be used with destructuring.

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifier that is valid.

Destructuring primitive values

Object destructuring is almost equivalent to property accessing . This means if you try to destruct a primitive value, the value will get wrapped into the corresponding wrapper object and the property is accessed on the wrapper object.

Same as accessing properties, destructuring null or undefined throws a TypeError .

This happens even when the pattern is empty.

Combined array and object destructuring

Array and object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following:

The prototype chain is looked up when the object is deconstructed

When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.

Specifications

Browser compatibility.

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

  • Assignment operators
  • ES6 in Depth: Destructuring on hacks.mozilla.org (2015)

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.

IMAGES

  1. 16 JavaScript Shorthand Coding Techniques

    javascript object assignment shorthand

  2. JavaScript Shorthand Techniques

    javascript object assignment shorthand

  3. Top JavaScript Shorthand Techniques

    javascript object assignment shorthand

  4. 20 JavaScript Shorthand Techniques that will save your time

    javascript object assignment shorthand

  5. Object Property Initializer Shorthand in JavaScript

    javascript object assignment shorthand

  6. Code Faster with JavaScript Shorthands

    javascript object assignment shorthand

VIDEO

  1. Attributes in Javascript

  2. Remove Properties From JavaScript Object (Copy) #javascript #javascriptlearning #javascriptdeveloper

  3. JavaScript Shorthand Tip's Part 6 If Presence #coding #webdesign #codinglife #codingmotivation #js

  4. object methods JavaScript

  5. object in javascript s -1 #khatushyam #shortvideo #viral

  6. Smart Object Assignment one for final exam

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

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

  4. Object.assign()

    The Object.assign () method only copies enumerable and own properties from a source object to a target object. It uses [ [Get]] on the source and [ [Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties, versus copying or defining new properties.

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

  6. 25+ JavaScript Shorthand Coding Techniques

    3. Declaring Variables Shorthand. 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 ...

  7. Enhanced Object Literal Value Shorthand: JavaScript ES6 ...

    Objects: Everything in JavaScript is one. When it comes to JavaScript, you may have heard the phrase thrown around that "everything in JavaScript is an object." Functions, strings, arrays, objects — they're all objects. ... // es2015 shorthand object property assignment const otherBreed = "alpaca"; const firstName = "Alfie"; ...

  8. Object Literals Using Object Property Shorthand

    The object is then returned. When the function runs we can see from the console log the object with the corresponding values. When ES6 was created object property shorthand was introduced. Object property shorthand enables us to simply pass in the name of the key as opposed to repeating the name and the key.

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

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

  11. 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). The ...

  12. Shorthand Property and Method Names in JavaScript

    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, function formatMessage (name, id, avatar) {. return {.

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

  14. Enhancing Objects: Advanced Object Literals in JavaScript

    An object literal is a simple way to create and define objects in JavaScript. It consists of a collection of key-value pairs enclosed within curly braces {}. Each key represents a property, and ...

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

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

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

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

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

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