1. Convert to string
const input = 123;
console.log(input + ''); // '123'
console.log(String(input)); // '123'
console.log(input.toString()); // '123'
2. Convert to number
const input = '123';
console.log(+input); // 123
console.log(Number(input)); // 123
console.log(parseInt(input)); // 123
3. Convert to boolean
const input = 1;
// Solution 1 - Use double-exclamation (!!) to convert to boolean
console.log(!!input); // true
// Solution 2 - Pass the value to Boolean()
console.log(Boolean(input)); // true
4. Problem with the string 'false'
const value = 'false';
console.log(Boolean(value)); // true
console.log(!!value); // true
// The best way to check would be,
console.log(value === 'false');
5. null vs undefined
null
is a value, whereas undefined
is not.null
is like an empty box, and undefined
is no box at all.
ex.,
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.
6. Truthy and Falsy values
Falsy values - false
, 0
, ""
(empty string), null
, undefined
, & NaN
.
Truthy values - "false"
, "0"
, {}
(empty object), & []
(empty array)
7. What changes can be made with const
const
is used when the value does not change. ex,
const name = 'Codedrops';
name = 'Codedrops.tech'; // Error
const list = [];
list = [1]; // Error
const obj = {};
obj = { name: 'Codedrops' }; // Error
But it can be used to update value in previously assigned arrays/objects references
const list = [];
list.push(1); // Works
list[0] = 2; // Works
const obj = {};
obj['name'] = 'Codedrops'; // Works
8. Difference between double equal and triple equal
// Double equal - Converts both the operands to the same type and then compares
console.log(0 == '0'); // true
// Triple equal - Does not convert to same type
console.log(0 === '0'); // false
9. Better way to accept arguments
function downloadData(url, resourceId, searchText, pageNo, limit) {}
downloadData(...); // need to remember the order
Simpler way to do this-
function downloadData(
{ url, resourceId, searchText, pageNo, limit } = {}
) {}
downloadData(
{ resourceId: 2, url: "/posts", searchText: "programming" }
);
10. Rewriting normal function as arrow function
const func = function() {
console.log('a');
return 5;
};
func();
can be rewritten as
const func = () => (console.log('a'), 5);
func();
11. Return an object/expression from arrow function
const getState = (name) => ({name, message: 'Hi'});
12. Convert a set to an array
const set = new Set([1, 2, 1, 4, 5, 6, 7, 1, 2, 4]);
console.log(set); // Set(6) {1, 2, 4, 5, 6, 7}
set.map((num) => num * num); // TypeError: set.map is not a function
To convert to an array,
const arr = [...set];
13. Check if a value is an array
const arr = [1, 2, 3];
console.log(typeof arr); // object
console.log(Array.isArray(arr)); // true
14. Object keys are stored in insertion order
const obj = {
name: "Human",
age: 0,
address: "Earth",
profession: "Coder",
};
console.log(Object.keys(obj)); // name, age, address, profession
Objects
maintain the order in which the keys were created.
15. Nullish coalescing operator
const height = 0;
console.log(height || 100); // 100
console.log(height ?? 100); // 0
Nullish coalescing operator
(??) returns the right-hand side value only if the left-hand side value is undefined
or null
16. map()
It is a utility function which helps in applying a function on every element of the array.
It returns a new array, which contains the values returned from that applied function. ex.,
const numList = [1, 2, 3];
const square = (num) => {
return num * num
}
const squares = numList.map(square);
console.log(squares); // [1, 4, 9]
Here, the function square
is applied to every element. i.e., 1, 2, 3.
The returned value of that function is returned as the new element value.
17. try..catch..finally - Real example
const getData = async () => {
try {
setLoading(true);
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
// if error occurs here, then all the statements
//in the try block below this wont run.
// Hence cannot turn off loading here.
const data = await response.json();
setData(data);
} catch (error) {
console.log(error);
setToastMessage(error);
} finally {
setLoading(false); // Turn off loading irrespective of the status.
}
};
getData();
18. Destructuring
const response = {
msg: "success",
tags: ["programming", "javascript", "computer"],
body: {
count: 5
},
};
const {
body: {
count,
unknownProperty = 'test'
},
} = response;
console.log(count, unknownProperty); // 5 'test'
Thanks for reading 💙
Follow @codedrops.tech for daily posts.
Instagram ● Twitter ● Facebook
Micro-Learning ● Web Development ● Javascript ● MERN stack ● Javascript
codedrops.tech
Top comments (5)
Hello, may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.
Sure, no problem.
thank you very mush.
Nice tips. Thanks
Nice !