Skip to main content

Posts

Showing posts with the label JavaScript

JavaScript vs TypeScript in 2025: Which One Should Beginners Learn?

JavaScript vs TypeScript in 2025: Which One Should You Choose? In 2025, web development continues to evolve rapidly, and developers often face the choice between JavaScript and TypeScript . Both languages are widely used, but choosing the right one depends on your project requirements, team experience, and long-term maintainability. 1. JavaScript vs TypeScript: Key Comparison Let’s start by understanding the main differences between the two languages in a simple way: Feature JavaScript TypeScript Typing Dynamically typed — variable types are flexible and checked only at runtime. Statically typed — variable types are defined, errors detected at compile-time. Error Detection Runtime errors only...

Understanding JavaScript Objects & Classes

Understanding JavaScript Objects & Classes JavaScript is built on objects. Whether you’re storing data, organizing functionality, or working with modern ES6 classes, a solid understanding of objects is essential. In this article, we’ll cover objects, prototypes, the this keyword, and classes with clear examples. Objects in JavaScript Objects are collections of key–value pairs. They can contain both data and functions, making them versatile structures for many tasks. const user = { name: "Ava", age: 28, greet() { return `Hi, I'm ${this.name}`; } }; Creating Objects The simplest way to create objects is with object literals. You can also use spread syntax to clone or extend them: const person = { name: "Kai", score: 42 }; const clone = { ...person }; // shallow copy Prototypes JavaScript uses prototypal inheritance, meaning objects can inherit beha...

How to Create a React Project

How to Create a React Project React is a popular JavaScript library for building interactive and dynamic user interfaces. Whether you are a beginner or a professional developer, creating a new React project is simple. In this guide, we’ll cover how to set up a React project both locally using Node.js and online using React.new . Step 1: Install Node.js To create a React project locally, you need Node.js installed on your system. Check your installation using: node -v npm -v Step 2: Create a React App Locally Use create-react-app to scaffold a new project: npx create-react-app my-app cd my-app npm start After running npm start , your app will be available at http://localhost:3000 . Step 3: Quick Start Using React.new If you prefer to start instantly without installing anything, visit https://react.new . This creates a new React project in the browser, ready for immediate ...

How to Use Nodemon in Node.js Projects

How to Use Nodemon in Node.js Projects Tired of manually restarting your Node.js server every time you make a change? That’s where nodemon comes in. This guide shows you how to install and use nodemon to streamline your development process. 1. What is Nodemon? Nodemon is a command-line tool that watches your Node.js files and automatically restarts the server whenever changes are detected. It saves time and improves your dev flow. 2. Installing Nodemon You can install nodemon globally (accessible from anywhere) or as a dev dependency: Global installation: npm install -g nodemon Local (project-level) installation: npm install --save-dev nodemon 3. Running Your App with Nodemon If your main file is app.js , you can start your project like this: nodemon app.js This behaves just like node app.js , but restarts automatically whenever the file changes. 4. Update Your Package.json (Optional) You can add a cust...

How to Set Up and Run Your First Node.js Project

How to Set Up and Run Your First Node.js Project New to Node.js? This guide walks you through setting up your first Node.js project from scratch—whether you’re building APIs, CLI tools, or learning backend development. 1. What is Node.js? Node.js is a runtime environment that allows you to run JavaScript on the server side. It’s fast, event-driven, and perfect for building scalable web apps and services. 2. Install Node.js Download and install Node.js from the official website: https://nodejs.org Once installed, verify it in your terminal: node -v npm -v 3. Create Your Project Folder Open your terminal and create a new directory for your project: mkdir my-first-node cd my-first-node 4. Initialize a New Node.js Project Use npm (Node Package Manager) to create a package.json file: npm init -y This will generate a basic configuration file to manage your project dependencies. 5. Create Your First Script ...

How to Build and Publish a Custom Node.js Utility Package

Build a Custom Node.js Utility Package – Step-by-Step Guide 🚀 View GitHub Repo: node-custom-package-guide 💡 Want to reuse common string operations like capitalize() or slugify() across projects? Learn how to create and publish your own Node.js utility package! 📁 Project Structure custom-package/ ├── index.js ├── package.json ├── README.md └── utils/ ├── capitalize.js ├── camelCase.js ├── slugify.js └── greeting.js ✅ Initialize the Package npm init -y This creates a package.json with default values. 🧩 Write Utility Functions utils/capitalize.js function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } module.exports = capitalize; utils/camelCase.js function camelCase(str) { return str .replace(/\s(.)/g, (match, group1) => group1.toUpperCase()) .replace(/\s/g, '') .replace(/^(.)/, (match, group1) => group1.toLowerCase()); } module.exports ...

