28 Tip Javascript Mà Bạn Nên Biết

Trong bài viết này, mình sẽ giới thiệu một số kỹ thuật JavaScript phổ biến, giúp bạn giải quyết các vấn đề thường gặp trong quá trình phát triển web một cách nhanh chóng và dễ dàng hơn.
1) Đảo Ngược Chuỗi (Reverse String)

Đoạn mã:
/*niemvuilaptrinh.com*/
const stringReverse = str => str.split("").reverse().join("");
stringReverse('hello world'); /*dlrow olleh*/
2) Cuộn Lên Đầu Trang (Scroll To Top)

Đoạn mã:
/*niemvuilaptrinh.com*/
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
3) Loại Bỏ Phần Tử Trùng Lặp Trong Mảng (Remove Duplicates)

Đoạn mã:
/*niemvuilaptrinh.com*/
const removeDuplicate = (arr) => [...new Set(arr)];
removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]
4) Lấy Một Phần Tử Ngẫu Nhiên Trong Mảng (Get Random Item)

Đoạn mã:
/*niemvuilaptrinh.com*/
const randomItemArray = (arr) => arr[Math.floor(Math.random() * arr.length)];
randomItemArray(['a', 'b', 'c', 1, 2, 3]);
5) Lấy Số Lớn Nhất Trong Mảng (Get Max Number)

Đoạn mã:
/*niemvuilaptrinh.com*/
const maxNumber = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
maxNumber([4,9,5,7,2]) /* 9 */
6) Kiểm Tra Kiểu Dữ Liệu Số (Check Type Number)

Đoạn mã:
/*niemvuilaptrinh.com*/
function isNumber(num) {
return !isNaN(parseFloat(num)) && isFinite(num);
}
isNumber("Hello"); /*false*/
isNumber(123);/*true*/
7) Kiểm Tra Giá Trị Null (Check Type Null)

Đoạn mã:
/*niemvuilaptrinh.com*/
const checkNull = val => val === undefined || val === null;
checkNull(123) /* false */
checkNull() /* true */
checkNull('hello') /* false */
8) Lấy Số Nhỏ Nhất Trong Mảng (Get Min Number)

Đoạn mã:
/*niemvuilaptrinh.com*/
const minNumber = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
console.log(minNumber([3,5,9,7,1])) /*1*/
9) Tính Giá Trị Trung Bình Của Mảng (Get Average Number)

Đoạn mã:
/*niemvuilaptrinh.com*/
const averageNumber = arr => arr.reduce((a, b) => a + b) / arr.length;
averageNumber([1, 2, 3, 4, 5]) /* 3 */
10) Kiểm Tra Kiểu Dữ Liệu (Checking the Element’s Type)

Đoạn mã:
/*niemvuilaptrinh.com*/
/*niemvuilaptrinh.com*/ const checkType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
checkType(true) /*boolean*/
checkType("hello World") /*string*/
checkType(123) /*number*/
11) Đếm Số Lần Xuất Hiện Của Một Phần Tử Trong Mảng (Count Element Occurrences)

Đoạn mã:
/*niemvuilaptrinh.com*/
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1,2,2,4,5,6,2], 2) /* Số 2 xuất hiện 3 lần trong array */
12) Lấy URL Hiện Tại (Get Current URL)

Đoạn mã:
/*niemvuilaptrinh.com*/
const getCurrentURL = () => window.location.href;
getCurrentURL() /* https://www.niemvuilaptrinh.com */
13) Viết Hoa Chữ Cái Đầu Trong Chuỗi (Capitalize Letters)

Đoạn mã:
/*niemvuilaptrinh.com*/
const capitalizeString = str => str.replace(/b[a-z]/g, char => char.toUpperCase());
capitalizeString('niem vui lap trinh'); /* 'Niem Vui Lap Trinh' */
14) Chuyển Đổi RGB Sang Hex (Convert RGB To Hex)

