JavaScript Tips, Tricks, and Best Practices

Frontend development is quite easy if we understand and know all the syntax but it is tough to remember everything on the shot.
These are the common questions that arise when doing Javascript development.
How to check whether a string contains a substring in JavaScript?
We can use the following two methods to achieve this function.
1. includes
The
includes()
method determines whether an array includes a certain value among its entries, returningtrue
orfalse
as appropriate.
const val1 = "abcoo";
const val2 = "oo";console.log(string.includes(val2));
2. index of
The indexOf()
the method returns the first index at which a given element can be found in the array, or -1 if it is not present.
var string = "foo";
var substring = "oo";console.log(string.indexOf(substring) !== -1);
How to replace all occurrences of a string?
- We can use ES6 to handle this.
str = str.replace(/abc/g, '');
2. We can use Regex.
var find = 'abc';
var re = new RegExp(find, 'g');
str = str.replace(re, '');
we could simplify it even more:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}function escapeRegExp(string) {
return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Which can be narrowed down to like this:
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
How to correctly clone a JavaScript object?
- Using ES6
var val1 = {data: "value"};
var val2= Object.assign({}, val1);
2. If you want a shallow copy
Object.assign({}, data)
3. For “deep” copy, use
JSON.parse(JSON.stringify(data))
What is the !! (not not) an operator in JavaScript?
!!
converts the value to the right of it to its equivalent boolean value.
!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!(1/0) === true // Infinity is truthy
!!"" === false // empty string is falsy
!!"foo" === true // non-empty string is truthy
!!"false" === true // ...even if it contains a falsy value
!!window.foo === false // undefined is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy; PHP programmers beware!
How to Loop through an array in JavaScript
we have several options:
1. Sequential for
loop:
var array = ["a","b"];
var arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {
console.log(array[i]);
//Do something
}
2. Array.prototype.forEach
The ES5 specification introduced a lot of beneficial array methods. One of them, the Array.prototype.forEach
, gave us a concise way to iterate over an array:
const data = ["a", "b", "c"]
data.forEach(function (item, index) {
console.log(item, index);
});
3. Use of reduce:
const numbers = [1,2,3,4,5];
const sum = numbers.reduce((total, n) => total + n, 0);console.log(sum);
4. ES6 for-of
statement
let data = ['a', 'b', 'c'];
for (const a of data){
console.log(a);
}
How do I copy to the clipboard in JavaScript?
We can prompt the user to click and enter by doing this:
function copy(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
Now the clipboard copy operation is SAFE because a user has clicked on the prompt.
<button id="data" onclick="copy(document.getElementById('data').innerHTML)">Copy here</button><script>
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
</script>
How do I test for an empty JavaScript object?
There are several ways to achieve this function.
1.jQuery:
jQuery.isEmptyObject({}); // true
2. lodash:
_.isEmpty({}); // true
3. Underscore:
_.isEmpty({}); // true
How do I make the first letter of a string uppercase in JavaScript?
We can either update the CSS which has text-transform property.
- In CSS:
p:first-letter {
text-transform:capitalize;
}
2. Using function we can call toUpperCase() method.
function makeCapital(s)
{
return s && s[0].toUpperCase() + s.slice(1);
}
References:
Are you preparing for interviews? Here are frequently asked interview questions in Angular. It covers the Latest interview questions for Angular and Frontend development. Let’s check how many of these questions you can answer?