Some Modern Javascript Tricks
tricks for writing short and clean code in javascript
When I was learning JavaScript, I used to make a list of tricks that saves time. I took these list from other people’s code, coding websites and anywhere other than the tutorials I was using to learn. I’ll share few of the tips from that list, that I find very clever and useful in modern JavaScript. I hope this article might be very useful for the ones at the learning phase and intermediate phase. Also, you guys can mention in the comments if there is any other way you found very useful and tricky.
Everyone in this country should learn to program a computer, because it teaches you how to think — Steve Jobs
There is no specific order for the below mentioned tips to write code that performs in a smarter way.”
Logical operator handing in variables assignment
1. AND (&&)
The logical AND (&&) operator for a set of boolean operands will be true if and only if all the operands are true. Otherwise it will be false.
Example :
More generally, the operator returns the value of the first falsy.
and the use case of variables
2. OR (||)
The logical OR (||) operator for a set of operands is true if and only if one or more of its operands is true. If any of its arguments are true, it returns true, otherwise it returns false.
Example:
Use above-mentioned examples, so that will compare
Dynamic property Name in Object
In modern javascript is setting an Object with a dynamic key is simple. using “[‘key’]” can add properties.
Example :
Array to Object , Object to Array
In modern javascript world, you can convert array to Object or Object to array is easiest way. I think you know about spread operator, you may used many places , like that we are going to use here
Example :
Array to Object
Object to Array
we have 3 types convert Object to array
- Object.Keys : using this method, will get a all keys as an array
2. Object.values: using this method will get all values as an array
3. Object.entries: will get both key and value in array
Destructuring assignment
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variable,most of the people used this feature in javascript frameworks like react, angular.
Note: When destructuring objects, you should use the same name for the variable as the corresponding object key.
if the keys is not then, the default value will assigned
In Array :