DEV Community

Cover image for 28 Tip Javascript You Should Know
Niemvuilaptrinh
Niemvuilaptrinh

Posted on • Edited on • Originally published at niemvuilaptrinh.com

28 Tip Javascript You Should Know

Today I will introduce some common techniques in Javascript to help you solve problems. Common problems in the process of setting up faster and easier.

1) Javascript Reverse String

Javascript Reverse String
And below is the code:

const stringReverse = str => str.split("").reverse().join("");
stringReverse('hello world'); /*dlrow olleh*/
Enter fullscreen mode Exit fullscreen mode

2) Scroll To Top Of Page

Scroll To Top Of Page
And below is the code:

const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
Enter fullscreen mode Exit fullscreen mode

3) Remove Duplicates In Array

Remove Duplicates In Array
And below is the code:

const removeDuplicate = (arr) => [...new Set(arr)];
removeDuplicate([1, 2, 3, 4, 4, 2, 1]); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

4) Get Random Item In Array

Get Random Item In Array
And below is the code:

const randomItemArray = (arr) => arr[Math.floor(Math.random() * arr.length)];
randomItemArray(['a', 'b', 'c', 1, 2, 3]);
Enter fullscreen mode Exit fullscreen mode

5) Get Max Number in Array

Get Max Number in Array
And below is the code:

const maxNumber = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
maxNumber([4,9,5,7,2]) /* 9 */
Enter fullscreen mode Exit fullscreen mode

6) Check Type Number

Check Type Number
And below is the code:

function isNumber(num) {
  return !isNaN(parseFloat(num)) && isFinite(num);
}
isNumber("Hello"); /*false*/
isNumber(123);/*true*/
Enter fullscreen mode Exit fullscreen mode

7) Check Type Null

Check Type Null
And below is the code:

const checkNull = val => val === undefined || val === null;
checkNull(123) /* false */
checkNull() /* true */
checkNull('hello') /* false */
Enter fullscreen mode Exit fullscreen mode

8) Get Min Number in Array

Get Min Number in Array
And below is the code:

const minNumber = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
console.log(minNumber([3,5,9,7,1])) /*1*
Enter fullscreen mode Exit fullscreen mode

9) Get Min Number in Array

Get Min Number in Array
And below is the code:

const averageNumber = arr => arr.reduce((a, b) => a + b) / arr.length;
averageNumber([1, 2, 3, 4, 5]) /* 3 */
Enter fullscreen mode Exit fullscreen mode

10) Checking the Element's Type

Checking the Element's Type
And below is the code:

 const checkType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
checkType(true) /*boolean*/
checkType("hello World") /*string*/
checkType(123) /*number*/
Enter fullscreen mode Exit fullscreen mode

11) Count Element Occurrences in Array

Count Element Occurrences in Array
And below is the code:

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1,2,2,4,5,6,2], 2) /* Number 2 Occurrences 3 times in array */
Enter fullscreen mode Exit fullscreen mode

12) Get Current URL Using Javascript

Get Current URL Using Javascript
And below is the code:

const getCurrentURL = () => window.location.href;
getCurrentURL() /* https://en.niemvuilaptrinh.com */
Enter fullscreen mode Exit fullscreen mode

13) Capitalize Letters in Strings

Capitalize Letters in Strings
And below is the code:

const capitalizeString = str => str.replace(/b[a-z]/g, char => char.toUpperCase());
capitalizeString('niem vui lap trinh'); /* 'Niem Vui Lap Trinh' */
Enter fullscreen mode Exit fullscreen mode

14) Convert RGB To Hex

Convert RGB To Hex
And below is the code:

 const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
 rgbToHex(52, 45, 125); /* Result: '#342d7d'*/
Enter fullscreen mode Exit fullscreen mode

15)Convert Number to Array

Convert Number to Array
And below is the code:

const numberToArray = n => [...`${n}`].map(i => parseInt(i));
numberToArray(246) /*[2, 4, 6]*/
numberToArray(357911) /*[3, 5, 7, 9, 1, 1]*/
Enter fullscreen mode Exit fullscreen mode

16)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..
Get Content From HTML
And below is the code:

const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
getTextInHTML('<h2>Hello World</h2>'); /*'Hello World'*/
Enter fullscreen mode Exit fullscreen mode

17)Assign Multiple Variables In JS

Assign Multiple Variables In JS
And below is the code:

var [a,b,c,d] = [1, 2, 'Hello', false];
console.log(a,b,c,d) /* 1 2 'Hello' false */
Enter fullscreen mode Exit fullscreen mode

18)Empty Array

Empty Array
And below is the code:

let arr = [1, 2, 3, 4, 5];
arr.length = 0;
console.log(arr); /* Result : [] */
Enter fullscreen mode Exit fullscreen mode

19)Copy Object In JS

Copy Object In JS
And below is the code:

const obj = {
    name: "niem vui lap trinh",
    age: 12
};
const copyObject = { ...obj };
console.log(copyObject); /* {name: 'niem vui lap trinh', age: 12}*/ 
Enter fullscreen mode Exit fullscreen mode

20)Check Even and Odd Numbers

Check Even and Odd Numbers
And below is the code:

const isEven = num => num % 2 === 0;
console.log(isEven(1)); /*false*/
console.log(isEven(2)); /*true*/
Enter fullscreen mode Exit fullscreen mode

21)Merge Two Or More Arrays JS

Merge Two Or More Arrays JS
And below is the code:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const arr = arr1.concat(arr2);
console.log(arr); /* [1, 2, 3, 4, 5, 6] */
Enter fullscreen mode Exit fullscreen mode

22)Copy Content To Clipboard

Merge Two Or More Arrays JS
And below is the code:

const copyTextToClipboard = async (text) => {
  await navigator.clipboard.writeText(text)
}
Enter fullscreen mode Exit fullscreen mode

23)Choose a Random Number From a Range of Values

Choose a Random Number From a Range of Values
And below is the code:

var max = 10;
var min = 1;
var numRandom = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(numRandom)
Enter fullscreen mode Exit fullscreen mode

24)Check Element Is Focused Or Not

Choose a Random Number From a Range of Values
And below is the code:

const elementFocus = (el) => (el === document.activeElement);
elementIsInFocus(element);
/*if true element is focus*/
/*if false element is not focus*/
Enter fullscreen mode Exit fullscreen mode

25)Testing Apple Devices With JS

Choose a Random Number From a Range of Values
And below is the code:

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*/
Enter fullscreen mode Exit fullscreen mode

26)Convert String to Array

Choose a Random Number From a Range of Values
And below is the code:

const str = "Hello";
const arr = [...str];
console.log(arr); /* ['H', 'e', 'l', 'l', 'o'] */
Enter fullscreen mode Exit fullscreen mode

27)Using Arrow Functions in JS

Choose a Random Number From a Range of Values
And below is the code:

/* regular function*/
const sum = function(x, y) {
  return x + y;
};
/* arrow function */
const sum = (x, y) => x + y;
Enter fullscreen mode Exit fullscreen mode

Summary:
I hope this article will provide you with useful javascript knowledge for development website and if you have any questions, please email me and I will respond as soon as possible. We hope you continue to support us Website so I can write more good articles. Have a nice day!

Top comments (1)

Collapse
 
someone_49 profile image
SomeOne_49 • Edited

Good job , Thanks๐Ÿ’•.