JavaScript Tips and Tricks for Developers
MD Hasan Patwary
Posted on July 6, 2024
JavaScript is a versatile language with numerous features that can make coding more efficient and enjoyable. Here are some useful tips and tricks every developer should know, complete with code snippets and detailed descriptions to help you understand and implement them easily.
1. Swapping Values
Swapping values in an array or between variables can be done in multiple ways. Here are three methods:
Using a Temporary Variable
Using a temporary variable is a straightforward method for swapping values.
let array = [1, 2, 3, 4, 5];
let temp = array[0];
array[0] = array[4];
array[4] = temp;
console.log(array); // Output: [5, 2, 3, 4, 1]
Using Array Destructuring
Array destructuring is a concise and modern way to swap values.
[array[0], array[4]] = [array[4], array[0]];
console.log(array); // Output: [5, 2, 3, 4, 1]
Using Arithmetic Operations
This method uses arithmetic operations to swap values without a temporary variable.
let a = 1, b = 2;
b = a + (a = b) - b;
console.log(a, b); // Output: 2 1
2. Copy to Clipboard
Copying text to the clipboard can be done using the following function, which creates a temporary textarea
element, selects its content, and executes the copy command.
function copyToClipBoard(str) {
const element = document.createElement("textarea");
element.value = str;
document.body.appendChild(element);
element.select();
document.execCommand("copy");
document.body.removeChild(element);
}
function handleClick() {
let text = document.querySelector("#text");
copyToClipBoard(text.innerText);
}
When handleClick
is called, it copies the text content of the element with the id text
to the clipboard.
3. Destructuring Aliases
Destructuring objects with aliases allows you to rename properties when extracting them, making your code cleaner and more readable.
const language = {
name: "JavaScript",
founded: 1995,
founder: "Brendan Eich",
};
const { name: languageName, founder: creatorName } = language;
console.log(languageName, creatorName); // Output: JavaScript Brendan Eich
4. Get Value as Data Type
You can retrieve the value of an input element as a specific data type, such as a number, using valueAsNumber
.
const element = document.querySelector("#number").valueAsNumber;
console.log(typeof element); // Output: number
5. Remove Duplicates from Array
Removing duplicates from an array can be easily achieved using a Set
, which only stores unique values.
const array = [1, 2, 2, 2, 3, 5, 6, 5];
console.log([...new Set(array)]); // Output: [1, 2, 3, 5, 6]
6. Compare Two Arrays by Value
To check if two arrays have the same elements in the same order, you can use the following function:
const hasSameElements = (a, b) => {
return a.length === b.length && a.every((v, i) => v === b[i]);
};
console.log(hasSameElements([1, 2], [1, 2])); // Output: true
console.log(hasSameElements([1, 2], [2, 1])); // Output: false
7. Shuffling Array
Shuffle an array using sort
and Math.random
to randomize the order of elements.
const numbers = [1, 2, 3, 4, 5, 6];
console.log(numbers.sort(() => Math.random() - 0.5)); // Output: [3, 5, 1, 6, 4, 2] (example, output may vary)
8. Comma Operator
The comma operator allows you to include multiple expressions in a context where only one is expected. It evaluates each expression from left to right and returns the value of the last expression.
let x = 1;
x = (x++, x);
console.log(x); // Output: 2
let y = (2, 3);
console.log(y); // Output: 3
let a = [[1, 2, 3, 4], [3, 4, 5], [5, 6], [7]];
for (let i = 0, j = 3; i <= 3; i++, j--) {
console.log("a[" + i + "][" + j + "] = " + a[i][j]);
// Output:
// a[0][3] = 4
// a[1][2] = 5
// a[2][1] = 6
// a[3][0] = 7
}
Additional Tips
Converting NodeList to Array
You can convert a NodeList
to an array using the spread operator or Array.from()
.
const nodeList = document.querySelectorAll("div");
const nodeArray = [...nodeList]; // or Array.from(nodeList);
console.log(Array.isArray(nodeArray)); // Output: true
Using Default Parameters
Default parameters allow you to initialize a function parameter with a default value if no value is provided.
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, Guest!
greet("John"); // Output: Hello, John!
Finding Unique Elements in Arrays
Use the filter
method along with indexOf
and lastIndexOf
to find unique elements in an array.
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index, self) => {
return self.indexOf(value) === self.lastIndexOf(value);
});
console.log(uniqueNumbers); // Output: [1, 3, 5]
These tips and tricks can help you write more efficient and cleaner code in JavaScript. Keep experimenting and exploring to find more ways to enhance your coding skills!
Posted on July 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.