Optimize your JavaScript code using modern techniques, tips, and tricks
I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I create tips for day to day Frontend development.
You might be doing JavaScript development for a long time but sometimes you might be not updated with the newest features which can solve your issues without doing or writing some extra codes. This article can help you to prepare yourself for JavaScript interviews in 2021.
Here I am coming with a new series to cover some tips which helped me in my day-to-day coding.
1. Sort an array of objects by string property value
It can be done in different ways.
1. Using Underscore
_.sortBy(collection, [iteratees=[_.identity]])
Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).
var objs = [ { val1: 'abc',val2: 'a' }, { val1: 'cde', val2: 'b' }, { val1: 'fgh', val2: 'c' }];
var sortedValues = _.sortBy( objs, 'val1' );
2. Using ES6 sort function
var data = [ { name: 'abc', value: 21 }, { name: 'cde', value: 37 }, { name: 'ee', value: 45 }, { name: 'ff', value: -12 }, { name: 'ab', value: 13 }, { name: 'cs', value: 37 }];
// sort by valuedata.sort(function (a, b) { return a.value - b.value;});
3. Using Lodash
const sortedValues = _.sortBy(data, 'string');
2. How to Round to at most 2 decimal places (only if necessary)
There are 3 different ways we can achieve this function.
Let’s understand some definitions before jumping to the solutions.
The
**_parseFloat()_**
function parses an argument (converting it to a string first if needed) and returns a floating point number.The
**_toFixed()_**
method formats a number using fixed-point notation.
- Using ParseFloat
parseFloat("183.456").toFixed(2);
The
**_Math.round()_**
function returns the value of a number rounded to the nearest integer.
2. Using MathRound
Math.round( num * 100 + Number.EPSILON ) / 100
[_Number()_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number)
Creates a new_Number_
value.
- Convert string to decimal
var string = 10.134.toFixed(2); // => '10.13'var num = Number(string); // => 10.13
12 Methods for Finding an Item in an Array (and Array of Objects) in JavaScript
12 Methods for Finding an Item in an Array (and Array of Objects) in JavaScript
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com
3. How do I loop through or enumerate a JavaScript Object?
Each ECMAScript version comp up with a different way to enumerate the Objects. Let’s check this out.
The
**_Object.keys()_**
method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.The
**_forEach()_**
method executes a provided function once for each array element.
ES5 (Object.keys() and forEach)
var data = { val1: "abc", val2: "cde" };
Object.keys(data).forEach(function(key) { console.log(key, obj[key]);});
ES6 (for...of):
The
**_for...of_**
statement creates a loop iterating over iterable objects, including: built-in[_String_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
,[_Array_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
, array-like objects (e.g.,[_arguments_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
or[_NodeList_](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)
),[_TypedArray_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray)
,[_Map_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
,[_Set_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set)
, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.
for (const key of Object.keys(data)) { console.log(key, obj[key]);}
ES8 [**Object.entries()**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
The
**_Object.entries()_**
method returns an array of a given object's own enumerable string-keyed property_[key, value]_
pairs, in the same order as that provided by a[_for...in_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)
loop.
Object.entries(data).forEach( ([key, value]) => console.log(key, value));
We can combine for...of
, destructuring, and Object.entries
:
for (const [key, value] of Object.entries(data)) { console.log(key, value);}
4. What is the difference between event.preventDefault() and return false
with return false, there is a chance that other functions are getting executed which is specifically written inside the click while preventDefault won’t allow executing anything.
$('a').click(function (e) { // logic
// runtime error...navigation happened
return false;});
Example of preventDefault()
$('a').click(function (e) { e.preventDefault();
// logic
// runtime error, naviagation will not happen});
5. How can I check for an empty/undefined/null string in JavaScript?
if (!!data) { // Some code here}
Or use type casting:
if (Boolean(data)) { // Code here}
Both do the same function. Typecast the variable to Boolean, where str
is a variable.
It returns false
for null
, undefined
, 0
, 000
, ""
, false
.
It returns true
for string "0"
and whitespace " "
.
If you are looking to Optimize your JavaScript code using modern shorthand techniques, tips, and tricks check out this article.
34 JavaScript Optimization Techniques to Know in 2021
_Optimize your JavaScript code using modern shorthand techniques, tips, and tricks_medium.com
6. How to insert an item into an array at a specific index (JavaScript)?
Append Single Element at a specific index
//Append at index 2array.splice(2, 0,'newData');
//Append at index 5array[5] = 'newData';
Append Multiple Element at a specific index
//Append at index 2array.splice(2, 0,'data1', 'data2', 'data3');
7. How to Get the current URL with JavaScript?
Use windows function:window.location.href
How to Remove Duplicates from an Array or Array of Objects in JavaScript
How to Remove Duplicates from an Array or Array of Objects in JavaScript
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com
8. Checking if a key exists in a JavaScript object?
Using in operator
let data = "abc" in array;
Using hasOwnProperty
let result = data.hasOwnProperty("abc")
Accessing elements directly (brackets style)
let result = data["abc"] === undefined
Accessing elements directly (object style)
let result = array.abc === undefined;
9. How to merge two arrays in JavaScript and remove duplicate items?
We do play with arrays in day to day life and there are a lot of requirements where we need to combine arrays as well as need to remove duplicates.
Below are some approaches to achieve this.
1. Using Lodash
console.log(_.union([10, 4, 5], [134, 26, 19, 10], [6, 1]));
2. Using Filter and Concat
let a = [56, 43, 3], b = [11, 43, 56, 12]let c = a.concat(b)let d = c.filter((val, pos) => c.indexOf(val) === pos)
3. Using Set
[...new Set([...array1 ,...array2])]; // => remove duplication
10. 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, returning_true_
or_false_
as appropriate.
const val1 = "atitpatel";const val2 = "patel";
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 str = "atitpatel";var substr = "patel";
console.log(str.indexOf(substr) !== -1);
If you are looking for array and object-related tips please check out this article.
21 Arrays and Object Tricks in JavaScript/TypeScript
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com
11. How to replace all occurrences of a string?
- We can use ES6 to handle this.
str = str.replace(/test/g, '');
- We can use Regex.
let find = 'ab';
let re = new RegExp(find, '');
let str = find.replace(re, 'cd');
console.log(str);
12. How to correctly clone a JavaScript object?
- Using ES6
var val1 = {data: "value"};var val2= Object.assign({}, val1);
- If you want a shallow copy
Object.assign({}, data)
- For a deep copy
JSON.parse(JSON.stringify(data))
13. 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;
14. 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("value",array[i]);}
2. Array.prototype.forEach
const data = ["a", "b", "c"];
data.forEach(function (item, index) { console.log(item, index);});
3. ES6 for-of
statement
let data = ['a', 'b', 'c'];for (const a of data){ console.log(a);}
9 Methods for Sorting an Item in an Array (and Array of Objects) in JavaScript
9 Methods for Sorting an Item in an Array (and Array of Objects) in JavaScript
_I always used to prefer something like a newspaper which give enough information in a shorter span of time. Here, I…_medium.com
15. 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 copy(text) { window.prompt("To Copy Please do this: Ctrl+C, Enter", text); }</script>
22 Utility Functions To Ace Your JavaScript Coding Interview
22 Utility Functions To Ace Your JavaScript Coding Interview
_JavaScript Coding Assessment Cheatsheet 2021_js.plainenglish.io
16. 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
17. 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 { text-transform:capitalize;}
- Using function we can call toUpperCase() method.
function makeUpperCase(val){ return val && val[0].toUpperCase() + val.slice(1);}
18. How can I change an element’s class with JavaScript?
There are a lot of requirements where we need to change some color or CSS based on conditions.
How it can be done in JavaScript?
To change all classes for an element:
To replace all existing classes with one or more new classes, set the className attribute:
document.getElementById("test").className = "newclass";
To add an additional class to an element:
To add a class to an element, without removing/affecting existing values, append a space and the new class name, like so:
document.getElementById("test").className += " newClass";
To remove a class from an element:
To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:
document.getElementById("test").className = document.getElementById("test").className.replace ( /(?:^|\s)newClass(?!\S)/g , '' )
19. Is it possible to apply CSS to half of a character?
We do see some fancy word art where the half of the character have different color while other half have different color. How we can achieve something like this in CSS?
Below is the example to make apply CSS for half character.
h1 { display: inline-block; margin: 0; /* for demo snippet */ line-height: 1em; /* for demo snippet */ font-family: helvetica, arial, sans-serif; font-weight: bold; font-size: 300px; background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%); -webkit-background-clip: text; -webkit-text-fill-color: transparent;}
<h1>XYZ</h1>
20. How to append something to an array?
In the older JavaScript version, it was done by using the apply method.
The
**_apply()_**
method calls a function with a given_this_
value, and_arguments_
provided as an array (or an array-like object).
let array1 = [33, 45, 5];let array2 = [100, 2];
Array.prototype.push.apply(array2, array1);
console.log(array2); // [100, 2, 33, 45, 5]
With ES6 it can be done using the spread operator.
let array1 = [11, 42, 53];let array2 = [1, 2];
array2.push(...array1);
console.log(array2); // [11, 2, 3, 42, 53]
Top comments (0)