Site icon NexGismo

Is JavaScript a Frontend Or Backend Language?

Is JavaScript a Frontend Or Backend Language?

JavaScript is an important part for modern web development. It is also a very flexible language because it is primarily used for frontend and backend purposes. But is it a frontend or backend language? The answer is that it is both. Let’s explore further to see how it operates within each aspect.

JavaScript in Frontend Development

In layman’s terms, frontend development means client side and pertains to what users see and experience in their web browsers. Javascript was created with the intention of improving web pages’ user experience by making them more interactive and fun to use.

Examples of JavaScript in Frontend

// Example of DOM Manipulation  
document.getElementById('search').addEventListener('input', function() {  
  // Fetch search results and update the DOM  
  let query = this.value;  
  fetch(`/search?q=${query}`)  
    .then(response => response.json())  
    .then(data => {  
      document.getElementById('results').innerHTML = data.results.map(result => `  
        <div>${result.name}</div>  
      `).join('');  
    });  
});  
// Example of Event Handling  
document.getElementById('myForm').addEventListener('submit', function(event) {  
  let isValid = true;  
  let inputs = this.querySelectorAll('input');  
  inputs.forEach(input => {  
    if (!input.value) {  
      isValid = false;  
      input.style.borderColor = 'red';  
    } else {  
      input.style.borderColor = 'green';  
    }  
  });  

  if (!isValid) {  
    event.preventDefault();  
  }  
});  
// Example of a React Component  
import React, { useState, useEffect } from 'react';  

function ProductList() {  
  const [products, setProducts] = useState([]);  

  useEffect(() => {  
    fetch('/api/products')  
      .then(response => response.json())  
      .then(data => setProducts(data));  
  }, []);  

  return (  
    <div>  
      {products.map(product => (  
        <div key={product.id}>  
          <h2>{product.name}</h2>  
          <p>{product.description}</p>  
        </div>  
      ))}  
    </div>  
  );  
}  

export default ProductList;  

JavaScript Within Backend Development

 With the emergence of Node.js, JavaScript transitioned to the server-side as well, allowing it to carry out backend development activities. In this regard, JavaScript is now considered a full stack language as it can operate on both server and client side.

Some JavaScript Based Backend Activities Are:

// Example of a Node.js Express Server  
const express = require('express');  
const app = express();  
const port = 3000;  

app.use(express.json());  

app.get('/users', (req, res) => {  
  // Fetch users from database  
  res.json([{ id: 1, name: 'John Doe' }]);  
});  

app.post('/users', (req, res) => {  
  // Save user to database  
  const user = req.body;  
  res.status(201).json(user);  
});  

app.listen(port, () => {  
  console.log(`Server running at http://localhost:${port}`);  
});  
// Example of Mongoose for MongoDB  
const mongoose = require('mongoose');  
const Schema = mongoose.Schema;  

mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });  

const userSchema = new Schema({  
  name: String,  
  email: String,  
  password: String  
});  

const User = mongoose.model('User', userSchema);  

// Create a new user  
const newUser = new User({ name: 'Jane Doe', email: 'jane@example.com', password: 'password123' });  
newUser.save().then(() => console.log('User saved'));  
// Example of a Real-Time Chat with Socket.io  
const io = require('socket.io')(3000);  

io.on('connection', socket => {  
  console.log('New user connected');  

  socket.on('chat message', msg => {  
    io.emit('chat message', msg);  
  });  

  socket.on('disconnect', () => {  
    console.log('User disconnected');  
  });  
});  

Can JavaScript be Classed as a Frontend or Backend Language?

The answer to this question is yes, knowing how to use javascript is a requirement for both frontend and backend development. This means developers are able to perform both client and server-based functions with the same language, saving time.

Conclusion

In conclusion, JavaScript is a multi-faceted language. It can be used in frontend development as well as backend development. This trait allows developers to build on both client and server using the same language which is highly beneficial for productivity. Learning javaScript allows you to build wide-reaching sleek to the point web applications.

Exit mobile version