DEV Community

Cover image for Useful JavaScript Code Snippets for Common Problems 😎
Tabassum Khanum
Tabassum Khanum

Posted on

Useful JavaScript Code Snippets for Common Problems 😎

Hey Coders!
JavaScript is one of the widely used languages in Web Development. A broad and vital ecosystem has evolved around JS, offering tons and tons of frameworks and libraries that help you develop applications faster. At the same time, it made our coding experience a little complicated. Sometimes it’s good to take a step back and try to understand how to do things without a library. In this article, we will be going through some JS snippets which will provide a little help with those repetitive, simple tasks that come up each day.

1. Sort an array

//strings
const names = ["Seema", "Rekha", "Jaya"];
names.sort();
//['Jaya', 'Rekha', 'Seema' ]

//Numbers
const numbers = [101, 8, 87];
numbers.sort((a, b) => {
  return a - b;
});
//[ 8, 87, 101 ]
Enter fullscreen mode Exit fullscreen mode

2. Select a random element

const items = ["Ball", "Bat", "Cup"]
const randomIndex = Math.floor(Math.random()*items.length)
items[randomIndex]
Enter fullscreen mode Exit fullscreen mode

3. Reverse a string

function reverseString(string) {
       return string.split(" ").reverse().join(" ")
}

revereseString("Random String")
Enter fullscreen mode Exit fullscreen mode

4. Check if element has a class

const element = document.querySelector("#element")
element.classList.contains("active")
Enter fullscreen mode Exit fullscreen mode

5. String interpolation

const name = "Jaya"
console.log(`Hi, ${name}. You have ${2 ** 3} new notifications.`}
//Hi, Jaya. You have 8 new notifications.
Enter fullscreen mode Exit fullscreen mode

6. Loop through an array

const cars = ["Ford", "BMW", "Audi" ]
for (let car of cars) {
      console.log(car)
}

/*
Ford
BMW
Audi
*/
Enter fullscreen mode Exit fullscreen mode

7. Get current time

const date = new Date()
const currentTime = 
   `${date.getHours()}:${date.getMintues()}:${date.getSeconds()}`

console.log(currentTimes)
//example output: "22:16:41"
Enter fullscreen mode Exit fullscreen mode

8. Replace part of a string

const string = "You are awesome."
const replacedString = string.replace("You", "We")

console.log(replacedString) //Output: "We are awesome"
Enter fullscreen mode Exit fullscreen mode

9. Destructing variable assignment

let profile = ['bob', 34, 'carpenter'];
let [name, age, job] = profile;
console.log(name);
// bob
Enter fullscreen mode Exit fullscreen mode

10. Using the spread operator

let data = [1,2,3,4,5];
console.log(...data);
//  1 2 3 4 5
let data2 = [6,7,8,9,10];
let combined = [...data, ...data2];
console.log(...combined);
// 1 2 3 4 5 6 7 8 9 10
console.log(Math.max(...combined));
// 10
Enter fullscreen mode Exit fullscreen mode

11. Return [Number] Maximum Elements From an Array

const maxElement = ( array, number = 1 ) => [...array].sort(( x,y ) => y - x).slice(0, number);

//Example 
maxElement ([ 1,2,3,4,5]);  // [5]
maxElement([ 6, 7, 8, 9 , 10, 10] , 2);   // [10,10]
Enter fullscreen mode Exit fullscreen mode

Latest comments (5)

Collapse
 
makeros profile image
Arek Czogała

Hi.
IMO, it would be nice to explain in 1-2 senteces why it's working (very short). Othervise I can imagine that people will just copy paste the snippents without understanding them.

Collapse
 
andrewbaisden profile image
Andrew Baisden

Nice snippets by the way you can increase the readability by using markdown syntax highlighting for your code blocks. Google it.

Collapse
 
hunterrajz profile image
HunterRajz

third one is not working.....and you also misspelled the function name in the end...

Collapse
 
mzaini30 profile image
Zen

Sort array based on object:

data.sort((a, b) => a.name > b.name ? 1 : -1)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
m1ras profile image
m1rasb • Edited

Hello!

Help change the script (newbie!)
This script parses instagram followers. You need to log into your account and open the list of subscribers / subscriptions and paste the script into the console. Then it will start parsing.

Help change the code so that it only parses those who have published a story.

Script:
let ul_accounts = document.getElementsByClassName("jSC57 _6xe7A"); // класс тега ul списка аккаунтов
function parsing() {
let accounts = ul_accounts[0].innerHTML
// ------------------------------------------------------------------------------
// Парсинг ников
// ------------------------------------------------------------------------------
let result_nick = accounts.match(/title="[^"]+"/g)
let result_count = result_nick.length
result_nick = result_nick.join(' ').match(/"[^"]+"/g).join(' ').match(/[^"]+/g).join('').match(/[^\s]+/g).join('\n')
// ------------------------------------------------------------------------------
// Печать ников
// ------------------------------------------------------------------------------
console.log(result_nick)
console.log('%cАккаунтов собрано: ' + result_count + ' шт.', 'color: #13a555; font-size:18px;')
}
parsing()

Or help me to realize the idea. You need to parse people who have published a storypublished a story.