17 Pro JavaScript tricks you didn't know
Tags: javascript, productivity, webdev, 100daysofcode
Published: 2020-11-29 11:50:56

There are many ways to write code but generally the first way for many people is very long and can take you some time. Here is my latest post that will increase your efficiency and productivity when coding JavaScript. 

---

# 600+ Free Design resources

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6q3qdida0rc6r3zpuua2.jpeg)

Resources. Freebies. Learn.
We're making things easier on Internet.

Visit - [600+ free design resources](https://www.producthunt.com/posts/600-free-design-resources/)

---

<hr>
# JavaScript : Tricks You Should Know

### The ternary operator

Noobs:
```javascript
let hungry = true;
let eat; 
if (hungry == true) {
       eat = 'yes'; 
} else {
       eat = 'no';
}
```
Pro:
```javascript
let hungry = true;
let eat = hungry == true ? 'yes' : 'no';
```

<hr>

### Number to string / string to number

Noobs: 
```javascript
let num = 15; 
let s = num.toString(); // number to string
let n = Number(s); // string to number
```

Pro: 
```javascript
let num = 15;
let s = num + ""; // number to string
let n = +s; // string to number
```
<hr>

### Populating an array


Noobs:
```javascript
for(let i=0; i < arraySize; i++){
       filledArray[i] {'hello' : 'goodbye'};
}
```

Pro:
```javascript
let filledArray = new Array(arraysize).fill(null).map(()=> ({'hello' : 'goodbye'}));
```
<hr>

### Dynamic properties in objects

Noobs: 
```javascript
let dynamic = "value"; 
let user = {
     id: 1,
};
user[dynamic] = "other value"; 
```

Pro:
```javascript
let dynamic = "value"; 
let user = {
    id: 1,
    [dynamic] = "other value"
};
```

<hr>

> Read more =>  [3 Steps to learn a programming language](https://blog.rahulism.co/3-steps-to-learn-a-programming-language) 
 
### Removing duplicates

Noob:
```javascript
let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = [];
let flag = false; 
for (j = 0; < array.length; j++) {
   for (k = 0; k < outputArray.length; k++) {
      if (array[j] == outputArray[k]) {
         flag = true;
       }
    }
    if (flag == false) {
      outputArray.push(array[j]);
     }
     flag = false;
}
//outputArray = [100, 23, 67, 45]

```

Pro: 
```javascript
let array = [100, 23, 23, 23, 23, 67, 45]; 
let outputArray = Array.from(new Set(array)); 
//outputArray = [100, 23, 67, 45]
```

<hr>

### Array to object

Noob: 
```javascript
let arr = ["value1", "value2", "value3"]; 
let arrObject = {};
for (let i = 0; i < arr.length; ++i) {
   if (arr[i] !== undefined) {
     arrObject[i] = arr[i];
   }
}
```

Pro:
```javascript
let arr = ["value1", "value2", "value3"]; 
let arrObject = {...arr}; 
```
<hr>

> Read more =>  [A guide to Geolocation API](https://blog.rahulism.co/a-guide-to-geolocation-api) 
 
### Object to Array

Noob: 
```javascript
let number = {
  one: 1, 
  two: 2,
};
let keys = []; 
for (let numbers in numbers) {
  if (number.hasOwnProperty(number)) {
     keys.push(number);
    }
}
// key = [ 'one', 'two' ]
```

Pro:
```javascript
let number = {
  one: 1, 
  two: 2,
};
let key = Object.keys(numbers); // key = [ 'one', 'two' ]
let value = Object.values(numbers);  // value = [ 1, 2 ]
let entry = Object.entries(numbers); // entry = [['one' : 1], ['two' : 2]]
```
<hr>

### Short circuit conditionals

Noob: 
```javascript
if (docs) {
    goToDocs();
}
```

Pro:
```javascript
docs && goToDocs()
```
<hr>

> Read more =>  ["use strict" in JavaScript](https://blog.rahulism.co/use-strict-in-javascript)
 
### Use ^ to check if numbers are not equal

```javascript
if(a!=123) // before // NOOBS

if(a^123) // after // PRO
```
<hr>

### Loop over an object

```javascript
const age = {
   Rahul: 20,  
   max: 16
};

// Solution 1 - Get 'keys' and loop over
const keys = Object.keys(age); 
keys.forEach(key => age[key]++);

console.log(age); // { Rahul: 21, max: 16 }

// Solution 2 - for ..in loop
for(let key in age){
   age[key]++;
}

console.log(age); // { Rahul: 22, max: 18 }
```
<hr>

### Object keys are stored in insertion order

```javascript
cosnt obj = {
  name: "Rahul", 
  age: 16, 
  address: "Earth", 
  profession: "Developer", 
}; 

console.log(Object.keys(obj)); // name, age, address, profession
```

<hr>

### Check if value is an array

```javascript
const arr = [1, 2, 3]; 
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
```

<hr>

### Initialize an array of size n and fill with default values

```javascript
const size = 5;
const defaultValue = 0;
const arr = Array(size).fill(defaultValue);
console.log(arr); // [0, 0, 0, 0, 0]
```

<hr>

### Truthy and False values

False values => `false`, `0`, `""`(empty string), `null`, `undefined`,  &`NaN`.                                           
Truthy values => `"Values"`, `"0"`, `{}`(empty object), &`[]`(empty array)

<hr>

### Difference between double equal and triple equal

```javascript
// Double equal - Converts both the operands to the same type and then comapares
console.log(0 == 'o'); // true

// Triple Equal - Does not convert t same type
console.log(0 === '0'); // false
```

<hr>

### Better way to accept arguments

```javascript
function downloadData(url, resourceId, searchTest, pageNo, limit) {}

downloadData(...); // need to remember the order
```

Simpler way to do:

```javascript
function downloadData(
{ url, resourceId, searchTest, pageNo, limit } = {}
) {}

downloadData(
  { resourceId: 2, url: "/posts", searchText: "WebDev" }
);
```

<hr>

### null vs undefined

null => It is a **value** whereas undefined is not.               
null is like an **empty box** and undefined it not box at all.

```javascript
const fn = (x = 'default value') => console.log(x);

fn(undefined); // default value
fn(); // default value

fn(null); // null
``` 

When null is passed, the default value is **not taken**. Whereas, when undefined or nothing is passed the default value is taken. 

<hr>
## Need Help
Need help in raising fund to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me. 

<a href="https://www.buymeacoffee.com/rahxuls">
![1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1606540958103/otN4S9TK8.png)
</a>

<hr>

⚡Thanks For Reading | Happy Coding 🍺