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 number
const maskedNumber = lastFourDigits.padStart(accountnum.length, '*');
console.log(lastFourDigits); // output will be 1957
console.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 10
const 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: Rahul
console.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); // false
const num2 = 10;
console.log(!!num2); // true
const n1 = 'Tim';
console.log(!!n1); // true
const n2 = '';
console.log(!!n2); // false
Top comments (1)
Interesting with the once:true at eventListener, is there a way to avoid that a eventListener register multiple times when the script is called again?