10 Lesser-Known JavaScript Tricks
In this article, I have outlined 10 great JavaScript tricks to help you make the most of its capabilities. Whether you're just starting to learn or already deep into practice, I believe you can learn something new from these. So, let's dive in now.
1.Scroll to Top Method
You can use the scrollTo()
method to scroll to a specific position on the page.
window.scrollTo({
top: 0,
behavior: "smooth",
});
2.Double Tilde for Math.floor
Using double tilde (~~) is a quick way to perform the Math.floor
operation.
let num = 5.67;
let rounded = ~~num;
3.Convert Strings to Numbers without parseInt
The plus operator (+) can be used to convert strings to numbers.
let str = "42";
let num = +str;
4.Optional Chaining Operator (?.)
The optional chaining operator (?.) allows handling potentially undefined properties.
let user = {
address: {
street: "123 Main St"
}
};
let street = user?.address?.street;
5.Logical OR Operator for Setting Default Values
Use the logical OR operator (||) to set default values for your applications.
let name = getUsername() || "Guest";
6.Object.entries for Iterating Object Properties
Object.entries
returns an array of [key, value] pairs of its own enumerable properties.
let person = { name: "John", age: 30};
for(let [key, value] of Object.entries(person)){
console.log(`${key}: ${value}`);
}
7.Counting <h1> Tags on a Page
This will print the count of <h1> tags on the page.
console.log(document.getElementsByTagName('h1'));
8.Variable Swapping without Temporary Variables
An example of swapping values of a and b without using a temporary variable.
let a = 5, b = 10;
[a, b] = [b, a];
9.Creating Arrays with Array.from
Array.from
can be used to create arrays in a concise way.
let array = Array.from({length: 5}, (_, index) => index + 1);
10.Checking for NaN
NaN is the only value in JavaScript that is not equal to itself.
let value = "Not a Number";
if(value !== value){
console.log("NaN");
}
Conclusion
These are the 10 JavaScript tricks I wanted to share with you today. I hope you can learn something new from them, helping you enhance your productivity and enjoy a better life.
Learn more: