2021년 1월 2일 토요일

55 Tips For JavaScript

 

1. Use ‘const’ for the constants instead of ‘var’

/* Old way */
var i = 1;
/* Correct */
const i = 1;

2. Use ‘let’ for the changing variables instead of ‘var’

/* Inadequate */
var myVal = 1;
for (var i; i < 10; i++){
myVal = 1 + i;
}
/* Correct */
let myVal = 1;
for (let i; i < 10; i++){
myVal += i
}

3. Declaring Objects

/* 
Old way
The Object() class makes an unnecessary function call
*/
const myObject = new Object();
/* Correct */
const myObject = {};

4. Declaring Arrays

/* 
Old way
The Array() class makes an unnecessary function call
*/
const myArray = new Array();
/* Correct */
const myArray = [];

5. Concatenate strings

/* Old way */
const myStringToAdd = "world";
const myString = "hello " + myStringToAdd;
/* Correct */
const myStringToAdd = "world";
const myString = `hello ${myStringToAdd}`;

6. Use object method shorthand

/* Inadequate */
const customObject = {
val: 1,
addVal: function () {
return customObject.val + 1;
}
}
/* Correct */
const customObject = {
val: 1,
addVal(){
return customObject.val++
}
}

7. Creating the value of an Object

/* Inadequate */
const value = 1;
const myObject = {
value: value
}
/* Correct */
const value = 1;
const myObject = {
value
}

8. Assign values to an Object

/* Old way */
const object1 = { val: 1, b: 2 };
let object2 = { d: 3, z: 4 };
object2.val = object1.val;
object2.b = object1.b;
/* Correct */
const object1 = { val: 1, b: 2 };
const object2 = { ...object1, d: 3, z: 4 }

9. Assign a value to an Array

/* Inadequate */
const myArray = [];
myArray[myArray.length] = "hello world";
/* Correct */
const myArray = [];
myArray.push('Hello world');

10. Concatenate Arrays

/* Inadequate */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = array1.concat(array2);
/* Correct */
const array1 = [1,2,3,4];
const array2 = [5,6,7,8];
const array3 = [...array1, ...array2]

11. Get multiple properties of an object

/* Inadequate */
function getFullName(client){
return `${client.name} ${client.last_name}`;
}
/* Correct */
function getFullName({name, last_name}){
return `${name} ${last_name}`;
}

12. Getting values from an object

/* Inadequate */
const object1 = { a: 1 , b: 2 };
const a = object1.a;
const b = object1.b;
/* Correct */
const object1 = { a: 1 , b: 2 };
const { a, b } = object1;

13. Creating functions

/* Old way but good */
function myFunc() {}
/* Good */
const myFunc = function() {}
/* Best */
const myFunct = () => {}
// IMPORTANT: In some cases it is not recommended to use these functions with arrows to avoid reading errors

14. Default values

/* Inadequate */
const myFunct = (a, b) => {
if (!a) a = 1;
if (!b) b = 1;
return { a, b };
}
/* Correct */
const myFunct = (a = 1, b = 1) => {
return { a, b };
}

15. Use ‘reduce’ Instead ‘forEach’ and ‘for’ to sum values

/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
values.forEach( (n) => { total += n})
/* Inadequate */
const values = [1, 2, 3, 4, 5];
let total = 0;
for (let i; i < values.length; i++){
total += values[i];
}
/* Correct */
const values = [1, 2, 3, 4, 5];
const total = values.reduce((total, num) => total + num);

16. Exist in array

/* Inadequate */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
let exist = false;
myArray.forEach( item => {
if (item.a === 2) exist = true
})
/* Correct */
const myArray = [{a: 1}, {a: 2}, {a: 3}];
const exist = myArray.some( item => item.a == 2)

17. Shortcut if boolean

/* Inadequate */
const a = 1;
const b = 1;
let isTrue = false
if (a === b) {
isTrue = true
}
/* Correct */
const a = 1;
const b = 1;
const isTrue = a === b

18. Shortcut if values

/* Inadequate */
const a = 5;
let b;
if (a === 5){
b = 3;
} else {
b = 2;
}
/* Correct */
const a = 5;
const b = a === 5 ? 3 : 2;

19. Resize or Empty an Array Using array.length


array.length = nvar array = [a, b, c, d, e, f, g, h, i , j];
console.log(array.length); // returns the length as 10
array.length = 4;
console.log(array.length); // returns the length as 4
console.log(array); // returns “a,b,c,d”

var array = [a, b, c, d, e, f, g, h, i , j];
array.length = 0;
console.log(array.length); // returns the length as 0console.log(array);


