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

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.

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

assignment shorthand js

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

18 JavaScript and TypeScript Shorthands to Know

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

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

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

Jump ahead:

JavaScript and TypeScript shorthands

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

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

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

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

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

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

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

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

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

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

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

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

Here are two examples of the nullish coalescing operator:

Example one

Example two, logical nullish assignment operator.

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

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

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

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

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

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

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

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

See an example of the object property assignment shorthand below:

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

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

See an example of optional chaining in action below:

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

assignment shorthand js

Over 200k developers use LogRocket to create better digital experiences

assignment shorthand js

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

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

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

The traditional JavaScript for loop syntax is as follows:

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

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

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

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

The examples below demonstrate these object loop shorthands in action:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The example below demonstrates this exponent power shorthand in action:

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

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

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

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

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

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

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

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

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

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

LogRocket : Debug JavaScript errors more easily by understanding the context

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

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

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

Try it for free .

Share this:

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

assignment shorthand js

Stop guessing about your digital experience with LogRocket

Recent posts:.

Using Pavex For Rust Web Development

Using Pavex for Rust web development

The Pavex Rust web framework is an exciting project that provides high performance, great usability, and speed.

assignment shorthand js

Using the ResizeObserver API in React for responsive designs

With ResizeObserver, you can build aesthetic React apps with responsive components that look and behave as you intend on any device.

assignment shorthand js

Creating JavaScript tables using Tabulator

Explore React Tabulator to create interactive JavaScript tables, easily integrating pagination, search functionality, and bulk data submission.

assignment shorthand js

How to create heatmaps in JavaScript: The Heat.js library

This tutorial will explore the application of heatmaps in JavaScript projects, focusing on how to use the Heat.js library to generate them.

assignment shorthand js

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

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

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

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

Have a good day

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

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

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

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

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

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

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

Good List of useful operators

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

Leave a Reply Cancel reply

assignment shorthand js

JavaScript — Shorthand Variable Assignment

A three minute introduction into shorthand variable assignment.

Brandon Morelli

Brandon Morelli

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

Assigning Variables to Other Variables

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

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

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

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

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

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

Using Commas When Assigning Variables

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

We can shorthand this code using commas:

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

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

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

Want to Learn More Shorthands?

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

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

Closing Notes:

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

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

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

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

Brandon Morelli

Written by Brandon Morelli

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

More from Brandon Morelli and codeburst

10 Awesome Web Developer Portfolios

10 Awesome Web Developer Portfolios

Get inspired with these 10 web developer portfolios..

How To Create Horizontal Scrolling Containers

How To Create Horizontal Scrolling Containers

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

Top 50 Java Interview Questions for Beginners and Junior Developers

Top 50 Java Interview Questions for Beginners and Junior Developers

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

JavaScript ES 2017: Learn Async/Await by Example

JavaScript ES 2017: Learn Async/Await by Example

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

Mastering DOM Manipulation with JavaScript: Tips and Best Practices

Aditya Armal

Mastering DOM Manipulation with JavaScript: Tips and Best Practices

Dom (document object model) manipulation is a crucial aspect of web development. it allows developers to interact with and modify the….

Dealing With Large Data In Javascript

Deniz Peker

Dealing With Large Data In Javascript

In current software development processes, we may have to perform issues such as filtering large amounts of data and processing data….

assignment shorthand js

General Coding Knowledge

assignment shorthand js

Stories to Help You Grow as a Software Developer

assignment shorthand js

Coding & Development

assignment shorthand js

ChatGPT prompts

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.

Closures in JavaScript

Snehal Vyawahare

Closures in JavaScript

In javascript, a closure is a combination of a function and the lexical environment within which that function was declared. closures allow….

best html css website templates

70+ Best Moderns Free HTML CSS Website Templates

Are you looking for either a simple free but professional html css template to design a showcase site, a langing page or other ….

Day-3 of Learning JavaScript: Unveiling the Magic of Code: Crafting a Simple Calculator

Aniket Saini

Day-3 of Learning JavaScript: Unveiling the Magic of Code: Crafting a Simple Calculator

Greetings, fellow code artisans today, we embark on an enchanting journey to conjure a digital oracle — an elementary calculator that….

Text to speech

  • Web Development

JavaScript Shorthand Coding Techniques

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

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

Assignment Operators Shorthand

Boolean comparison shorthand.

The conventional way:

The shortcut way:

Get a Character From String Shorthand

Create a link shorthand.

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

Create an Array Shorthand

