9 Useful JavaScript code examples for beginners

9 Useful JavaScript code examples for beginners in 2022

Useful JavaScript code examples!!!

Nowadays JavaScript is a widely-used programming language and one of the best languages to build a responsive website.

Whether you want to learn Web development, Game development, 3-D graphics, want to build mobile applications, and many more. JavaScript played a very vital role to develop these applications. Hence JavaScript is the most popular and the most loved language around the globe.

Javascript has some basic JavaScript code example(snippets) that is really important to know. The code snippets are a set of small pieces of JavaScript code that can be added to any website.

In this article, we will discuss 9 JavaScript code examples (snippets) that are really important to know as a beginner.

LOL!!!

Here are a couple of related posts you may find helpful, too:

  1. How to make money through coding? 9 Easy Ways To Make Money.
  2. 15+FREE Stuff For College Students Using Your College ID.
  3. how to get rich by coding? I make $100 every month from coding

9 Useful JavaScript code examples

<!-- wp:heading --> <h29 Useful JavaScript code examples

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:

  1. 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.
  2. 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.
  3. Furthermore, we can also use spread operator(…) and reverse() function to reverse your string.
  4. 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]
JavaScript code examples

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}`);
}

6. Given an integer number is the power of two

This section contains JavaScript code snippets to help you check if a number is a power of two.

//example code

const isPowerTwo = n => !!n &&( n & (n - 1) ) == 0;
console.log(isPowerTwo(3)) //true
console.log(isPowerTwo(8)) //true
console.log(isPowerTwo(4)) //true

7. Replace part of a string

String.replace() method is used to replace all occurrences of the specified string with another string in the target string.

The following code snippets show how to replace a substring in JavaScript.

const string = "Prakash is a bad looking guy"
const replacedString = string.replace("bad", "good")

console.log(replacedString) //Output: "Prakash is a good looking guy"

8. Merge arrays

JavaScript code snippets for merge arrays is a function that takes two arrays and returns a new array containing all the elements from both of them.

There are three methods of merging arrays in JavaScript:

  • Using concat() function.
  • Using Array.concat() method.
  • Using Array.join() function.

The concat() function takes two or more arrays and inserts the elements of the second array into the first array at the position where it is called while joining them together into a single array, which is returned as a result of the call to concat().

The Array.concat() method does not return any new array but instead modifies the passed argument by inserting all of its elements at its end (in order).

The Array.join() function takes an array and inserts each element in that array into a new string separated by commas,

let arrOne = [1,3,5]
let arrTwo = [2,4,6]

// first way
let combine = arrOne.concat(arrTwo) 
console.log(combine)

// second way
combine = [...arrOne,...arrTwo]
console.log(combine)

9. Error Handling

Error handling is one of the most important concepts of JavaScript which is regularly used while developing any applications.

There are a few different ways to handle errors in JavaScript, but the most common way is using try-catch statements.

The try-catch statement can be used when you want to catch an error and do something with the error. The catch block will execute if an error occurs in the try block.

JavaScript code examples:

try {
try_statements
}
catch (exception_var) {
catch_statements
}
finally {
finally_statements
}

Final Thoughts

I hope this blog helps you and how these 9 Useful JavaScript code examples work.

If you find it helpful then please share it with your friend and colleagues and show some support. Let me know if you have any doubts please comment down regarding JavaScript code examples:.

To contact me here’s my Instagram link: untied_blog

Read more

  1. how to get rich by coding? I make $100 every month from coding
  2. How To Create An App Without Coding| Build an App In 5 Minutes
  3. 11 Amazing ReactJS Projects Ideas For Beginners with Source Code
  4. How To Answer “Tell Me About Yourself”| Interview Questions.
  5. How To Answer “Strengths And Weaknesses” (Interview Questions)
  6. “Why Should We Hire You” 7+ Best Answers Examples

Leave a Comment