1. Declare variables
It is a good practice to declare variable assignment at the beginning of a function. This shorthand method can save you a lot of time and space when declaring multiple variables at the same time.
Common writing
let x; let y; let z = 3;
Simplified writing
let x, y, z=3;
2. Use ternary operators
Your life becomes easier when you start using ternary conditions instead of if... else statements.
Common writing
const age = 26; let eligibility; if(age > 18){ eligibility = "Allowed"; } else{ eligibility = "Not Allowed"; }
Simplified writing
let eligibility = (age > 18) ? "Allowed" : "Not Allowed";
You can also if nest your statements like this:
let eligibility = age > 10 ? "greater than 10" : (age < 5 ? "less than 5" : "between 5 and 10");
3. JavaScript For loop
This tip is useful if you want pure JavaScript and don't want to rely on external libraries such as jQuery or lodash.
Common writing
const fruits = ['mango', 'peach', 'banana']; for (let i = 0; i < fruits.length; i++)
Simplified writing
for (let fruit of fruits)
If you only want to access the index:
for (let index in fruits)
This also applies if you want to access keys in text objects:
const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'} for (let key in obj) console.log(key) // output: continent, country, city
Abbreviation of Array.forEach:
function logArrayElements(element, index, array) { console.log("a[" + index + "] = " + element); } [5, 7, 2].forEach(logArrayElements); // a[0] = 5 // a[1] = 7 // a[2] = 2
4. Array lookup
If you've ever been asked to write a find function in pure JavaScript, you might use a for loop. In ES6, find() introduces a new array function called.
Common writing
const pets = [ { type: 'Dog', name: 'Max'}, { type: 'Cat', name: 'Karl'}, { type: 'Dog', name: 'Tommy'}, ] function findDog(name) { for(let i = 0; i<pets.length; ++i) { if(pets[i].type === 'Dog' && pets[i].name === name) { return pets[i]; } } }
Simplified writing
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy'); console.log(pet); // { type: 'Dog', name: 'Tommy' }
5. Use of if
This may be trivial, but it is worth mentioning. In case of "if check", the assignment operator can sometimes be omitted
Common writing
if (isLovely === true)
Simplified writing
if (isLovely)
Also, note that the two examples are not exactly equal because as long as isLovely is Truth value The shorthand check will pass.
This is another example. If a is not equal to true, some actions are performed.
Common writing
let a; if ( a !== true ) { // do something... }
Simplified writing
let a; if ( !a ) { // do something... }
Bonus: formatting JSON code
When you want to format JSON objects or JSON responses without using any third-party tools. Open your browser console and click the following command to format your JSON.
The stringify method requires three inputs. Value, replace and space. Maybe you only know the value!
The next two are optional parameters. That's why we don't use them in a general way. To indent our JSON, we must use the space parameter.
console.log(JSON.stringify({name:"Rax",Age:26},null,'\t'));
6. Arrow function
Classic functions are easy to read and write in their simple form, but once you start nesting them in other function calls, they become a little verbose and confusing.
Common writing
function sayHi(name) { console.log('Hello Rax', name); } setTimeout(function() { console.log('Loaded') }, 2000); list.forEach(function(item) { console.log(item); });
Simplified writing
sayHi = name => console.log('Hello Rax', name); setTimeout(() => console.log('Loaded'), 2000); list.forEach(item => console.log(item));
It should be noted that the internal value of this arrow (similar to Java Lambda expression) function is different from that of ordinary function, so the two examples are not strictly equivalent.
7. Multiline string
If you find that you need to write multiline strings in your code, you can write them as follows:
Common writing
const lorem = 'Lorem ipsum dolor sat amet, consectetur\n\t' + ' adipisicing elit, sed do eiusmod tempor incididunt\n\t' + 'ut Labore et dolore magna aliqua. Ut enim ad minim\n\t' + 'veniam, quis nostrud exercitation ullamco Laboris\n\t' + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t' + 'irure dolor in reprehenderit in voluptate velit esse. \n\t'
But there is a simpler way. Just use backquotes. ``
Simplified writing
const lorem = `Lorem ipsum dolor sat amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut Labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco Laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse. `
8. Template text
Aren't you tired of using '+' to connect multiple variables into a string? Is there no simpler way to do this? If you can use ES6, you are lucky. All you need to do is use backquotes and enclose the ${} variable.
Common writing
const welcome = 'You have logged in as ' + firstName + ' ' + lastName + '.' const db = 'http://' + host + ':' + port + '/' + database;
Simplified code
const welcome = `You have logged in as ${firstName} ${lastName}`; const db = `http://${host}:${port}/${database}`;
9. Short circuit assessment
If the expected parameter is null or undefined, there is no need to write five or six lines of code to assign the default value. We can simply use the short circuit logic operator and do the same thing with only one line of code.
Common writing
let dbHost; if (process.env.DB) { dbHost = process.env.DB; } else { dbHost = '127.0.0.1'; }
Simplified writing
const dbHost = process.env.DB || '127.0.0.1';
10: Gets the last item in the array
If you want to get elements from the end of the array, you can use slice with negative integers.
let array = [0, 1, 2, 3, 4, 5, 6, 7] console.log(array.slice(-1)); >>>[7] console.log(array.slice(-2)); >>>[6, 7] console.log(array.slice(-3)); >>>[5, 6, 7]
11. Object properties
Defining object literals in JavaScript makes life easier. ES6 provides a simpler way to assign attributes to objects. If the variable name is the same as the object key, shorthand symbols can be used.
Common writing
const x = 2020, y = 2021; const obj = { x:x, y:y };
Simplified writing
const obj = { x, y };
12. Implicit return
Return is a keyword we often use to return the final result of the function. An arrow function with a single statement implicitly returns its evaluation (the function must omit braces ({}) to omit the return keyword).
To return multiline statements, such as object literals, you must wrap the function body with () instead of {}. This ensures that the code is evaluated as a single statement.
Common writing
function calcCircumference(diameter) { return Math.PI * diameter }
Simplified writing
calcCircumference = diameter => ( Math.PI * diameter; )
13. Deconstruction assignment
If you are using any popular Web framework, you are likely to use arrays or data in the form of object text to pass information between components and API s. Once the data object reaches a component, you need to unpack it.
Common writing
const observable = require('mobx/observable'); const action = require('mobx/action'); const runInAction = require('mobx/runInAction'); const store = this.props.store; const form = this.props.form; const loading = this.props.loading; const errors = this.props.errors; const entity = this.props.entity;
Simplified writing
import { observable, action, runInAction } from 'mobx'; const { store, form, loading, errors, entity } = this.props;
You can even assign your own variable name:
const { store, form, loading, errors, entity:contact } = this.props;
14. Propagation operator
The extension operator introduced in ES6 has several use cases, which can make JavaScript code more efficient and interesting to use. It can be used to replace some array functions. The expansion operator is just a series of three points.
Common writing
// joining arrays const odd = [1, 3, 5]; const nums = [2 ,4 , 6].concat(odd); // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = arr.slice()
Simplified writing
// joining arrays const odd = [1, 3, 5 ]; const nums = [2 ,4 , 6, ...odd]; console.log(nums); // [ 2, 4, 6, 1, 3, 5 ] // cloning arrays const arr = [1, 2, 3, 4]; const arr2 = [...arr];
Unlike the concat() function, you can use the expand operator to insert an array anywhere within another array.
const odd = [1, 3, 5 ]; const nums = [2, ...odd, 4 , 6];
You can also use the extension operator with the ES6 deconstruction symbol:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 }; console.log(a) // 1 console.log(b) // 2 console.log(z) // { c: 3, d: 4 }
15. Default parameter value
You can use this if statement to define the default values of function parameters. In ES6, you can define default values in the function declaration itself.
Common writing
function volume(l, w, h) { if (w === undefined) w = 3; if (h === undefined) h = 4; return l * w * h; }
Simplified writing
volume = (l, w = 3, h = 4 ) => (l * w * h); volume(2) //output: 24
Reward: truncate array
If you want to destructively delete the value from the end of the array, it is better than using splice()
For example, if you know the size of the original array, you can redefine its length attribute as follows:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array.length = 4;console.log(array); // Result: [0, 1, 2, 3]
This is a particularly concise solution. However, I found that the slice() method runs faster. If speed is your primary goal, consider using the following:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; array = array.slice(0, 4);console.log(array); // Result: [0, 1, 2, 3]
16. Object [key] benefits
Do you know that Foo.bar can also be written as Foo['bar']? At first, there seems to be no reason for you to write like this. However, this representation provides you with building blocks for writing reusable code.
Consider a simplified example of this validation function:
function validate(values) { if(!values.first) return false; if(!values.last) return false; return true; } console.log(validate({first:'Bruce',last:'Wayne'})); // true
This function does its job perfectly. However, consider a scenario where you have many forms that require validation, but have different fields and rules. Isn't it good to build a general validation function that can be configured at run time?
Simplified writing
// object validation rules const schema = { first: { required:true }, last: { required:true } } // universal validation function const validate = (schema, values) => { for(field in schema) { if(schema[field].required) { if(!values[field]) { return false; } } } return true; } console.log(validate(schema, {first:'Bruce'})); // false console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true
Now we have a validation function that we can reuse in all forms without writing a custom validation function for each form.
17. Exponential power
It is useful for mathematical exponential power functions:
Common writing
Math.pow(2,3); // 8 Math.pow(2,2); // 4 Math.pow(4,3); // 64
Simplified writing
2**3 // 8 2**4 // 4 4**3 // 64
18. Convert string to number
Sometimes your code will receive data in string format, but it needs to be processed in digital format. It's no big deal. We can make a quick conversion.
Common writing
const num1 = parseInt("100"); const num2 = parseFloat("100.01");
Simplified writing
const num1 = +"100"; // converts to int data type const num2 = +"100.01"; // converts to float data type
19. Object.entries()
This is a feature introduced in ES8 that allows you to convert text objects into an array of key / value pairs. See the following example:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' }; const arr = Object.entries(credits); console.log(arr); /** Output: [ [ 'producer', 'John' ], [ 'director', 'Jane' ], [ 'assistant', 'Peter' ] ] **/
20. Object.values()
This is also a new feature introduced in ES8. It performs a function similar to Object.entries(), but has no key parts:
const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' }; const arr = Object.values(credits); console.log(arr); /** Output: [ 'John', 'Jane', 'Peter' ] **/
Use = = = instead==
If necessary, = = (or) !=) The operator performs automatic type conversion. The = = = (or! = =) operator of does not perform any conversion. It compares values and types, which can be considered to be better than = =
[10] === 10 // is false [10] == 10 // is true '10' == 10 // is true '10' === 10 // is false [] == 0 // is true [] === 0 // is false '' == false // is true but true == "a" is false '' === false // is false
Also, please note, undefined, null, 0, false, NaN, '' (empty string) are false.
21. Bitwise index
When performing a lookup using an array, the indexOf() function retrieves the location of the item you are looking for. If the item is not found, - 1 returns the value. In JavaScript, 0 is considered false, and the number 0 greater than or less than is considered true. Therefore, you must write the correct code like this.
Common writing
if(arr.indexOf(item) > -1) { // Confirm item IS found } if(arr.indexOf(item) === -1) { // Confirm item IS NOT found }
Simplified writing
if(~arr.indexOf(item)) { // Confirm item IS found } if(!~arr.indexOf(item)) { // Confirm item IS NOT found }
The bitwise(~) operator will return what the truth value is, but - 1. Negating it is as simple as doing! ~. Alternatively, we can use the include() function:
if(arr.includes(item)) { // Returns true if the item exists and false if it does not exist }
22. Object attribute assignment
Consider the following codes:
let fname = { firstName : 'Black' }; let lname = { lastName : 'Panther'}
How do you combine them into one object? One way is to write a function to copy data from the second object to the first object. Unfortunately, this may not be what you want - you may need to create a new object without changing any existing objects. The easiest way is to use the function introduced in Object.assignES6:
let full_names = Object.assign(fname, lname);
You can also use the object destruction symbol introduced in ES8:
let full_names = {...fname, ...lname};
There is no limit to the number of object properties you can merge. If you do have objects with the same property name, the values will be overwritten in the order they are merged.
23. Double Bitwise NOT shorthand
Bitwise operators are one of the features you learned in the JavaScript beginner tutorial, and you can never implement them anywhere. Agree? In addition, who would like to use 1 and 0 if you don't deal with binaries?
However, there is a very useful use case for the bitwise non operator. You can use it as Math.floor() The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can Here Read more about bitwise operators.
Common writing
Math.floor(4.9) === 4 //true
Simplified writing
~~4.9 === 4 //true
24. Short circuit assessment
When assigning a variable value to another variable, you may need to ensure that the source variable is not null, undefined, or empty. You can write if long statements with multiple conditions or use short circuit evaluation.
Common writing
if (variable1 !== null || variable1 !== undefined || variable1 !== '') { let variable2 = variable1;
Simplified writing
const variable2 = variable1 || 'new';
Don't believe me? voluntarily Test (at In es6console Paste the following code:
let variable1; let variable2 = variable1 || 'bar'; console.log(variable2 === 'bar'); // prints true variable1 = 'foo'; variable2 = variable1 || 'bar'; console.log(variable2); // prints foo
Note that if you set variable1 to false or 0, bar assigns this value.
25. Mandatory parameters
By default, JavaScript sets function parameters to undefined (in short, no value is assigned). Some other languages throw warnings or errors. To force parameter assignment, you can use ifstatement to throw an error if Undefined, or you can use force parameter shorthand.
Common writing
function foo(bar) { if(bar === undefined) { throw new Error('Missing parameter!'); } return bar; }
Simplified writing
mandatory = () => { throw new Error('Missing parameter!'); } foo = (bar = mandatory()) => { return bar; }
Swap two variables
In order to exchange two variables, we often use the third variable, but it can be easily done by array deconstruction assignment.
Common writing
let x = "rakshit", y = "shah"; const temp = x; x = y; y = temp;
Simplified writing
[x,y] = [y,x]
26. Convert anything to Boolean
When developing any code, you may encounter situations where Boolean values are required for comparison or true / false checking. This method can be very useful in this case!
const foo = 'Some character serial'; const toBool = !!foo console.log(toBool) // really
27. Convert anything into numbers
You can implement it by using the + operator.
const foo = '522' const toNumber = +foo console.log(toNumber) // 522 const toNegativeNumber = -foo console.log(toNegativeNumber) // -522
28. Convert array to object
const arr = ['foo', 'bar', 1] const obj = { ...arr } console.log(obj) // {0: "foo", 1: "bar", 2: 1}
29. Delete duplicates in Array
The Set object allows you to store unique values of any type, whether Original value Or object references.
const arr = ['a', 'b', 'c', 'b', 'd'] const newArr = [... new Set(arr)] console.log(newArr) // ["a", "b", "c", "d"]
30. Comment your code often
Often, developers hate or forget to comment on the features, algorithms, or code they develop. Obviously, it will help your peers if you comment where you need to.
Comments are a good way to summarize the purpose of code snippets and save your development partners the time they need to determine it themselves.
It also allows code to catch possible errors if it doesn't do what it's annotated to do. In general, it's best to leave a comment on each function.
If you're not sure if you should comment, do it! If it's too messy, you can delete it at any time in the future.
When you feel that some code is missing or needs to be completed in the future, just add TODO comments.