Create an object shorthand.

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

Regular Expressions Testing Shorthand

Shorthand using the comma operator.

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

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

Using the Ternary (conditional) Operator

Common usage:.

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

Other Usage:

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

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

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

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

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

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

Shorthand Coding With Truthy and Falsy

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

Truthy (values that evaluate to true ):

Falsy (values that evaluate to false ):.

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

With that information, code like the following is possible:

indexOf() Shorthand

String contains:, string does not contain:.

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

Type Casting Shorthands

Converting to boolean:.

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

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

Converting to Number:

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

Converting to String:

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

Self-Calling Anonymous Functions

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

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

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

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

Other Syntax:

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

Shorthand Coding by Short-Circuiting Evaluations

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

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

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

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

With that knowledge, consider the following conventional code:

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

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

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

Specifying Default Values:

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

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

Set Value If Truthy:

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

Eager (Non-Short-Circuited) Evaluations

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

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

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

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

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

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

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

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

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

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

Home » JavaScript Tutorial » JavaScript Assignment Operators

JavaScript Assignment Operators

Summary : in this tutorial, you will learn how to use JavaScript assignment operators to assign a value to a variable.

Introduction to JavaScript assignment operators

An assignment operator ( = ) assigns a value to a variable. The syntax of the assignment operator is as follows:

In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a .

The following example declares the counter variable and initializes its value to zero:

The following example increases the counter variable by one and assigns the result to the counter variable:

When evaluating the second statement, JavaScript evaluates the expression on the right-hand first ( counter + 1 ) and assigns the result to the counter variable. After the second assignment, the counter variable is 1 .

To make the code more concise, you can use the += operator like this:

In this syntax, you don’t have to repeat the counter variable twice in the assignment.

The following table illustrates assignment operators that are shorthand for another operator and the assignment:

Chaining JavaScript assignment operators

If you want to assign a single value to multiple variables, you can chain the assignment operators. For example:

In this example, JavaScript evaluates from right to left. Therefore, it does the following:

  • Use the assignment operator ( = ) to assign a value to a variable.
  • Chain the assignment operators if you want to assign a single value to multiple variables.

Jscurious.com Logo

Web Development Blog

20+ JavaScript tips and tricks that you should know

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

1. Assigning values to multiple variables

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

2. The Ternary operator

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

3. Assigning a default value

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

4. Remove duplicates from an Array

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

Reference: JavaScript Set object to store unique values

5. AND(&&) Short circuit evaluation

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

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

6. Swap two variables

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

7. Arrow Function

Reference : JavaScript Arrow function

8. Template Literals

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

9. Multi-line String

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

10. Multiple condition checking

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

11. Object Property Assignment

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

12. String into a Number

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

13. Repeat a string multiple times

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

14. Exponent Power

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

15. Double NOT bitwise operator (~~)

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

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

16. Find the max and min numbers in an array

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

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

17. For loop

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

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

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

18. Merging of arrays

19. remove properties from an object.

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

20. Get character from string

21. remove falsy values from array.

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

22. Create a random string token

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

Amitav Mishra

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

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

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

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

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

Leave a Reply Cancel reply

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

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

Shorthand Property and Method Names in JavaScript | ES6

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

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

Object initializer

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

Description

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties , which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

Object literal syntax vs. JSON

The object literal syntax is not the same as the J ava S cript O bject N otation ( JSON ). 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. Computed property names are not allowed either.
  • JSON object property values can only be strings, numbers, true , false , null , arrays, or another JSON object. This means JSON cannot express methods or non-plain objects like Date or RegExp .
  • In JSON, "__proto__" is a normal property key. In an object literal, it sets the object's prototype .

JSON is a strict subset of the object literal syntax, meaning that every valid JSON text can be parsed as an object literal, and would likely not cause syntax errors. The only exception is that the object literal syntax prohibits duplicate __proto__ keys, which does not apply to JSON.parse() . The latter treats __proto__ like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the __proto__ key — for object literals, it sets the object's prototype; for JSON, it's a normal property.

Creating objects

An empty object with no properties can be created like this:

However, the advantage of the literal or initializer notation is, that you are able to quickly create objects with properties inside the curly braces. You notate a list of key: value pairs delimited by commas.

The following code creates an object with three properties and the keys are "foo" , "age" and "baz" . The values of these keys are a string "bar" , the number 42 , and another object.

Accessing properties

Once you have created an object, you might want to read or change them. Object properties can be accessed by using the dot notation or the bracket notation. (See property accessors for detailed information.)

