This content originally appeared on DEV Community and was authored by Anshu
useful tips & tricks in javascript
JavaScript is the most popular language and this language that you can learn easily by yourself. it's front-hand language. And it's one of the languages used by coders, developers, and programmers. Not to be confused with JScript, Java, or Javanese script that all are similar languages.
We all know that javascript is now more updated than before. There are so many new features added in Javascript 2021(Check out some of the best features in JavaScript). That makes our work easier and faster. programmer, developers, and coders always have some goal to complete it, for them, there are some short and simple useful tips & tricks in javascript they must use it to makes them work easy.
Quick way to using slice and ES8 PadStart method
const accountnum = "204910110001957";
const lastFourDigits = accountnum.slice(-4);
// print last four digit of account number
const maskedNumber = lastFourDigits.padStart(accountnum.length, '*');
console.log(lastFourDigits); // output will be 1957
console.log(maskedNumber); // ***********1957
Run an event handler only one time ##
If you want to run the addEventListener method you have to pass {once: true} as the third argument then the event handler method will run only one time. That's one of the useful tips & tricks in javascript.
document.getElementById("btn").addEventListener("click",
function () {
console.log("Button is Clicked..");
},
{ once: true }
);
Update an object's properties by spread operator
The spread syntax can be used when all elements from an object or array need to be included in a list of some kind. By using this operator you can update any types of object properties. This is one of the most useful javascript tips.
const object = {
name: "Anshuman",
age: 29,
city: "Surat",
};
const newAge = 49;
const updatedObject = {
...object,
age: newAge
};
console.log(object); // { name:"Rahul", age:29, city:"Surat"}
console.log(updatedObject); // { name:"Rahul", age:49, city:"Surat"}
Find the length of properties in an object
What's the fastest way to find the length of properties, you can find the length by using
[objectLength = Object.keys(exampleObject).length]
this syntax. That's one of the most useful tips in javascript.
Const Object = {
id: 1,
name: 'Arun',
age: 30
}
console.log(Object.keys(object).length);
Print the last elements of an array
generally, Array is a collection of the same variables. That is one of the most useful tips in javascript is given here, if you want to print only the last number from the array you must use the syntax given below:
const elements = [5,6,7,8,9,10];
const last = elements.slice(-1);
console.log(last); // Output will be 10
const secondLast = elements.slice(-2);
console.log(secondLast); // Output will be 9,10
Check Array
In Javascript, There are three ways to check an array is in proper syntax or not. An array is an object, so obviously it has proper syntax. That's one of the useful tips in javascript to check an array is actually an array or not.
const array = [2,4,6,8,10];
Print current timestamp
A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp. It means it converts the current time in a string with different types of time zones. That's one of the useful tips & tricks in javascript and it's most useful.
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
Provide dynamic key for an object
Moving on to computed keys, the value of object keys can be computed directly in the object literal using the same bracket notation in the literal. In a new feature of javascript, we can provide a dynamic key for an object that's the better javascript than the old one. That one of the best tips & tricks in javascript.
function obj(key, value) {
const dyn = {
[key]: value
};
return dyn;
}
console.log(obj('name', 'Rahul')); // Output will be name: Rahul
console.log(obj('age', '29')); // Output will be age: 29
Destructuring Array
The destructuring syntax is a JavaScript expression that makes it possible to take out values from arrays, or properties from objects, into distinct variables. It's one of the best tips & tricks in javascript.
const names = ["yash", "mayur", "krushil", "kenil", "ansh", "raju", "rahul"];
const [firstName, secondNmae] = names;
console.log(thirdName); // Output will be krushil
console.log(secondName); // Output will be mayur
Execute number variable to function
ES6 is the very advanced operator that converts commas to separate values in an array. So, when you enter the number variable to add it becomes an array. This is one of the most useful tips & tricks in javascript.
function add(...numbers) {
return numbers.reduce((var, value) => {
return var + value;
}, 0);
}
const sum = add(2,4,6,8,10);
console.log(sum); // Output will be 30
Create an array by spread operator
The spread operator allows an iterable to expand in places where more than zero arguments are expected. It mostly uses when an array has more than one value. That's one of the most useful tips & tricks in javascript.
const s1 = ["1", "2", "3"];
const s2 = [ "5", "6", "8"];
const combined = ["4", ...s1, "7", ...s2]
console.log(combined); // Output will be ["1", "2", "3", "4", "5", "6" , "7", "8"]
Fill array with specific values
The fill() method fills the specified elements in an array with a static value. You can specify the position of where to start and end the filling. If you don't specify the position then all elements will be filled. This is one of the most useful tips & tricks in javascript.
var fruits = ["Banana", "Orange", "mango", "kiwi"];
fruits.fill("strawberry", 2, 4); // Output will be Banana,Orange,strawberry,strawberry
Remove duplicates values from array
There are so many duplicate values in an array. So, the programmer can remove them easily by using the console.log(var); syntax. That makes work easier and faster. This is one of the most useful tips & tricks in javascript. There are two types available to remove the duplicate values which are given below:
By array filter
const dup = [10, 10, 20, 50, 30, 30, 50];
const arr = dup.filter((value, index) => {
return dup.indexOf(value) === index;
});
console.log(arr); // Output Will be [10, 20, 30, 50]
By set
const dup = [10, 10, 20, 50, 30, 30, 50];
const arr = [...new Set(dup)];
console.log(arr); // [10, 10, 20, 50, 30, 30, 50];
Add scroll button to the top of the page
Many times pages are so lengthy to scroll. That is the top scroll button available by using the below syntax: (And this is one of the most useful tips & tricks in javascript)
window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
Convert any type of value to boolean
In JavaScript, there are two types of boolean values true and false. You can use the Boolean() function to find out if a variable is true or not. That's one of the most useful tips & tricks in javascript.
let num1;
console.log(!!num1); // false
const num2 = 10;
console.log(!!num2); // true
const n1 = 'Tim';
console.log(!!n1); // true
const n2 = '';
console.log(!!n2); // false
This content originally appeared on DEV Community and was authored by Anshu
Anshu | Sciencx (2021-06-07T10:32:22+00:00) Useful Tips & Tricks In JavaScript. Retrieved from https://www.scien.cx/2021/06/07/useful-tips-tricks-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.