NX Team
50 JS Shorthand Book
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 2: Array concatenation
You can merge different arrays and also add new elements to an existing one using spread syntax.
Example 3: Template Literals
Example 4: Use of for/in and for/of
- for/in – loops through the properties of an object
- for/of – loops through the values of an iterable object
Example 5: 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 7: Remove falsy values
The ‘.Filter(boolean) ‘ just removes values from a list which are “falsy”
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 8.2: JSON.stringify
If your data object holds sensitive data, you can use the replacer to filter that part out:
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 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 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 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 12: Default Parameter Values
- 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
Example 13: Ternary operator
We used the ternary operator as a shorthand for an if else statement
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 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 16: Object Property Assignment
There is no limit to the number of object properties you can merge
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 18: Structured cloning of objects
The global structuredClone method creates a deep clone of a given value using the structured clone algorithm
Example 19: …rest operator
…Rest help us remove a property from an object via destructuring
Example 20: Nested object destructuring
Object destructuring assigns the properties of an object to variables with the same names by default
Example 21: Swapping of variables
Destructuring assignment – Destructuring assignment lets you extract items of an array into variables
Example 22: Destructuring assignment
You can assign multiple values at the same time using destructuring
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 24: 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.
Example 26: String to Number Conversion
You can convert a string into a number in a much simpler way using the + operator like shown
Example 27: 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.
Example 29: Declaring Variables Shorthand
Declaring multiple variables at the same time
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 31: Timestamp Shorthand
When a date object is converted to number, it becomes the timestamp same as date.Gettime()
Example 32: Variable scope in switch case
Block scope in switch cases: this will not throw an error for reassigning the const
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.
Example 34: Declaration and initialization in same line
Declaring multiple variables at the same time with same value
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
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
Example 37: 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.
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
Example 41: Int conversion, replace method
Remove comma and convert to int
Example 42: Logical OR and nullish coalescing operator
- || returns the right-hand side operand if the left operand is any falsy value, not only null or undefined
- returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand
Example 43: IndexOf and includes method
For multiple value matching, we can put all values in an array and use indexof() or includes() method.
Example 44: RegExp object shorthand
Example 45.1: Truthiness
In javascript, truthiness is whether something returns true or false in an if statement
Example 45.2: Truthiness
Example 46: Logical AND
- The expression is evaluated as follows: Starting from left and moving to the right, return the first operand that is falsy
- If no falsy operand was found, return the latest operand
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
Example 48: Caching data
Example 49: Alternative of if else
Example 50: Embed functionality within arguments
Save delimiters by processing stuff within (unused) arguments
Github repository link:
https://github.com/successive-saurabh/js-shorthand