Node.js Path Module – Complete Notes with Real Use Cases

Node.js Path Module – Notes with Use Cases 💡 The path module in Node.js provides utilities to work with file and directory paths. It is built-in and can be imported using: const path = require('path'); ✅ path.basename(path) Returns: The filename from a full path. Use Case: Extract file name during file upload logging. path.basename('C:\\temp\\abcd.html'); // Output: 'abcd.html' ✅ path.dirname(path) Returns: The directory portion of the path. Use Case: Get parent directory before saving a file. path.dirname('foo\\abcd\\test.html'); // Output: 'foo\\abcd' ✅ path.extname(path) Returns: The file extension from the path. Use Case: Validate file type before processing upload. path.extname('test.html'); // '.html' path.extname('file.name.md'); // '.md' path.extname('.hiddenfile.txt'); // '.txt' path.extnam...

Solving the Two Sum Problem in JavaScript

Solving the Two Sum Problem in JavaScript Problem: Given an array of integers and a target number, return indices of the two numbers that add up to the target. 🔢 Input: let arr = [1, 2, 6, 9, 3, 2, 8, 7]; let resultNumber = 10; 🧠 Brute Force Approach: This solution checks all possible pairs (i, j) in the array. let indexes = []; for(let i = 0; i 📈 Time Complexity: O(n²) – because we check each pair of elements once. 🧩 Sample Output: [ [ 0, 3 ], [ 1, 6 ], [ 4, 7 ], [ 5, 6 ] ] 💡 Optimization Tip: We can reduce time complexity to O(n) using a hash map. Stay tuned for the optimized version in my next post! ✅ Summary: Clear understanding of nested loops Simple yet effective for small input sizes Ideal for beginners practicing DSA If you liked this post, follow my blog or connect with me on LinkedIn !

How to Write DRY Code in Node.js Using Helper Functions – Beginner’s Guide

How to Write DRY Code in Node.js Using Helpers As developers, one of the most important principles we should follow is DRY: Don't Repeat Yourself . Repetition makes code harder to maintain and debug. In this post, you'll learn how to write cleaner, reusable, and DRY code in Node.js using helper functions. 💡 What is DRY Code? DRY code means reducing repetition in your codebase. Instead of copying and pasting the same logic multiple times, you extract that logic into a function (or helper), then reuse it wherever needed. 🛠️ What are Helpers in Node.js? Helpers are utility functions that handle repetitive tasks like formatting, validation, date conversions, logging, etc. These are usually stored in a separate file (like helpers.js ) to keep the main code clean. 📁 Example Project Structure project/ ├── helpers/ │ └── stringHelper.js ├── routes/ │ └── userRoutes.js ├── app.js ✍️ Example: Creating a Helper ...

How to Use Node.js Documentation the Better Way

How to Use Node.js Documentation in a Better Way If you're learning or working with Node.js, the official documentation is one of the most important resources at your fingertips. Unfortunately, many developers ignore it or find it hard to navigate. In this guide, we'll walk through simple and effective ways to use the Node.js documentation better so you can become a more confident backend developer. 📘 1. Start with the Right Version Node.js evolves fast. Always use the documentation that matches the version you're running locally. Check your version: node -v Then go to the matching version docs from nodejs.org . 🔍 2. Understand the Structure of Docs Each module in the docs is structured in a standard format: Description: What it does Syntax: How to use it Parameters: Input details Return Value: What it returns Examples: Code samples to try out 🧭 3. Use the Sidebar for Easy Navigation ...

Axios vs Fetch API in JavaScript – Everything You Need to Know

Axios vs Fetch API in JavaScript – Everything You Need to Know When building web apps, you often need to fetch data from APIs or send data to a server. In JavaScript, two popular ways to make HTTP requests are Fetch API and Axios . But which one should you use? In this guide, we’ll break it down with examples, pros and cons, features, and real-life use cases. 🔍 What is Fetch API? Fetch API is a built-in browser feature that allows you to make HTTP requests. It returns Promises and is supported in all modern browsers. fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); ⚙️ What is Axios? Axios is a third-party JavaScript library built on top of XMLHttpRequest . It provides a clean API for sending HTTP requests and handling responses. axios.get('https://jsonplaceholder.typicode.com/posts') .then(respons...

How to Use Middleware in Node.js (Express)

How to Use Middleware in Node.js (Express) with Real-Time Example Middleware is one of the most powerful concepts in Express.js, allowing you to intercept and modify requests and responses. In this guide, we’ll explore middleware usage in Express — with a real-world use case: Authentication Middleware . 📌 What is Middleware? In Express.js, middleware is a function that sits between the request and response in the HTTP lifecycle. It has access to: req – the HTTP request object res – the HTTP response object next() – a function that passes control to the next middleware Think of middleware as the logic that can: Log request details Check if a user is authenticated Parse request bodies (JSON, form data, etc.) Serve static files Handle errors Middleware runs before the final route handler and can either: Terminate the request (by sending a response) Call next() to pass control to t...

Building a REST API with Express.js – Step-by-Step Guide

Building a REST API with Express.js – Step-by-Step Guide If you're a JavaScript developer looking to build scalable backend services, Express.js is a great starting point. In this guide, you’ll learn how to build a basic RESTful API using Node.js and Express.js. 🔧 Prerequisites Basic knowledge of JavaScript Node.js and npm installed Code editor (like VS Code) Postman or curl for testing 📁 Step 1: Initialize a Node.js Project mkdir express-api cd express-api npm init -y 📦 Step 2: Install Express.js npm install express 📄 Step 3: Create the Main Server File Create a file named server.js and add the following code: const express = require('express'); const app = express(); const PORT = 3000; app.use(express.json()); app.get('/', (req, res) => { res.send('Welcome to the Express.js API!'); }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); })...

Building a Weather App with JavaScript and Open Weather API

How I Built a Weather App using JavaScript and OpenWeather API Have you ever wondered how weather apps work behind the scenes? In this blog, I’ll walk you through how I built a simple yet powerful weather app using HTML , CSS , JavaScript , and the OpenWeather API . 🧾 Prerequisites Basic knowledge of HTML, CSS, and JavaScript Code editor (like VS Code) OpenWeather API key (free to generate) Basic understanding of REST APIs 📁 Project Structure weather-app/ ├── index.html ├── style.css ├── script.js ✨ Features 🌆 Search weather by city name 🌡️ Display temperature, humidity, wind speed 🌤️ Dynamic icon and weather description 🌈 Background image changes based on weather 🕔 5-day forecast using OpenWeather's Forecast API 🔄 Reset button to clear UI 📱 Responsive layout with Bootstrap 🔌 How It Works The app connects to two endpoints from the OpenWeather API: /weather –...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. 🧾 Prerequisites Node.js installed Basic knowledge of Express.js Internet connection 📁 Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js 📦 Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon 🔁 Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } 🔐 Step 2: Create a .env File Create a .env file a...

Most Important JavaScript Events You Must Know

Top JavaScript Events You Must Know JavaScript is event-driven, meaning a lot of its power lies in responding to user interactions and browser behavior. Whether you’re building a simple webpage or a complex web app, understanding **JavaScript events** is crucial. 🔑 What Are JavaScript Events? Events are signals that something has happened — like a button click, a key press, a form submission, or even a mouse hover. You can attach listeners to these events to execute JavaScript code. 📋 Commonly Used JavaScript Events click – User clicks an element submit – Form submission keydown , keyup – Key press events change – Value change (e.g. dropdowns, inputs) mouseover , mouseout – Mouse hovers over or leaves an element load – Page or resource finishes loading DOMContentLoaded – DOM fully loaded without waiting for styles/images resize – Browser window is resized scroll – Scroll action happens 📌 E...

Understanding JavaScript Arrow Functions

Understanding JavaScript Arrow Functions Arrow functions, introduced in ES6 (ECMAScript 2015), provide a cleaner and shorter way to write functions in JavaScript. They are especially useful for callbacks and functional programming. ✨ Syntax Comparison Here’s how a regular function compares to an arrow function: // Traditional function function add(a, b) { return a + b; } // Arrow function const add = (a, b) => a + b; 🔍 When Should You Use Arrow Functions? When you want shorter, cleaner syntax When you don’t need your own this context In array methods like map , filter , and forEach 📌 Key Features Implicit return for single-expression functions Lexical this binding (doesn’t bind its own this ) No arguments object ⚠️ Things to Watch Out For Arrow functions don’t have their own this . Be careful when using them as object methods or constructors. Example: Lexical this const per...

How to Display Flash Messages in EJS using Node.js and Express

Displaying Flash Messages in EJS with Node.js and Express Flash messages are a great way to give users quick feedback — like "Login successful!" or "Please enter all fields!" . In this guide, you’ll learn how to implement them using: express-session connect-flash EJS templating 📦 Step 1: Install Required Packages npm install express express-session connect-flash ejs ⚙️ Step 2: Setup Express App and Middleware const express = require('express'); const session = require('express-session'); const flash = require('connect-flash'); const app = express(); // Set view engine app.set('view engine', 'ejs'); // Middleware app.use(express.urlencoded({ extended: true })); app.use(session({ secret: 'yourSecretKey', resave: false, saveUninitialized: true })); app.use(flash()); // Make flash messages available to all views app.use((req, res, next) => { res.lo...