Property definitions

We have already learned how to notate properties using the initializer syntax. Oftentimes, there are variables in your code that you would like to put into an object. You will see code like this:

There is a shorter notation available to achieve the same:

Duplicate property names

When using the same name for your properties, the second property will overwrite the first.

After ES2015, duplicate property names are allowed everywhere, including strict mode . You can also have duplicate property names in classes . The only exception is private properties , which must be unique in the class body.

  • Method definitions

A property of an object can also refer to a function or a getter or setter method.

A shorthand notation is available, so that the keyword function is no longer necessary.

There is also a way to concisely define generator methods.

Which is equivalent to this ES5-like notation (but note that ECMAScript 5 has no generators):

For more information and examples about methods, see method definitions .

Computed property names

The object initializer syntax also supports computed property names. That allows you to put an expression in square brackets [] , that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.

Now you can use a similar syntax in object literals, too:

Spread properties

Object literals support the spread syntax . It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype ) or merging objects is now possible using a shorter syntax than Object.assign() .

Warning: Note that Object.assign() triggers setters , whereas the spread syntax doesn't!

Prototype setter

A property definition of the form __proto__: value or "__proto__": value does not create a property with the name __proto__ . Instead, if the provided value is an object or null , it points the [[Prototype]] of the created object to that value. (If the value is not an object or null , the object is not changed.)

Note that the __proto__ key is standardized syntax, in contrast to the non-standard and non-performant Object.prototype.__proto__ accessors. It sets the [[Prototype]] during object creation, similar to Object.create — instead of mutating the prototype chain.

Only a single prototype setter is permitted in an object literal. Multiple prototype setters are a syntax error.

Property definitions that do not use "colon" notation are not prototype setters. They are property definitions that behave identically to similar definitions using any other name.

Specifications

Browser compatibility.

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

  • Property accessors
  • Lexical grammar

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!

IMAGES

  1. 16 JavaScript Shorthand Coding Techniques

    assignment shorthand js

  2. Top JavaScript Shorthand Techniques

    assignment shorthand js

  3. JavaScript Shorthand Techniques

    assignment shorthand js

  4. Assignment Operator (Shorthand) in JavaScript Tutorial

    assignment shorthand js

  5. Shorthand Property and Method Names in JavaScript

    assignment shorthand js

  6. 18 JavaScript and TypeScript shorthands to know

    assignment shorthand js

VIDEO

  1. AUGUST 2023 SHORTHAND EXAM RESULT

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

  3. ENGLISH SHORTHAND DICTATION

  4. CRPF Typing Test

  5. Shorthand cricket #shorthandcricket #cricketlover

  6. FEBRUARY 2011 SHORTHAND ENGLISH SENIOR SPEED DICTATION

COMMENTS

  1. 25+ JavaScript Shorthand Coding Techniques

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

  2. JavaScript Assignment

    Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.

  3. Expressions and operators

    An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal (=), which assigns the value of its right operand to its left operand.That is, x = f() is an assignment expression that assigns the value of f() to x. There are also compound assignment operators that are shorthand for the operations listed in the ...

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

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

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

  7. javascript

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

  8. 15+ JavaScript Shorthand Coding Techniques for Beginners

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

  9. 12 Good JavaScript Shorthand Techniques

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

  10. JavaScript Assignment Operators

    An assignment operator ( =) assigns a value to a variable. The syntax of the assignment operator is as follows: let a = b; Code language: JavaScript (javascript) In this syntax, JavaScript evaluates the expression b first and assigns the result to the variable a. The following example declares the counter variable and initializes its value to zero:

  11. Mastering JavaScript Shorthand: Declaring Variables, Assignment

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

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

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

  13. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  14. Shorthand Property and Method Names in JavaScript

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

  15. Object initializer

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

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

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

  18. javascript

    How can I merge properties of two JavaScript objects dynamically? - user120242. Jun 21, 2020 at 8:33. react shorthand for passing props - user120242. ... How shorthand for assign more property object in js. 81. How to dynamically access object property in TypeScript. Hot Network Questions

  19. How do you use the ? : (conditional) operator in JavaScript?

    It's a little hard to google when all you have are symbols ;) The terms to use are "JavaScript conditional operator". If you see any more funny symbols in JavaScript, you should try looking up JavaScript's operators first: Mozilla Developer Center's list of operators. The one exception you're likely to encounter is the $ symbol.

  20. What is JavaScript shorthand property?

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