20. How to Merge Arrays Without Causing Server Overload
var list1 = [a, b, c, d, e];
var list2 = [f, g, h, i, j];
console.log(list1.push.apply(list1, list2));
// returns the merged values of both arrays (a, b, c, d, e,f, g, h, i, j)

21. How to Extract Unique Values
const cars = ['Opel','Bugatti','Opel','Ferrari','Ferrari','Opel'];
var unrepeated_cars = [...new Set(cars)]; // spread Operator
console.log(unrepeated_cars); // returns the values Opel, Bugatti, Ferrari


22. How to Check if an Object Has Values
Object.keys(objectName).length// if it returns 0 then the Object is empty,// otherwise it displays the number of values

23. Assigning values to multiple variables

//Longhand 
let a, b, c;
a = 5;
b = 8;
c = 12;
//Shorthand
let [a, b, c] = [5, 8, 12];


24. Assigning default value
//Longhand 
let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
imagePath = path;
} else {
imagePath = 'default.jpg';
}

//Shorthand
let imagePath = getImagePath() || 'default.jpg';

25. AND(&&) Short circuit evaluation

//Longhand 
if (isLoggedin) {
goToHomepage();
}

//Shorthand
isLoggedin && goToHomepage();
<div> { this.state.isLoading && <Loading /> } </div>

26. Swap two variables
let x = 'Hello', y = 55; //Longhand 
const temp = x;
x = y;
y = temp;

//Shorthand
[x, y] = [y, x];

27. Multi-line String
//Longhand 
console.log('JavaScript, often abbreviated as JS, is a\n' + 'programming language that conforms to the \n' +
'ECMAScript specification. JavaScript is high-level,\n' +
'often just-in-time compiled, and multi-paradigm.' );
//Shorthand
console.log(`JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification. JavaScript is high-level, often just-in-time compiled, and multi-paradigm.`);

28. Multiple condition checking
//Longhand 
if (value === 1 || value === 'one' || value === 2 || value === 'two') {
// Execute some code
}

// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) {
// Execute some code
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) {
// Execute some code
}

29. Object Property Assignment
let firstname = 'Amitav'; 
let lastname = 'Mishra';
//Longhand
let obj = {firstname: firstname, lastname: lastname};

//Shorthand
let obj = {firstname, lastname};

30. String into a Number
//Longhand 
let total = parseInt('453');
let average = parseFloat('42.6');

//Shorthand
let total = +'453';
let average = +'42.6';

31. Repeat a string for multiple times
//Longhand 
let str = '';
for(let i = 0; i < 5; i ++) {
str += 'Hello ';
}
console.log(str); // Hello Hello Hello Hello Hello

// Shorthand
'Hello '.repeat(5);
'sorry\n'.repeat(100);

32. Find max and min number in array
// Shorthand 
const arr = [2, 8, 15, 4];
Math.max(...arr); // 15
Math.min(...arr); // 2

33. For loop
let arr = [10, 20, 30, 40]; //Longhand 
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
//Shorthand
//for of loop
for (const val of arr) {
console.log(val);
}
//for in loop
for (const index in arr) {
console.log(`index: ${index} and value: ${arr[index]}`);
}
let obj = {x: 20, y: 50}; 
for (const key in obj) {
console.log(obj[key]);
}


34. Merging of arrays
let arr1 = [20, 30]; //Longhand 
let arr2 = arr1.concat([60, 80]);
// [20, 30, 60, 80]

//Shorthand
let arr2 = [...arr1, 60, 80];
// [20, 30, 60, 80]

35. Deep cloning of multi-level object
let obj = {x: 20, y: {z: 30}}; 
//Longhand
const makeDeepClone = (obj) => {
let newObject = {};
Object.keys(obj).map(key => {
if(typeof obj[key] === 'object'){
newObject[key] = makeDeepClone(obj[key]);
} else {
newObject[key] = obj[key];
}
});
return newObject;
}
const cloneObj = makeDeepClone(obj);
//Shorthand
const cloneObj = JSON.parse(JSON.stringify(obj));
//Shorthand for single level object
let obj = {x: 20, y: 'hello'};
const cloneObj = {...obj};


36. Get character from string
let str = 'jscurious.com'; //Longhand 
str.charAt(2); // c

//Shorthand
str[2]; // c

37. Smart Data Filteration

// Data Filterationvar data = ["Football", "Soccer", "Cricket", "Basketball", "Hockey"]var filtered_data = data.filter(data => data.length < 8)console.log(filtered_data) // ["Soccer", "Cricket", "Hockey"]

38. Looping Keys and Values

// looping throught objectslet data = {JavaScript: 1, Dart: 2, Java: 3};Object.keys(data).forEach((key, value) => {  console.log(key, value); });// Output
// JavaScript 0
// Dart 1
// Java 2

