JavaScript Practical Use snipets

Assigning variables

#1. Using an object to pass to func
function about(args) {
console.log(“Name ” + args.name + ” and “+ args.age);
}

about({ name: “Serg”, age: 22 });

#2 Function generator
function* idGenerate() {
let id = 2 // or could be anything else
while (true) {
yield id++;
}
}
var myIdGenerate = idGenerate();
myIdGenerate.next().value

#3 JSON usefull
const args = {
name: “Serg”,
age: 22,
data: [“hellow”, “world”]
}
// if the JSON is large OR has many sub categories
console.log( JSON.stringify(args) )
console.log( JSON.stringify(args, null, 2) )

#4 variable || method objects
var underground = {
yellowLine = [“stat 1”, “stat 1”, “stat 1”],
redLine = [“stat 3”, “stat 4”, “stat 5”],
}
console.log( underground.yellowLine.join(‘ ‘) );
console.log( underground.yellowLine?.join(‘ ‘) ); // checks if the variable/method exists ( ? ) ….

#5 Destructuring syntax
const args = {
name: “Serg”,
age: 22,
data: [“hellow”, “worlda”]
}
var { name, age } = args; // Serg 22
OR
var { 0: hello, 1: world} = args.data
console.log( nameIs, ageIs ) // hellow worlda

#6 Spread syntax
var array = [12,24]
var newArr = […array, 35,45] //  [12, 24, 35, 45]

#7 Dealing with duplicates
var array = [1,2,5,1,4,5,4,12,24]
var unique = newSet(array)
OR if an array is needed
console.log( [ …new Set(array) ] )

#8 Getting an array of items type Number
var array = [“1″,2,”5″,1,4,”5”,4,12,24]
var arNewNum = array.map( Number ) //  [1, 2, 5, 1, 4, 5, 4, 12, 24]
IF the array has multiple arrays inside array, use ( flat() method )
array.flat().map( Number )

#9 Seeing how long the script runs
console.time(“start 1”)
var a = 15, b = 25;
// Nice
[ a, b ] = [ b, a ];
console.timeEnd(“start 1”)
// Or a Straight approach
var tmp = a, a = b, b = a; // runs faster

Was this article helpful?

Related Articles

Leave A Comment?