This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


Childhood memories: when I was a child there was a very famous advertisement: “very happy oh, and can eat happy growth, I love to eat happy growth ~~”

This article introduces the growth of Hacks, a common feature of JavaScript. Eat a growth happiness, like eating a growth happiness ╮(╯▽╰)╭

1. Use length to adjust the array size

a=['Pune','Hyderabad','Banglore','Mumbai','Indore','Delhi']
console.log(a.length) //OUTPUT 6
a.length=3
console.log(a) //OUTPUT ['Pune','Hyderabad','Banglore']
Copy the code

2. Exchange two values with array destruct assignment

let a=10; let b=20; Console. log(a,b) //OUTPUT: 10,20 [a,b]=[b,a] console.log(a,b) //OUTPUT: 20,10Copy the code

3. Reduce the memory consumption of array merge

//old way a=[1,2,3,4,5] b=[4,5,6,7,8] c=a.concat(b Array a and array b array in c which will consume lot of memory. The console, log (c) / / the OUTPUT: 1,2,3,4,5,4,5,6,7,8 / / new way A =[1,2,3,4,5] b=[4,5,6,7,8] a.push.apply(a,b) // it will only push the content of array b in array a.console.log (a)Copy the code

4. Filter null/undefined with Boolean

a=[null,undefined,{"name":"Alex"},{"name":"Nick"},{"name":""},null]
c=a.filter(item=>item.name.length>0) //this will show error Uncaught TypeError: Cannot read property 'length' of undefined

// we can use filter with Boolean to remove null and undefined Values

c=a.filter(Boolean).filter(it=>it.name.length>0) //This will work
console.log(c) //OUTPUT
Copy the code

5. Extend operation traversal from 0 to n

[...Array(100)].map((it,index)=>console.log(index))
Copy the code

6. Replace everything with /g

str="India India USA India UK India"
console.log(str.replace(/India/,'USA'))
//OUPUT USA India USA India UK India
//Add g at the end of string it will replace all occurences
console.log(str.replace(/India/g,'USA'))
Copy the code

7. Use “or and not”

// old way let a="hello" let b; if(a==undefined){ b="Nothing" } else{ b=a } console.log(b) //hello // new way b=a||"Nothing" console.log(b) //hello // old way let data={"name":"Allen"} if(data! =undefined)console.log(data.name) // new way data! =undefined&&console.log(data.name)Copy the code

8. String digits are exchanged

// string to number
a="123"
console.log(+a) //Output 123
b=""
console.log(+b) //NaN

//number to string

a=123
console.log(a+"")
Copy the code

9. Placeholders in console

// %s replaces an element with a string console.log("Helllo I love %s so much","Javascript") // %d replaces an element Replaces an element with a float console.log("Helllo %d ",1) // % F Replaces an element with a float console.log("Helllo %f ",1.078) // %(o|O) | element is displayed as an object. console.log("Helllo %O",{"Name":"Sidd"}) // %c | Applies the provided CSS console.log("%cThis is a red text", "color:red");Copy the code

10. console.table

// we can use console.table to show objects in tabular format
a=[{"city":"Banglore"},{"city":"Pune"},{"city":"Mumbai"}]
console.table(a)
Copy the code

11. Intercept the last few bits of the array

A = conosle,2,3,4,5,6,7,8,9,10 [1]. The log (a.s lice (1)) / / [10] the console. The log (a.s lice (2)) / / [9]Copy the code

12. Js exponentiation

console.log(2 ** 3) //8
console.log(2 ** 12)  //4096
Copy the code

13. Use “!!!!!!!!” distinguishing

//In javascript following values are falsy 0, "", null, undefined, NaN and of course false except it all are truly // use !! operator to get falsy or trult console.log(!! 0,!!!!! ", "!!!!! null,!! "Hii",!! undefined,!! NaN ,!! false,!! true) //OUTPUT false false false true false false false trueCopy the code

14. Use “eval” to call functions

const print=()=>console.log("hello")
setTimeout(()=>eval('print')(),1000)//hello
Copy the code

15. Typeof Determines the type

//The typeof operator returns a string indicating the type of the unevaluated operand.
console.log(typeof 12) //number
console.log(typeof "hello") //string
console.log(typeof []) //object
console.log(typeof true) //boolean
console.log(typeof {}) //object
Copy the code

16. The yield keyword pauses the function

//The yield keyword is used to pause and resume a generator function function* list(index,length) { while (index < length) { yield index; index++; }} const iterator = list(0,10); console.log(iterator.next().value); // expected output: 0 console.log(iterator.next().value); // expected output: 1Copy the code

Function * in JS

//The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
function* generator(i) {
  yield i;
  yield i + 10;
}

const gen = generator(10);

console.log(gen.next().value);
// expected output: 10

console.log(gen.next().value);
// expected output: 20
Copy the code

18. New. Target in JS