39. Destructing assignment

// Destructive Assignmentlet data = ["Haider", "22", "50000", "Web Developer"]let [name, age, salary, profession] = dataconsole.log(name, age, salary, profession) // Haider 22 50000 Web Developer

40. Slicing Array

// Slicing An Arraylet array = [10, 12, 13, 14, 15, 16]console.log(array.slice(0, 3)) // [10, 12, 13]
console.log(array.slice(0, 2)) // [10, 12]

41. Search Object in Array

// Search Object in Arraylet data = [
{name:"haider", Salary:60000},
{name:"John", Salary:50000},
{name:"Peter", Salary:20000},
]
let emp = data.find(data => data.name === "Peter")console.log(emp)
// Output
{
name:"Peter",
Salary:20000
}

42. String Reversing

// String Reversevar reverse = (data) => {return data.split("").reverse().join(""); }console.log(reverse("CoderBoy")) // yoBredoCconsole.log(reverse("Medium")) // muideM

43. Concatenate Lists

let arr1 = [10, 20, 30]
let arr2 = [40, 50]
var arr = arr1.concat(arr2)
console.log(arr) // [10, 20, 30, 40, 50]

44. Capture Right Click

// Capture Right Clickwindow.oncontextmenu = () => {console.log("Right Click is Pressed!")}

45. Built-in Sorting

// Built in Sortingvar num = [9, 8, 4, 2, 8, 0, 3, 8]num.sort()console.log(num) //[0, 2, 3, 4, 8, 8, 9]

46. Handle Errors in JS

// Error Handlingtry {
// Code Block to try
}
catch(err) {
// Code Block to handle errors
}
finally {
// Code Block to be executed regardless of the try and catch results
}

47. Find Index of Array Element

// Index of Elementvar num = [9, 8, 4, 2, 8, 0, 3, 8]console.log(num.indexOf(9)) // 0console.log(num.indexOf(3)) // 6console.log(num.indexOf(8)) // 1

48. Check String is Uppercase

// Check for UpperCase
const CheckUpper = string => string === string.toUpperCase();
console.log(CheckUpper("Hello")) // false
console.log(CheckUpper("LEARN")) // true

49. Reverse a string

const reverseString = (...strArr) => strArr.reverse().join('');

50. Get query parameters from the URL

const getQueryParams = (URL) => JSON.parse(    '{"' +
      decodeURI(URL.split('?')[1])
        .replace(/&/g, '","')
        .replace(/=/g, '":"') +
      '"}'
  );
getQueryParams('https://codingcafe.co.in?name=gyan&age=24');
// output
{name: 'gyan', age: '24'}
const getSearchParams = (url) => new URL(url).searchParams;

51. Clipboard API

const copy =    (text) => navigator.clipboard.writeText('Hello world!');

52. Remove duplicate from an Array

const removeDuplicates = (ary) => [...new Set(ary)];
removeDuplicates([5,6,1,2,3,6,3,5,1]) // [5, 6, 1, 2, 3]

53. Check to see if the current tab is visible or focused

const inView = () => document.hidden;
inView();
// Result: returns true or false depending on if tab is focused

54. Check to see if the Element is focused

const inView = (el) => (el === document.activeElement);
inView(element);
// Result: returns true or false depending on if element is focused

55. URL query parameters

const params = new URLSearchParams(location.search.replace(/\?/ig, "")); // location.search = "?name=test&sex=man"
params.has("test"); // true
params.get("sex"); // "man"

56. Scroll to top or to the bottom

const scrollToTop = () => window.scrollTo(0,0);
scrollToTop();
const scrollToBottom = () => window.scrollTo(0,document.body.scrollHeight); scrollToBottom()

57. Check that Caps Lock is on

const passwordInput = document.getElementById('password');

passwordInput.addEventListener('keyup', function (event) {
    if (event.getModifierState('CapsLock')) {
        // CapsLock is open
    }
}); 

58. Get the mouse position

document.addEventListener('mousemove', (e) => {
    console.log(`Mouse X: ${e.clientX}, Mouse Y: ${e.clientY}`);
});

59. element’s dataset

<div id="user" data-name="Maxwell" data-age="32" data-something="Some Data">
    Hello Maxwell
</div>

<script>
    const user = document.getElementById('user');
  
    console.log(user.dataset); 
    // { name: "Maxwell", age: "32", something: "Some Data" }
  
    console.log(user.dataset.name); // "Maxwell"
    console.log(user.dataset.age); // "32"
    console.log(user.dataset.something); // "Some Data"
</script>




댓글 없음:

댓글 쓰기