An Interest In:
Web News this Week
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
July 18, 2022 04:30 am GMT
Original Link: https://dev.to/devsimc/useful-tips-tricks-in-javascript-2m1n
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.
1. A quick way to using slice and ES8 PadStart method
const accountnum = "204910110001957";const lastFourDigits = accountnum.slice(-4);// print last four digit of account numberconst maskedNumber = lastFourDigits.padStart(accountnum.length, '*');console.log(lastFourDigits); // output will be 1957console.log(maskedNumber); // ***********1957
2. 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.
document.getElementById("btn").addEventListener("click",function () {console.log("Button is Clicked..");},{ once: true });
3. Update an object's properties by spread operator
const object = { name: "Rahil", 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"}
4. Find the length of properties in an object
Const Object = { id: 1, name: 'Arun', age: 30 }console.log(Object.keys(object).length);
5. Print the last elements of an array
const elements = [5,6,7,8,9,10];const last = elements.slice(-1);console.log(last); // Output will be 10const secondLast = elements.slice(-2);console.log(secondLast); // Output will be 9,10
Provide a dynamic key for an object
function obj(key, value) { const dyn = { [key]: value }; return dyn;}console.log(obj('name', 'Rahul')); // Output will be name: Rahulconsole.log(obj('age', '29')); // Output will be age: 29
6. 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.
let num1;console.log(!!num1); // falseconst num2 = 10;console.log(!!num2); // trueconst n1 = 'Tim';console.log(!!n1); // trueconst n2 = '';console.log(!!n2); // false
Original Link: https://dev.to/devsimc/useful-tips-tricks-in-javascript-2m1n
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To