Đoạn mã:
/*niemvuilaptrinh.com*/
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(52, 45, 125); /* Kết quả là: '#342d7d'*/
15) Chuyển Đổi Số Thành Mảng (Convert Number to Array)

Đoạn mã:
/*niemvuilaptrinh.com*/
const numberToArray = n => [...`${n}`].map(i => parseInt(i));
numberToArray(246) /*[2, 4, 6]*/
numberToArray(357911) /*[3, 5, 7, 9, 1, 1]*/
16) Lấy Nội Dung Từ HTML (Get Content From HTML)
This will be very useful for preventing users from being able to embed HTML tags in the web page when filling out information in the form of login, registration, post content..

Đoạn mã:
/*niemvuilaptrinh.com*/
const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
getTextInHTML('<h2>Hello World</h2>'); /*'Hello World'*/
17) Gán Nhiều Biến Cùng Lúc (Assign Multiple Variables)

Đoạn mã:
/*niemvuilaptrinh.com*/
var [a,b,c,d] = [1, 2, 'Hello', false];
console.log(a,b,c,d) /* 1 2 'Hello' false */
18) Làm Rỗng Mảng (Empty Array)

Đoạn mã:
let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); /* Kết quả : [] */
19) Sao Chép Object (Copy Object)

Đoạn mã:
/*niemvuilaptrinh.com*/
const obj = {
name: "niem vui lap trinh",
age: 12
};
const copyObject = { ...obj };
console.log(copyObject); /* {name: 'niem vui lap trinh', age: 12}*/
20) Kiểm Tra Số Chẵn Lẻ (Check Even and Odd Numbers)

Đoạn mã:
/*niemvuilaptrinh.com*/
const isEven = num => num % 2 === 0;
console.log(isEven(1)); /*false*/
console.log(isEven(2)); /*true*/
21) Gộp Hai Hoặc Nhiều Mảng (Merge Arrays)

Đoạn mã:
/*niemvuilaptrinh.com*/
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr = arr1.concat(arr2);
console.log(arr); /* [1, 2, 3, 4, 5, 6] */
22) Sao Chép Nội Dung Vào Clipboard (Copy To Clipboard)

Đoạn mã:
/*niemvuilaptrinh.com*/
const copyTextToClipboard = async (text) => {
await navigator.clipboard.writeText(text)
}
23) Chọn Số Ngẫu Nhiên Trong Một Khoảng (Random Number Range)

Đoạn mã:
/*niemvuilaptrinh.com*/
var max = 10;
var min = 1;
var numRandom = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(numRandom)
24) Kiểm Tra Phần Tử Có Đang Được Focus Hay Không (Check Element Is Focused)

Đoạn mã:
/*niemvuilaptrinh.com*/
const elementFocus = (el) => (el === document.activeElement);
elementIsInFocus(element);
/*if true element is focus*/
/*if false element is not focus*/
25) Kiểm Tra Thiết Bị Apple (Testing Apple Devices)

Đoạn mã:
/*niemvuilaptrinh.com*/
const isAppleDevice =
/Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
/*if true element is apple devices **/
/*if false element is not apple devices*/
26) Chuyển Đổi Chuỗi Thành Mảng (Convert String to Array)

Đoạn mã:
/*niemvuilaptrinh.com*/
const str = "Hello";
const arr = [...str];
console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] */
27) Sử Dụng Arrow Functions (Arrow Functions)

Đoạn mã:
/* regular function*/
const sum = function(x, y) {
return x + y;
};
/* arrow function */
const sum = (x, y) => x + y;
28) Viết Gọn Câu Điều Kiện (Short Hand For Conditional Sentences)

Tổng Kết:
Hy vọng bài viết này cung cấp cho bạn những kiến thức JavaScript hữu ích cho việc phát triển website. Nếu bạn có bất kỳ câu hỏi nào, vui lòng liên hệ với mình qua email và mình sẽ trả lời sớm nhất có thể. Cảm ơn bạn đã ủng hộ website! Chúc bạn một ngày tốt lành!