5 JavaScript Code Snippets for Beginners


In this article we will discuss 5 JavaScript Code Snippets for Beginners

An extensive collection of code javascript snippets you can integrate into your js projects. Optimal for beginners wanting to boost their Javascript knowledge.

What is JavaScript?
JavaScript is a client-side scripting language used to build immersive web applications. With JavaScript, you can dynamically update data on a html webpage, add animate elements, control images/files, and handle performance.

1. AJAX Requests

The given below snippets will influence the fetch() function to execute HTTP requests (POST,GET,REQUEST, etc.).

GET Request
Get a JSON file and output the data:

fetch('https://example.com/data.json').then(response => response.json()).then(data => console.log(data));

POST Request
run a POST request with JSON initiate as the data type:

fetch('https://example.com/authenticate', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    body: JSON.stringify({ username: 'David', password: '12345' })
}).then(response => response.json()).then(data => {
}).catch(error => {
    console.error('Error:', error);

We are using here the FormData interface:

const formData = new FormData();
formData.append('username', 'David');
formData.append('password', '12345');
fetch('https://example.com/authenticate', {
    method: 'POST',
    body: formData
}).then(response => response.json()).then(data => {
}).catch(error => {
    console.error('Error:', error);

In adding to above, you can select an current HTML form with:

const formData = new FormData(document.querySelector('#yourFormId'));

2. Input Validation

The given javascript code snippets will validate several input values.

Validate Email Address

if (/\S+@\S+\.\S+/.test('david@codeshack.io')) {
    console.log('Email is valid!');
} else {
    console.log('Email is invalid!');

String Length

Validate string length between two numbers:

const username = "david123";
if (username.length > 4 && username.length < 16) {
    console.log('Username is valid!');
} else {
    console.log('Username must be between 5 and 15 characters long!');

Alphanumeric Validation

Check if a string pass only letters and numeric values:

if (/^[a-zA-Z0-9]+$/.test(username)) {
    console.log('Username is valid!');
} else {
    console.log('Username must contain only letters and numerals!');

Variable is Number

Check if a variable is a numeric value:

const num = 12345.12;
if (!isNaN(parseFloat(num)) && isFinite(num)) {
    console.log('Variable is a number!');
} else {
    console.log('Variable is not a number!');

3. Storing content in the Browser

The Web Storage API will allow us to save data in the browser. The localStorage interface can store up to 5MB per domain (in most browsers) as opposing to the 4KB limit cookies can store data.

Set Item
Now, Store a new item in loc
al storage:

localStorage.setItem('username', 'David');

Get Item

Fetch an item from local storage:


Item Exists

See if item exists in local storage:

if (localStorage.getItem('username')) {
    console.log('Item exists!');

Remove Item

Take away an item from local storage:


Remove all items:


4. Data Attributes

The data attributes will allow you to associate data to a specific element. You can then later on use Javascript to get the data.

The given snippet will get data attributes with Javascript:

<a href="#" data-name="David" data-surname="Adams" data-unique-id="30" data-btn>Click me!</a>
const btn = document.querySelector('a[data-btn]');
btn.onclick = event => {
    // Output data attributes
    console.log(btn.dataset.name); // David
    console.log(btn.dataset.surname); // Adams
    console.log(btn.dataset.uniqueId); // 30

5. Inject HTML

The given below code snippets will insert HTML into a particular point in the HTML document.

Inject After

Insert HTML after the following element:

<a id="home-btn" href="home.html">Home</a>
document.querySelector('#home-btn').insertAdjacentHTML('afterend', '<a href="about.html">About</a>');

Inject Before

Insert HTML before the given element:

<section id="section-2">
    <h2>Title 2</h2>
    <p>Description 2</p>
document.querySelector('#section-2').insertAdjacentHTML('beforebegin', `
        <h2>Title 1</h2>
        <p>Description 1</p>

Add and Prepend HTML

Add an item to a list element:

<ul id="list">
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
document.querySelector('#list').insertAdjacentHTML('beforeend', '<li>Item 5</li>');

Prepend an item to a list element:

document.querySelector('#list').insertAdjacentHTML('afterbegin', '<li>Item 1</li>');

Also Read: Remove Duplicates value from Array in javascript

Like it? Share with your friends!