NX Team

50 JS Shorthand Book

By NX Team

Last updated cal_iconJanuary 31, 2023

NX Team

 

Example 1: Flatten array

1. The flat method in JavaScript is used to flatten an array up to the required depth
2. If you are not sure about the depth, use flat(infinity) to flatten the array of any depth

Example Flatten array

 

Example 2: Array concatenation

You can merge different arrays and also add new elements to an existing one using spread syntax.

Example

 

Example 3: Template Literals

Example Template Literals

 

Example 4: Use of for/in and for/of

  1. for/in – loops through the properties of an object
  2. for/of – loops through the values of an iterable object

Example Use of for in and for of

 

Example 5: Using length to delete or reduce an array length

Example Using length to delete or reduce an array length

 

Example 6: Remove Duplicates

The new Set will implicitly remove duplicate elements. Then we will convert this set back to the unique array.

Example Remove Duplicates

 

Example 7: Remove falsy values

The ‘.Filter(boolean) ‘ just removes values from a list which are “falsy”

Example Remove falsy values

 

Example 8.1: JSON.stringify

You can use JSON.Stringify ‘s second replacer parameter to pluck specific fields from it, by passing in an array

Example JSON.stringify

 

Example 8.2: JSON.stringify

If your data object holds sensitive data, you can use the replacer to filter that part out:

Example 8.2 JSON.stringify

 

Example 8.3: JSON.stringify

A string or number that’s used to insert white space (including indentation, line break characters, etc.) Into the output JSON string for readability purposes.

Example 8.3 JSON.stringify

 

Example 9: Find method in array

Returns the value of the first element in the array that satisfies the given function and returns undefined if none of the elements satisfy the function.

Example Find method in array

 

Example 10: Arrow 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).

Example Arrow function

 

Example 11: Mandatory parameter shorthand

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’

Example Mandatory parameter shorthand

 

Example 12: Default Parameter Values

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

Example Default Parameter Values

 

Example 13: Ternary operator

We used the ternary operator as a shorthand for an if else statement

Example Ternary operator

 

Example 14: Optional Chaining

Optional chaining (Variables) – The optional chaining ?. stops the evaluation if the value before ?. is  undefined or null and returns undefined.

Example Optional Chaining

 

Example 15: Optional Chaining

Optional chaining (Variables) -The optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.
Function will call only if it’s not null and undefined

Example Optional Chaining

 

Example 16: Object Property Assignment

There is no limit to the number of object properties you can merge

Example Object Property Assignment

 

Example 17: Object Property Shorthand

If the variable name is the same as the object key, you can take advantage of the shorthand notation

Example Object Property Shorthand

 

Example 18: Structured cloning of objects

The global structuredClone method creates a deep clone of a given value using the structured clone algorithm

Example Structured cloning of objects

 

Example 19: …rest operator

…Rest help us remove a property from an object via destructuring

Example rest operator

 

Example 20: Nested object destructuring

Object destructuring assigns the properties of an object to variables with the same names by default

Example Nested object destructuring

 

Example 21: Swapping of variables

Destructuring assignment – Destructuring assignment lets you extract items of an array into variables

Example Swapping of variables

 

Example 22: Destructuring assignment

You can assign multiple values at the same time using destructuring

Example Destructuring assignment

 

Example 23: Alternative for a Switch statement

You can use an object with function names associated with a key as an alternative for a switch statement

Example Alternative for a Switch statement

 

Example 24: Convert Values to Boolean

Convert Values to Boolean

 

Example 25: Double tilde operator

You can use ~~ instead of Math.floor() to find the floor value of a number with a decimal point in a much quicker and easy way.

Double tilde operator

 

Example 26: String to Number Conversion

You can convert a string into a number in a much simpler way using the + operator like shown

String to Number Conversion

 

Example 27: Get character from string

Get character from string

 

Example 28: Decimal base exponents

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.

Decimal base exponents

 

Example 29: Declaring Variables Shorthand

Declaring multiple variables at the same time

Declaring Variables Shorthand

 

Example 30: Repeat Method

The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

Example 30: Repeat Method

 

Example 31: Timestamp Shorthand

When a date object is converted to number, it becomes the timestamp same as date.Gettime()

Timestamp Shorthand

 

Example 32: Variable scope in switch case

Block scope in switch cases: this will not throw an error for reassigning the const

Variable scope in switch case

 

Example 33: TypeScript constructor shorthand

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.

TypeScript constructor shorthand

 

Example 34: Declaration and initialization in same line

Declaring multiple variables at the same time with same value

Declaration and initialization in same line

Example 35: Exponentiation Operator

When you want to raise the power of a given number, you use the Math.pow. Instead, you can do the same using the ** in a much easier way

Exponentiation Operator

 

Example 36: Unary  ~ operator

Use ~ to coerce any non-number to –1.
Used together with the unary -, this is a great way to increment numerical variables not yet initialized

Unary  operator

 

Example 37: Round Number

Round number

 

Example 38: Find min and max in array

We can also use the Array.reduce() method to find the max and min number in the array. But using a spread operator we can do it in a single line.

Find min and max in array

 

Example 39: Find min, max, sum in array using reduce

Find out the sum, minimum and maximum value.
We should make use of reduce method to quickly find basic math’s operations.

 

Example 40: Base64 format

Convert the file into base64 format

Base64 format

 

Example 41: Int conversion, replace method

Remove comma and convert to int

Int conversion, replace method

 

Example 42: Logical OR and nullish coalescing operator

  1. || returns the right-hand side operand if the left operand is any falsy value, not only null or undefined
  2. returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand

Logical OR and nullish coalescing operator

 

Example 43: IndexOf and includes method

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

IndexOf and includes method

 

Example 44: RegExp object shorthand

RegExp object shorthand

 

Example 45.1: Truthiness

In javascript, truthiness is whether something returns true or false in an if statement

Truthiness

 

Example 45.2: Truthiness

Example 45.2: Truthiness

 

Example 46: Logical AND

  1. The expression is evaluated as follows: Starting from left and moving to the right, return the first operand that is falsy
  2. If no falsy operand was found, return the latest operand

Logical AND

 

Example 47: every method in array

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value

every method in array

 

Example 48: Caching data

 Caching data

 

Example 49: Alternative of if else

 Alternative of if else

 

Example 50: Embed functionality within arguments

Save delimiters by processing stuff within (unused) arguments

Embed functionality within arguments

 

Github repository link:

https://github.com/successive-saurabh/js-shorthand

 

 

 

 

 

 

 

Get In Touch

How Can We Help ?

We make your product happen. Our dynamic, robust and scalable solutions help you drive value at the greatest speed in the market

We specialize in full-stack software & web app development with a key focus on JavaScript, Kubernetes and Microservices
Your path to drive 360° value starts from here
Enhance your market & geographic reach by partnering with NodeXperts