Share 13 useful JavaScript snippets to boost your productivity

044c6f081b3be56dc96dc9ecebbaccfa.jpeg

JavaScript is one of the most popular languages ​​you can learn. When I started learning JavaScript, I was always looking for code snippets on StackOverflow, medium and other blogs. In this article, I'll share 15 JavaScript code snippets that I've found useful.

1. Repeat a string without looping

This JS snippet will show how to repeat a string without using any loops. We'll use the JS built-in method repeat() by passing in it a number that will act as the number of times you need to loop.

//Old Method
for(var i = 0; i<5; i++)
{
  console.log("") // 
}
// Best Method
console.log("".repeat(5)) //

2. The difference between arrays

Another great snippet to make you stand out in an array. This comes in handy when you're dealing with a long array and want to see how that array is similar or different. The following sample code will improve your understanding, you can freely use this code in your JS projects.

//Code Example
function ArrayDiff(a, b){
  const setX = new Set(a)
  const setY = new Set(b)
return [
    ...a.filter(x=>!setY.has(x)),
    ...b.filter(x=>!setX.has(x))
  ]
}
  const Array1 = [1, 2, 3];
  const Array2 = [1, 2, 3, 4, 5];
console.log(ArrayDiff(Array1, Array2)) // [4, 5]

3. Whether String is Json

This code snippet comes in handy when you need to check if the data is a string or JSON. Assuming you get a response from the server side and parse that data, you need to check if it's JSON or a string. Check the code snippet below.

//Code Example
function isJSON(str)
{
  try
  {
      JSON.parse(str)
  }
  catch
  {
      return false
  }
return true
}
var str = "JavaScript"
console.log(isJSON(str)) //false

4. Short Console.log

Tired of writing console.log() again and again? Don't worry this snippet will save you a lot of time writing long console.log()s.

var cl = console.log.bind(document)
cl(345) 
cl("JAVASCRIPT")
cl("PROGRAMMING") 
<--Give it a try!-->

5. Replace all

This code snippet will show you how to replace words in a string without iterating over each word, matching it and placing the new word. The code snippet below uses the replaceAll(Target Word, New Word) method.

//Code Example
var str = "Python is a Programming Language, Python is a top programming language and favourite of every developer"
str = str.replaceAll("Python", "JavaScript")
console.log(str) // JavaScript is a Programming Language, JavaScript 5is a top programming language and favourite of every developer

6. Number to Number Array

This code snippet is very useful for converting a number to an array of numbers. Using the spread operator with map we can do this in a second. try:

//example code
const NumberToArray = number => [...`${number}`].map(i => parseInt(i));
console.log(NumberToArray(86734)) //[8,6,7,3,4]
console.log(NumberToArray(1234)) //[1,2,3,4]
console.log(NumberToArray(9000)) //[9,0,0,0]

7. Number to Binary

This code snippet will simply convert the number to binary using the toString() method. Take a look at the code sample below.

var n1 = 500
console.log(n1.toString(2)) // 111110100
var n2 = 4
console.log(n2.toString(2)) // 100
var n3 = 5004
console.log(n3.toString(2)) // 1001110001100

8. Delete an element from an array

This code snippet comes in handy when you need to remove an element from an array. In the code snippet example below, we have used the array.slice() built-in method.

const DropElement = (array, num = 1) => array.slice(num);
console.log(DropElement([2,45,6,7],2)) //[6, 7]
console.log(DropElement([2,45,6,7],1)) //[45, 6, 7]

9. Reverse a String

Now you don't need to loop over the string to reverse it. This code snippet will show how to reverse a string using the spread operator (…) and the reverse() function. This is handy when reversing large strings, for which you need a fast code snippet. Check the code sample below.

//example code
function Reverse(str){
return [...str].reverse().join('');
}
console.log(Reverse("data")) //atad
console.log(Reverse("Code")) //edoC

10. Flatten the depth array

Flattening an array is the process of converting any ordered and two-dimensional array into a one-dimensional array. In short, you reduce the dimensionality of the array. You've seen the "flatten array" snippet code, but what about deeply flattening an array? This code snippet is useful when you have a large ordered array and normal flattening doesn't work on it. For this, you need deep leveling.

//example code
function DeepFlat(array)
{
  return [].concat(...array.map(value=>  (Array.isArray(value) ? DeepFlat(value) : value)));
}
console.log(DeepFlat([1,[2,[4,6,6,[9]],0,],1])) // [1, 2, 4, 6, 6, 9, 0, 1]

11. Calculate byte size

Every programmer wants their JavaScript programs to be efficient and perform well. To do this, we need to ensure that we have data of a certain size without overloading memory. Check out the code snippet below to see how to check the bytes of any data.

// byte size calculation
const ByteSize = string => new Blob([string]).size;
console.log(ByteSize("Codding")) // 7 
console.log(ByteSize(true)) // 4
console.log(ByteSize("")) // 4

12. Array to CSV

CSV is a widely used spreadsheet nowadays, you can convert an array to CSV using a simple code snippet as shown below.

// Code Example
const ArrayToCsv= (array, delimiter =',')=> array.map(value => value.map(num => `"${num}"`).join(delimiter)).join('\n');
console.log(ArrayToCsv([['name', 'age'], ['haider', '22'], ['Peter', '23']]))
// Output
// "name","age"
// "haider","22"
// "Peter","23"

13. The last element of the array

Now you no longer need to iterate or loop the whole array and extract the last element. You can do the same with the simple code snippet below.

//code example
const LastElement = array => array[array.length - 1];
console.log(LastElement([2,3,4])) // 4
console.log(LastElement([2,3,4,5])) // 5
console.log(LastElement([2,3])) // 3

Finish

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132013808