// new.target is used to detect that weather a function or constructor call using new or not. // if it called using new it will return refrence to constructor or function else it return undefined. function learn(){ new.target? console.log("Called using new"):console.log("Called without new") } learn() //called without learn new learn() //called using new. //In arrow functions, new.target is inherited from the surrounding scope.Copy the code

19. Expression tags

//The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to. loop1: for (let i = 0; i < 5; i++) { loop2: for(let j=0; j<5; j++) { console.log(i,j) if(i==j) { continue loop1 } } } // 0 0 // 1 0 // 1 1 // 2 0 // 2 1 // 2 2 // 3 0 // 3 1 // 3 2 // 3 3/4 0 // 4 1/4 2 // 4 3/4 4Copy the code

20. Remaining parameters

//The rest parameter syntax allows a function to accept an indefinite number of arguments as an array,it like variadic function in C. function abc(... Args) {the console. The log (args)} (1)/ABC/ABC (1, 2) / / [1] [1, 2] ABC (1, 2, 3) / / ABC (1, 2, 3, 4) / [1, 2, 3] / [1, 2, 3, 4]Copy the code

21. slice VS splice

Slice does not affect the original array;

Splice is used to make changes to the original array, either removing elements or replacing them;

//slice //array.slice(start,end) // start: denotes the starting index of slicing. // end: Cofbo = cofbo (24, 824) and cofbo = cofbo (24, 824, 824) Console. The log (B) / / (three, four, five) / / splice / / array splice (start, deleteCount, n1, n2, n3,...). // start: the starting index of splicing. // deleteCount: number of elements to delete from start index. // n1,n2,n3,n4.... : A=[1,2,3,4,5,6,7,8,9,10] B= a.spice (2,3) console.log(A) . / /,2,6,7,8,9,10 [1] the console log (B) / / (three, four, five) C = A.s plice (0,2,10,11,12,13,14). The console log (C) / / [1, 2] the console, log (A) / /,11,12,13,14,6,7,8,9,10 [10]Copy the code

22. forEach VS map

ForEach is often used to iterate without having to return something;

Map needs to return (avoid using map everywhere);

/ / the map A = B =,2,3,4,5,6,7,8,9,10 [1] arjun ap (item = > item % 2 = = 0) console. The log (B) / / [false, true, false, true, false, true, false, true, false, True] / [] / / forEach A = C = A.f,2,3,4,5,6,7,8,9,10 [1] orEach (item = > item % 2 = = 0) to the console. The log (C) / / undefinedCopy the code

23. Use “in” to judge existence

Log (2 in a) //true console.log(9 in a) //falseCopy the code

24. Getters & Setters

Use js native Getters & Setters;

A={
    subjectName:"Math",
    set marks(value)
    {
    if(isNaN(value))throw Error("Marks must be number")
    //for propert name you have to use _(underscore) before its name.
    else this._marks=value 
    },
    get result()
    {
    if(this._marks>=33)return "Pass" 
    else return "Fail"
    }
}
A.marks=59
console.log(A.result)
//Pass
A.marks='sa'
//Will throw Error
Copy the code

25. Iterate over the object

//declaration of JSON
a={"firstName":"Siddhant","lastName":"Johari","age":"XX","phoneNumber":"+9187XXXXXXXX"}
Object.keys(a).forEach(it=>console.log(it,":",a[it]))//Object.keys(a) it will create an array with keys of a
// firstName : Siddhant
// lastName : Johari
// age : XX
// phoneNumber : +9187XXXXXXXX
Copy the code

26. Multiple “or” judgments

// old way if (fruit === 'apple' || fruit === 'orange' || fruit === 'banana' || fruit ==='grapes') { //code } // new way  if (['apple', 'orange', 'banana', 'grapes'].includes(fruit)) { //code }Copy the code

27. Multiple “and” judgments

// old way if(obj && obj.address && obj.address.postalCode) { console.log(obj.address.postalCode) } // new way console.log(obj? .address? .postalCode); // Optional chain operator, ES2020 requiredCopy the code

28. Switch case

// old way
switch (number) {
  case 1:
     return 'one';
  case 2:
     return 'two';
  default:
     return;
}


// new way
const data = {
  1: 'one',
  2: 'two'
};
//Access it using
data[num]

Copy the code

29. Conditional calls

// old way
function area() {
    console.log('area');
}
function volume() {
    console.log('volume');
}
if(type === 'square') {
    area();
} else {
    volume();
}

// new way
(type === 'square' ? area : volume)()
Copy the code

30. Array deep copy

// old way
const newArr = JSON.parse(JSON.stringify(arr))


// new way
const newArr = slice(arr)
Copy the code

The above. Is there one you don’t know about?

Tell you a little secret, ╰(?

Learned a few points, the comment buckles “the n point, learned”, all know, the comment buckles “this?” .

I am Nuggets Anthony, public number [Nuggets Anthony], output exposure input, technical insights into life! Goodbye ~