레이블이 ES6인 게시물을 표시합니다. 모든 게시물 표시
레이블이 ES6인 게시물을 표시합니다. 모든 게시물 표시

2021년 8월 26일 목요일

꼭 알아야될 10가지 JavaScript 기본 컨셉

 

1. Arrow Function


  1. Traditional functions have ‘this’ keyword but arrow functions have no ‘this’ keyword.
  2. Traditional functions have ‘arguments’ keywords but arrow functions have no ‘arguments’ keywords.
  3. Traditional functions can use as ‘constructors’ but arrow functions can not use as ‘constructors’.

2. Default parameters


3. IIFE Function



IIFE full meaning — Immediately Invoked Function Expression

4. Spread operator


Spread operator(…) or three dots are the es6 Features. You can concat array, object, and string by using the spread operator. It is used for array expression or string to be expanded or an object expression to be expanded in places. You can copy all the elements of an array, all the properties of an object, and all iterable of the string.



5. isNaN() Method

isNaN() Method returns true if the argument is NaN, Otherwise it returns false.


JavaScript has two types of data types. Primitive and Reference or Objects and Functions.

6. Primitive Values

There are 7 Primitive data types. They are___

  1. Number
  2. String
  3. Boolean
  4. Undefined
  5. Null
  6. Symbol
  7. BigInt

7. Reference or Objects and Functions

Without primitive data types, javaScript’s other data types are reference data types. They are ____

  1. Object
  2. Function

Arrays, regular expressions, and dates are the Object type.



8. Double Equal(==) vs Triple Equal (===)

9. Ternary Operator


10. Destructuring

There are two Destructuring, Array and Object.

Object Destructuring: We can destructure object properties in variable and the variable name and property name should be the same. We can destructure any properties in an object. In object Destructuring, we should not maintain any order which property was first or last or any position. In object destructuring, we should declare a variable with curly braces { }. In curly braces, we should write those properties that we want to destructure from an object. Then we should use the assignment operator = and on the right side, we use that object.

Array Destructuring: We can destructure array elements in variable and the variable name and the element don't need to be the same name. In array destructuring, we should maintain the order which element was first or last or any position. In array destructuring, we should declare a variable with an array symbol[]. In the array symbol, we should write elements by an order which element was first or last or any position. If we want the second element and don’t want the first element we can use only a comma. Then we should use the assignment operator = and on the right side, we use that array.

** In Array and object destructuring we can use a spread operator or three dots to destructuring another array of elements in an array variable and another object properties in an object variable.

10. Destructuring

There are two Destructuring, Array and Object.

Object Destructuring: We can destructure object properties in variable and the variable name and property name should be the same. We can destructure any properties in an object. In object Destructuring, we should not maintain any order which property was first or last or any position. In object destructuring, we should declare a variable with curly braces . In curly braces, we should write those properties that we want to destructure from an object. Then we should use the assignment operator and on the right side, we use that object.{ }=

Array Destructuring: We can destructure array elements in variable and the variable name and the element don't need to be the same name. In array destructuring, we should maintain the order which element was first or last or any position. In array destructuring, we should declare a variable with an array symbol. In the array symbol, we should write elements by an order which element was first or last or any position. If we want the second element and don’t want the first element we can use only a comma. Then we should use the assignment operator and on the right side, we use that array.[]=

** In Array and object destructuring we can use a spread operator or three dots to destructuring another array of elements in an array variable and another object properties in an object variable.

2021년 4월 15일 목요일

promise.all(), promise.any(), promise.race(), promise.allsettled() 차이 설명 쉬운 예제

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        
        const prom1 = new Promise((resolve, reject) => {
            setTimeout(() => {
                // resolve('first promise resolved')
                reject('first promise rejected')
            }, Math.floor(Math.random() * 1000));
        });

        const prom2 = new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('second promise resolved')
                // reject('second promise rejected')
            }, Math.floor(Math.random() * 1000));
        });

        const prom3 = new Promise((resolve, reject) => {
            setTimeout(() => {
                // resolve('third promise resolved')
                reject('third promise rejected')
            }, Math.floor(Math.random() * 1000));
        });

        // Promise.all()
        // 첫 번째 거부 된 Promise로 오류를 던진다...
        (async function() {
            try {
                const result = await Promise.all([prom1, prom2, prom3]);
                console.log(result);
            } catch (err) {
                console.log(err)
            }
        })();

        // Promise.race()
        // 새로고침을 계속하면 3개중 하나의 결과만 리턴해준다.
        // reject든 resolve든 간에...
        (async function() {
            try {
                const result = await Promise.race([prom1, prom2, prom3]);
                console.log(result);
            } catch (err) {
                console.log(err)
            }
        })();
        
        // Promise.any()
        // Promise.race() 는 reject되도 상관없지만 any() 는 resolve된것만 리턴. 새로고침하며 결과 확인
        // Promise 중 하나가 reject 되더라도 다른 Promise를 계속 해결할 것.
        // 모든 Promise가 reject된 경우에만 집계 오류가 발생
        (async function() {
            const result = await Promise.any([prom1, prom2, prom3]);
            console.log(result); // Prints “A”, “B” or “C”
        })();

        // Promise.allSettled()
        // 모든 Promise가 resolve되거나 reject된 후에 각 Promise의 결과를 설명하는 다양한 개체와 함께 해결하는 Promise를 return
        (async function() {
            try {
                const result = await Promise.allSettled([prom1, prom2, prom3]);
                console.log(result);
            } catch (err) {
                console.log(err)
            }
        })();
    </script>
</body>
</html>

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>