5 Useful JavaScript code examples for beginners in 2022
Tags: programming, javascript, devops, 100daysofcode
Published: 2022-02-11 12:30:12

## 1. Sort an Array
Sorting an array is one of the easiest and most regularly used snippets. Basically, JavaScript has its own built-in function i.e. sort() function. This sort() function helps you to directly sort an array as well as numbers.

sort() function sorts in both ways alphabetic sort and numeric sort. Let’s see the code:
```
//strings
const names = ["Prakash", "Ajay", "Mohan"];
names.sort();
//['Ajay', 'Mohan', 'Prakash' ]
//Numbers
const numbers = [25, 18, 29];
numbers.sort((a, b) => {
  return a - b;
});
//[ 18, 25, 29 ]
```

## 2. Reverse a String
Reverse a string is the easiest and a very common problem which you can solve in 3 different ways. Following are the 3 ways to reverse a string:

By using 3 simple function i.e. split(), reverse(), and join(): Firstly you have to split the string and make an array, then reverse it, and lastly join them.
By using loop: It’s very simple and most of them have already know about this concept. You simply have to use for loop in reverse order and add it to a new variable.
Furthermore, we can also use spread operator(…) and reverse() function to reverse your string.
The last possible solution is the recursion function. Now let’s see the code:

```
// reverse using basic functions
function reverse(string) {
    return string.split("").reverse().join("");
}
console.log(reverse('Prakash'));


// reverse using loop

function reverse(string) {
    var newString = "";
    for (var i = string.length - 1; i >= 0; i--) {
        newString += string[i];
    }
    return newString;
}
console.log(reverse('Prakash'));


//Using spread operator

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


// reverse using recursion function

function reverse(string) {
  if (string === "")
    return "";
  else
    return reverse(string.substr(1)) + string.charAt(0);
}
console.log(reverse('Prakash'));
```

## 3. Using the Spread Operator
The spread operator is a JavaScript feature that allows an expression to be expanded in places where multiple arguments or elements are expected. This article will discuss how to use the spread operator in JavaScript code snippets.

The spread operator is represented by three dots (…) and it can be used with arrays, sets, and other iterables. It accepts another expression as an argument and evaluates it for each element in the array or set.

JavaScript code examples:

```
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
```

## 4. Difference in Arrays
Basically, it’s the most interesting code snippet in which we will use new concepts that are added in ES6 JavaScript. JavaScript code examples(snippets) are handy when you are working on a long array and want to know the similarities or differences of that array.

In this code snippet, you will use a new JavaScript feature i.e. spread operator(…). It usually takes in an iterable (e.g an array) and expands it into individual elements.

```
//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]
```

## 5. Loop through an Object
Basically, looping over an object is a regular basis need of every programming language and the easiest JavaScript code examples or snippets you can use.

Sometimes it can be a complex object with multiple keys and values. Going through this kind of pair is a little confusing. Here I am going to describe two possible ways.

Here we have discussed two ways to loop through an object. In the first one, we have used it for in loop, and in the second one, we have used object which is very easy.

JavaScript code examples:

```
// Simple way

const person = { name: "Prakash", Age: 25, Gender: "Male" };
for (const property in person) {
  console.log(`${property}: ${person[property]}`);
}

// Another way
const anotherPerson = {
  Name: 'Shoaib',
  Age: 25,
  Gender:"Male"
};

for (const [key, value] of Object.entries(anotherPerson)) {
  console.log(`${key}: ${value}`);
}
```
https://untiedblogs.com/9-useful-javascript-code-examples-for-beginners/