Code Javascript like a Guru with these tricks
Frequently Asked JavaScript Interview Questions and Answers for Freshers and Experienced
Hi guys, it's me again - Rikikudo. Welcome back to my blog. If you're a front-end developer then you have to way to run away from Javascript. It's powerful, especially in web development, but it's also one of the most difficult programing languages. So today, I'm here to tell you guys some tips and tricks which I think are super useful and really really cool. Moreover, by using these tips and tricks, you will get to the next level and boost up your productivity. So let's get started.
So you're having an array that contains some elements which appear more than one time and you want to get rid of them. The naive solution is that initialize a new empty array (let call it b) and then go through the initial array (array a). At each step, search for the current element of array a in array b. If it doesn't exist in b, push it into b and continue, otherwise, just ignore it and go to the next step right away. It's a kind of easy and straightforward solution. We have 2 for loops for that job. But in Javascript, we have a simpler solution for it.
2 for loop to remove duplicated elements?
Okay, the trick here is to use Set (which was introduced in ES6) and spread operator (...). Things will be easy just like a piece of cake. So here's an example of solving above problem in Javascript using Set and ...
const arr = [1, 1, 1, 2, 2, 2, 3, 5, 3, 2];
const newArr = [...new Set(arr)];
console.log(newArr); // [ 1, 2, 3, 5 ]const arr = [1, 1, 1, 2, 2, 2, 3, 5, 3, 2];
const newArr = [...new Set(arr)];
console.log(newArr); // [ 1, 2, 3, 5 ]Set is a data structure that only contains the unique element. By converting the initial array to a set, we will remove all duplicated elements. After that, we will convert that set back to an array using the spread operator.
⚠️ This trick only works with array contains primitive data type (number, strig, null, undefined, symbol). If you want to remove duplicated objects, you can use this snippet code
// Remove duplicate object in array
const removeDuplicateObjectInArray = (list) =>
list.filter((item, index) => {
const _item = JSON.stringify(item);
return (
index ===
list.findIndex((obj) => {
return JSON.stringify(obj) === _item;
})
);
});// Remove duplicate object in array
const removeDuplicateObjectInArray = (list) =>
list.filter((item, index) => {
const _item = JSON.stringify(item);
return (
index ===
list.findIndex((obj) => {
return JSON.stringify(obj) === _item;
})
);
});Falsy values in Javascript are 0, false, NaN, undefined, null, '' (empty string)
Truthy values are all other values except Falsy vaues
Okay, so imagine that we have an array which consists of fasly and truthy values
we want to get all truthy values from that array. There are a lot of ways to do that, but I will introduce to you guys a very simple way which I think is the simplest way out there. By using fiter and Boolean
const arr = [
0,
false,
NaN,
undefined,
"",
null,
1,
true,
"Hello World",
{ name: "value" },
];
const truthyValues = arr.filter(Boolean);
console.log(truthyValues); // [1, true, "Hello World", {name: "value"}]const arr = [
0,
false,
NaN,
undefined,
"",
null,
1,
true,
"Hello World",
{ name: "value" },
];
const truthyValues = arr.filter(Boolean);
console.log(truthyValues); // [1, true, "Hello World", {name: "value"}]This 1-line code does the trick and it's one of my favorite snippet code.
For example, we have a piece of code:
const a = 1;
const b = 1;
if (a == b) console("a=b");
else console.log("a!=b");const a = 1;
const b = 1;
if (a == b) console("a=b");
else console.log("a!=b");Instead of using if , we could use ternary operator to shorten our code like this:
a == b ? console.log("a=b") : console.log("a!=b");a == b ? console.log("a=b") : console.log("a!=b");Or
console.log(`${a == b ? "a=b" : "a!=b"}`);console.log(`${a == b ? "a=b" : "a!=b"}`);There is another way is using && and || operators
Short explanation of && and || || finds the first truthy value. If all expressions return falsy, it will return the last expression
&& find the first fasly value. If all expressions return truthy value, it will return the last expression. For example:
const a = 1;
const b = 2;
console.log(a || b); // 1
console.log(0 || 1); // 1const a = 1;
const b = 2;
console.log(a || b); // 1
console.log(0 || 1); // 1We can re-write expression at the beginning of this section as:
console.log(`${(a == b && "a = b") || "a != b"}`);console.log(`${(a == b && "a = b") || "a != b"}`);Hmm, No different, right ? So let's consider another case:
const data = await fetch([api]);
if (data) {
console.log(data.length);
} else {
console.log(0);
}const data = await fetch([api]);
if (data) {
console.log(data.length);
} else {
console.log(0);
}We can write above code using || like this:
const data = await fetch([api]);
console.log(data.length || 0);const data = await fetch([api]);
console.log(data.length || 0);Explanation: if data.length is truthy value, it will log data.length, otherwise 0.
Example of using a combination of && and ||
const response = {
message: "",
success: true,
result: {
name: "response-list",
list: [1, 2, 3, 4],
},
};
// Get value of result
const result = (response && response.result) || "Default result";
// Get a un-exist property of response
const unknownProperty =
response && response.result && response.result.unknownProperty;
// Get a un-exist property of response but have default value
const unknownPropertyWithDefaultValue =
(response && response.result && response.result.unknownProperty) ||
"Default Value";
console.log(result); // { name: 'response-list', list: [ 1, 2, 3, 4 ] }
console.log(unknownProperty); // undefined
console.log(unknownPropertyWithDefaultValue); // "Default Value"const response = {
message: "",
success: true,
result: {
name: "response-list",
list: [1, 2, 3, 4],
},
};
// Get value of result
const result = (response && response.result) || "Default result";
// Get a un-exist property of response
const unknownProperty =
response && response.result && response.result.unknownProperty;
// Get a un-exist property of response but have default value
const unknownPropertyWithDefaultValue =
(response && response.result && response.result.unknownProperty) ||
"Default Value";
console.log(result); // { name: 'response-list', list: [ 1, 2, 3, 4 ] }
console.log(unknownProperty); // undefined
console.log(unknownPropertyWithDefaultValue); // "Default Value"In above case, every time an expression before || returns a falsy value, the variable will be set to default value immediately without touching other expressions.
It's one of the best practices recommended in real projects, it's a way of avoid uncontrolled error caused by falsy values .
In addition, we can use Optional Chaining
const response = {
message: "",
success: true,
result: {
name: "response-list",
list: [1, 2, 3, 4],
},
};
const result = response?.result ?? "Default result";
const unknownProperty = response?.result?.unknownProperty;
const unknownPropertyWithDefaultValue =
response?.result?.unknownProperty ?? "Default Value";
console.log(result); // { name: 'response-list', list: [ 1, 2, 3, 4 ] }
console.log(unknownProperty); // undefined
console.log(unknownPropertyWithDefaultValue); // "Default Value"const response = {
message: "",
success: true,
result: {
name: "response-list",
list: [1, 2, 3, 4],
},
};
const result = response?.result ?? "Default result";
const unknownProperty = response?.result?.unknownProperty;
const unknownPropertyWithDefaultValue =
response?.result?.unknownProperty ?? "Default Value";
console.log(result); // { name: 'response-list', list: [ 1, 2, 3, 4 ] }
console.log(unknownProperty); // undefined
console.log(unknownPropertyWithDefaultValue); // "Default Value"You can convert from string to number easily by using + operator
const strInt = "10";
const number = +strInt;
console.log("number", number); // 10
console.log("typeof number", typeof number); // numberconst strInt = "10";
const number = +strInt;
console.log("number", number); // 10
console.log("typeof number", typeof number); // numberBesides, it's used to convert from boolean value to number
console.log(+true); // Return: 1
console.log(+false); // Return: 0console.log(+true); // Return: 1
console.log(+false); // Return: 0Another way is to use ~~ operator
const strInt = "10";
const number = ~~strInt;
console.log("number", number); // 10
console.log("typeof number", typeof number); // numberconst strInt = "10";
const number = ~~strInt;
console.log("number", number); // 10
console.log("typeof number", typeof number); // numberPersonally, I think ~~ is more powerful then +
It's okay if we use these operators to convert a "number-like" string to number. But if the string to be convert contains characters which are not digit, + operator will return NaN (Not a number) while ~~ returns "0"
But ~~ has a weaken, + operator will return exact number after converting while ~~ operator returns value equivalents to Math.floor([number]) if that number is floating point number.
const strArr = ["10", "Str", (x = 23), "false", "10.6"];
strArr.forEach((item) => console.log(+item)); // 10, NaN, NaN, NaN,10.6
strArr.forEach((item) => console.log(~~item)); // 10, 0, 23, 0,10const strArr = ["10", "Str", (x = 23), "false", "10.6"];
strArr.forEach((item) => console.log(+item)); // 10, NaN, NaN, NaN,10.6
strArr.forEach((item) => console.log(~~item)); // 10, 0, 23, 0,10const initialArr = [1, 2, 3, 4, 5];
const shuffledArr = initialArr.sort(() => 0.5 - Math.random());
console.log(shuffledArr); // [ 1, 5, 2, 3, 4 ]const initialArr = [1, 2, 3, 4, 5];
const shuffledArr = initialArr.sort(() => 0.5 - Math.random());
console.log(shuffledArr); // [ 1, 5, 2, 3, 4 ]const propertyName = "Rikikudo";
const object = {
[propertyName]: "Value",
};
console.log("object", object); // object { Rikikudo: 'Value' }const propertyName = "Rikikudo";
const object = {
[propertyName]: "Value",
};
console.log("object", object); // object { Rikikudo: 'Value' }With this, you can change name of property by change value of the variable.
const arr = [1, 2, 3, 4, 5, 6];
const obj = { ...arr };
console.log(obj); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }const arr = [1, 2, 3, 4, 5, 6];
const obj = { ...arr };
console.log(obj); // { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }You want to delete all data of an array ? You this : arr.length = 0;
var array = [11, 12, 13, 14, 15];
console.log(array.length); // 5
array.length = 0;
console.log(array.length); // 0
console.log(array); // []var array = [11, 12, 13, 14, 15];
console.log(array.length); // 5
array.length = 0;
console.log(array.length); // 0
console.log(array); // []let a = 1,
b = 2;
let c = "c",
d = "d";
[a, b] = [b, a];
[c, d] = [d, c];
console.log(`a: ${a}, b: ${b}, c: ${c}, d: ${d}`); //a: 2, b: 1, c: d, d: clet a = 1,
b = 2;
let c = "c",
d = "d";
[a, b] = [b, a];
[c, d] = [d, c];
console.log(`a: ${a}, b: ${b}, c: ${c}, d: ${d}`); //a: 2, b: 1, c: d, d: cconst obj1 = {
a: 1,
b: 2,
};
const obj2 = {
c: 3,
d: 4,
};
const obj3 = {
e: 5,
f: 6,
};
const obj4 = {
g: 7,
h: 8,
};
const obj5 = {
i: 9,
j: 10,
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5,
};
console.log(mergedObj); //{ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 }const obj1 = {
a: 1,
b: 2,
};
const obj2 = {
c: 3,
d: 4,
};
const obj3 = {
e: 5,
f: 6,
};
const obj4 = {
g: 7,
h: 8,
};
const obj5 = {
i: 9,
j: 10,
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5,
};
console.log(mergedObj); //{ a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 }⚠️ If there are objects share the same name of property, the value of that property will be the value of property belongs to the latest object.
For example:
const obj1 = {
a: 1,
b: 2,
};
const obj2 = {
c: 3,
d: 4,
};
const obj3 = {
a: 5,
f: 6,
};
const obj4 = {
g: 7,
h: 8,
};
const obj5 = {
a: 9,
j: 10,
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5,
};
console.log(mergedObj); // { a: 9, b: 2, c: 3, d: 4, f: 6, g: 7, h: 8, j: 10 }const obj1 = {
a: 1,
b: 2,
};
const obj2 = {
c: 3,
d: 4,
};
const obj3 = {
a: 5,
f: 6,
};
const obj4 = {
g: 7,
h: 8,
};
const obj5 = {
a: 9,
j: 10,
};
const mergedObj = {
...obj1,
...obj2,
...obj3,
...obj4,
...obj5,
};
console.log(mergedObj); // { a: 9, b: 2, c: 3, d: 4, f: 6, g: 7, h: 8, j: 10 }Okay, so I've introduced to you guys some useful tips and tricks. Even though there are some arguments about the advantages and disadvantages of those tips and tricks but I do think that they're still really cool way of solving specific problem in real life.
So what do you think about it? Leave a comment to let me know about your opiniion.
Thank you
Ref : Stackoverflow.com / Devto.com / Javascript.info