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
Get In Touch
Ketan Jadhav
Closures in JavaScript
According to the internet, javascript is an object-oriented programming language commonly used to create interactive effects within web browsers.
Many of us use javascript in our day to day life, but we never paid attention to concepts of it. JavaScript closures are one of those concepts that many people have trouble understanding.
If you want to save yourself from the so-called monsters of JavaScript, you must understand how it works. I’ll explain what a closure is in clear terms and relate it to a real-life example to make it easier to remember.
So, What is Closure?
A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function’s variables.
Let’s understand it using below code snippet:
Here we have two functions:
- An outerFunc with variable f_name and returning innerFunc.
- An innerFunc with its variable l_name and also accessing outerFunc variable f_name.
The scope of variable f_name is limited to the outerFunc function, and the scope of a variable l_name is limited to the innerFunc function.
Now, what happened when this line of code was executed.
var getName = outerFunc();
getName();
Result of outerFunc() gets stored in a variable called getName and now is a function type.
And, Now comes the interesting part.
When getName() function gets executed:
- It creates a variable called l_name and assigns a value John to it.
- Now, javascript try to execute console.log(“Name: “, f_name, l_name); , javascript knows that l_name variable is exist as it is just now created, but f_name is no longer existed because f_name is a part of outerFunc() and it will only exist if outerFunc() is in execution. So here f_name is no longer exists.
Then how will we get the f_name variable?
The answer is Closure!, yes you heard it right.
During the execution of the parent function, it passes its scope chain to the child function, and in this way, the child can access the variables that are preserved(closure) in the preserved variable.
So, our innerFunc() will preserve the variable f_name=”John” when the outerFunc() is implemented and kept holding it.
Now, on execution of getName function(child function), it has its own scope now, and scope also contains variable f_name because it has preserved variable within its own closure(scope) at the execution of parent function.
In this way, Javascript knows f_name = “John” and l_name = “Washington” , and we will get output as: Name: John Washington.
Closure stores the references of variables of outer function.
Hurrey!Now you have completely understood what closure is in javascript.
Conclusion:
Closures are one of those concepts in javascript which is difficult to understand at the beginning, But one if you understand it carefully, it isn’t that bad or difficult.
Closures will allow us to access the variables and functions even after the execution of those functions has done.
Get In Touch
Shashank Baranawal
Hoisting in JavaScript
Let’s talk about hoisting in JavaScript, how it works and how we can benefit from it.
JavaScript’s another beautiful part that makes us love language.
So, let’s start with this :
What is Hoisting in JavaScript?
In simple and easy words hoisting in javascript means hosting is the action of moving all the variable and function declarations of the javascript interpreter to the top of the current scope before the code execution. It allows us to access the variables and functions anywhere in their scope, no matter where they are declared.
We will see various examples below that will help us better understand the Variable and function hoisting behavior of JavaScript.
In this article we will talk about:
- Hoisting Variable
- Hoisting Functions
Before moving on to hoisting, you must know undeclared variables do not exist until the code assigning them is executed.
All undeclared variables are global variables.
Hoisting Variable ?
The scope of a variable declared with the keyword var is its current execution context. This is either the enclosing function or for variables declared outside any function, global.
Consider the below piece of code and let’s see what the output would be.
Javascript hoists our variable language to the top of the file and declares is there but it does not set it equal to anything, then as the interpreter moves through the file to where the variable was initially declared and sets the variable equal to the correct value which is javascript.
Output:-
You can see our first console log was undefined and the second console log was the value javascript since it ran through the file and set the language variable equal to javascript.
Note? : Although it seems that the declaration has moved up in the program in hoisting, what happens here is that the function and variable declarations are added to memory during the compile phase.
When the variable is declared inside the function, it will be hoisted at the top of the function, see the below example.
Output:-
We get a reference error when we try to access a topic variable in the console statement outside the function because the variable topic is hoisted at the top of the greet function instead of the top of the program, and it becomes a local variable instead of the global variable.
Variables declared with let and const remain uninitialized at the beginning of execution while variables declared with var are initialized with a value of undefined.
Hoisting Function?
Same as variable declarations are hoisted and moved to the top, functions that are declared also get hoisted.
Output:-
We have called the helloHoisting() function before its declaration and get the desired output due to hoisting, the program is executed as follows:
function declaration is moved to the top due to hoisting!
However it we use functions as an expression then it’s not hoisted because be it variable or function hoisting it only works with var keyword, see below:
Output:- ReferenceError: Cannot access ‘sayHello’ before initialization
ES6: let Keyword
Output:-
As before, for the var keyword, we expect the output to be undefined. But this time we got a reference error. Does that mean let and const variables were not hoisted? The answer is that variables declared with let are still hoisted, but not initialized, inside their nearest enclosing block. If we try to access it before initialization, it will throw a Reference Error.
Conclusion?:
Hoisting is the default behavior of JavaScript that enables us to access variables and functions before their declaration. Hoisting works with var keyword and not let and const keywords, just the declarations are hoisted and not the initialization. If a variable is declared inside the function it will be hoisted at the top of the function and not at the global scope level. Functions are hoisted too, but functions as an expression are not.