JavaScript Begineer to Advance
JavaScript Begineer to Advance

In current generation JavaScript is backbone of web development, enabling dynamic, interactive websites & applications, Now JS is also been used as server side backend programming language used as to build server. Whether you’re a complete beginner or someone with some coding experience, In this quick guide will take you to topic to study on daily to learn JavaScript from the basics to advanced concepts, making yourself to build a strong foundation in JavaScript concepts. Follow this Article on Day wise like Day 1 basic like wise Each day focuses on a specific topic. By following this article by the end, you’ll have good knowledge on JavaScript and will be able/ready to complete more complex projects.

Day 1: Introduction to JavaScript

Start your journey by knowing about JavaScript & it’s history.

What is JS?

JavaScript is a High-Level Interpreted Programming Language that is been used to add interactivity & dynamic behavior to Applications.

JS Variables: Containers used to store data. var, let & const.

Data Types: We have 2 types of DataTypes in JavaScript, 1. Primitive & 2. Non-Primitive DataType.
Primitive DataTypes are(String, Number, BigInt, Boolean, Undefined, Null, Symbol).
Non Primitive DataTypes are (Objects, Arrays, Functions, Date).

Operators: Operations in JS are Symbols used to perform operations on variables & values.
Operations like (+ Addition, Subtractions, * Multiplications, / Divisions, % Modules, ** Exponentiation (Power), ++ increments, Decrement, == equal, === Strick equal to, != not Equal to, > greater then, < less then and more )

Functions: In JavaScript Functions are block of code that can be defined once & reused when required. In JavaScript we have Functions likes (Named Function, Anonymous Functions, Arrow Function, Function Expressions, IIFE ( Immediately Invoked Functions Expression), Async Functions and more.


Day 2: Control Flow & Conditionals

Conditional Statement: Learn how to make use of conditional statements like if else if and else or switch for executing different code blocks based on different conditions.

Comparison Operations: As stated above we can make use of Comparison operation such as ==,===,!=,!==,<,>,<=,>=.

Logical Operation: make use of logical condition like && (and operator), || (or operator), and ! (NOT operator), that is mostly used in condition statement like if conditions.

Ternary Operation: This are basically single line statement that act as if else condition.
condition ? exprIfTrue : exprIfFalse


Day 3: Loops & Iterations

Study in depth on all the types of iteration like

for: Execute the code block with the specified number of times.

for (initialization; condition; increment/decrement) {
    // Code block to execute
}

while: Execute the code block until the condition is true.

while (condition) {
    // Code block to execute
}


do…while: This loop will definitely execute at least once before the condition is check

do {
    // Code block to execute
} while (condition);


for…in: Specially used to iterate an object properties.

for (let key in object) {
    // Code block to execute
    // key refers to the object's property names
}


for…of: Iterate over the values of an iterable object like arrays or strings

for (let value of iterable) {
    // Code block to execute
    // value refers to the elements of the iterable
}

Day 4: Arrays & Objects

Arrays: Ordered collections of data/values that can we accessed by using numeric indices.

Array method: Learn how to make use of Arrays predefined functions using which we can manipulate array content, such as push(), pop(), shift(), unshift() ,splice(), slice() and more.

Objects: Object are basic collections of data that are stored in a form of key-value pairs. JavaScript have also provided objects method that is used to play with object in JS.

Object.assign(), Object.create(), Object.defineProperty(), Object.defineProperties(), Object.entries(), Object.freeze(), Object.fromEntries() and more.


Day 5: Function & Scopes

Learn about what is scope and types of scopes in Javascript

Local Scope: The Variables that are declared within an function are accessable only within that particular function, if used outside will result into undefined.

function localScopeExample() {
    let localVar = "I'm local";
    console.log(localVar); // Accessible here
}

localScopeExample();
console.log(localVar); // Error: localVar is not defined (undefined outside the function)

Global Scope: This are the variable that are accessible anywhere in a code base.

let globalVar = "I'm global";

function globalScopeExample() {
    console.log(globalVar); // Accessible inside the function
}

globalScopeExample();
console.log(globalVar); // Accessible outside the function too

Function Declarations: This function are defined by using function keyword.

function greet() {
    console.log("Hello!");
}

greet(); // Function call

Function Expressions: This are the functions that are defined as expressions, offen assigned to a variable.

const greet = function() {
    console.log("Hello!");
};

greet(); // Function call

Arrow Functions: A more concise syntax for writing functions, using the arrow (=>) syntax.

const greet = () => {
    console.log("Hello!");
};

greet(); // Function call

Day 6: DOM Manipulations

DOM (Document Object Model): A programming interface for web documents, representing the structure of an HTML document as a tree of objects.

Selecting Elements: Methods like getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector(), and querySelectorAll() to select elements from the DOM.

Modifying Elements: Methods like innerHTML, textContent, setAttribute(), classList etc to modify the content and attributes of elements.

Creating & Removing Elements: Methods like createElement(), appendChild(), removeChild() etc to dynamically create & remove elements from the DOM.


Day 7: Event Handling

Events: Any Action performed by user or happen because of triggers are Events.

Event Handlers: This are functions that are triggered only when specific event occurs, such a user clicked on a button is a event.

Event Listeners: Methods like addEventListener() to connect event handlers to an elements.

Event Object: An object containing all the information about the event, passed to event handler functions as an arguments.

Event Propagation: The order in which event handlers are executed.

Event Delegation: Technique for handling events on multiple elements with a single event handler.


Day 8: Asynchronous Operation

Callbacks: A function that is passed as an argument to other functions are called Callbacks, and the callback is executed later.

function fetchData(callback) {
    setTimeout(() => {
        console.log("Data fetched");
        callback();
    }, 1000);
}

function processData() {
    console.log("Processing data");
}

fetchData(processData);  // Output: Data fetched (after 1 second) then Processing data

Promises: A Promise is an object that simply represent event completion or failure on an asynchronous operations.

const fetchData = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Data fetched");
    } else {
        reject("Error fetching data");
    }
});

fetchData.then(result => console.log(result))
         .catch(error => console.log(error));

async/await: Introduced with JavaScript ES6 version to basically write asynchronous code in a synchronous manner.

function fetchData() {
    return new Promise((resolve) => {
        setTimeout(() => resolve("Data fetched"), 1000);
    });
}

async function processData() {
    const data = await fetchData();
    console.log(data);  // Output: Data fetched
}

processData();

XHR (XML HttpRequest): This is an Object used to interact with servers & make HTTP requests from web browsers.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onload = function () {
    if (xhr.status === 200) {
        console.log(xhr.responseText);
    }
};
xhr.send();

Fetch API: Modern alternative to XHR from making HTTP request in JavaScript.

fetch("https://api.example.com/data")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

AJAX (Asynchronous JavaScript and XML): Technique for updating part of web page with reloading the whole page.

const xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com/data", true);
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        document.getElementById("content").innerHTML = xhr.responseText;
    }
};
xhr.send();

Day 9: ES6 & Modern JavaScript

ES6 (ECMAScript 2015): This is Major Update of JavaScript Language.

Arrow Functions: A more concise syntax for writting functions.

const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5

Template Literals: String that allows embedded expressions.

const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!

Destructuring Assignment: Extracting values from array or objects & assign it to a variables.

// Array Destructuring
const [x, y] = [10, 20];
console.log(x, y); // Output: 10 20

// Object Destructuring
const person = { firstName: "Jane", age: 25 };
const { firstName, age } = person;
console.log(firstName, age); // Output: Jane 25

Spread Operator: Expands an iterable (like array) into individual elements.

const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5, 6];
console.log(moreNumbers); // Output: [1, 2, 3, 4, 5, 6]

Classes & inheritance: Prototype Inheritance in JS using class syntax.

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.

Modules: Encapsulating code into reusable modules using import & export statements.

// In math.js (exporting module)
export const add = (a, b) => a + b;

// In main.js (importing module)
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5

Day 10: Advanced JavaScript Concepts

Closures: A Closure are the functions that remembers variables from it’s outer scope, even though the outer function finished its executions. by using Closure in js we can maintain state across function calls.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        console.log(count);
    };
}
const counter = outer();
counter();  // Output: 1
counter();  // Output: 2

ProtoTypes and Inheritance:

This is an mechanism by which JS object inherit feature from one another.

function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    console.log(`Hello, my name is ${this.name}`);
};
const john = new Person("John");
john.greet();  // Output: Hello, my name is John

Context(this): A reference to the object that owns the currently executions code.

const obj = {
    name: "Alice",
    greet: function() {
        console.log(this.name);
    }
};
obj.greet();  // Output: Alice

Execution Context & hoisting:

Here variable declarations is automatically moved to top of their containing scope

console.log(x);  // Output: undefined (due to hoisting)
var x = 5;

Event Loops:

Although JavaScript is a single threaded it make use of Event Loop to perform non-blocking operations.

console.log("Start");
setTimeout(() => console.log("Delayed"), 1000);
console.log("End");
// Output: Start, End, Delayed (after 1 second)

Day 11 & 12: Function Programming & Advanced JS

Here are brief explanations for each of the topics:

Functional Programming:

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing state or mutable data. It emphasizes the use of pure functions, immutability, and higher-order functions to create predictable and maintainable code.

Pure Functions:

A pure function is a function that, given the same input, always returns the same output and has no side effects (i.e., it doesn’t alter any external state or depend on external variables).

function add(a, b) {
    return a + b;  // Pure function: no side effects
}

Immutability:

Immutability means that once a data structure is created, it cannot be changed. Instead of modifying an object, you create a new one with the desired changes, which helps avoid unintended side effects.

const arr = [1, 2, 3];
const newArr = [...arr, 4];  // Creating a new array instead of modifying the original

Higher-Order Functions:

A higher-order function is a function that takes other functions as arguments or returns a function as its result. These are often used to abstract or compose behaviors.

function greet(name) {
    return function(message) {
        console.log(`${message}, ${name}`);
    };
}
const sayHello = greet("Alice");
sayHello("Hello");  // Output: Hello, Alice

Map, Filter & Reduce:

These are common higher-order functions in JavaScript that operate on arrays. map transforms elements, filter selects elements based on a condition, and reduce aggregates elements into a single value.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);  // [2, 4, 6, 8]
const evens = numbers.filter(n => n % 2 === 0);  // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0);  // 10

Recursion:

Recursion is a technique where a function calls itself to solve a smaller instance of the same problem, often used to solve problems that can be broken down into simpler, repetitive tasks.

function factorial(n) {
    if (n === 1) return 1;
    return n * factorial(n - 1);
}
console.log(factorial(5));  // Output: 120

Module Patterns:

The module pattern in JavaScript is used to encapsulate and organize code, often providing private and public access to methods and variables. This helps avoid polluting the global namespace and creates self-contained units of functionality.

const Module = (function() {
    const privateVar = "I am private";

    function privateMethod() {
        console.log(privateVar);
    }

    return {
        publicMethod: function() {
            privateMethod();
        }
    };
})();
Module.publicMethod();  // Output: I am private

Singleton Pattern:

The singleton pattern ensures that a class or object has only one instance throughout the application, providing a global point of access to it.

const Singleton = (function() {
    let instance;

    function createInstance() {
        return { name: "SingletonInstance" };
    }

    return {
        getInstance: function() {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();
const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2);  // Output: true

Observer Pattern:

The observer pattern is a design pattern in which an object (subject) maintains a list of dependents (observers) and notifies them of state changes, allowing for a publish-subscribe mechanism.

function Subject() {
    this.observers = [];
}
Subject.prototype = {
    subscribe: function(fn) {
        this.observers.push(fn);
    },
    unsubscribe: function(fn) {
        this.observers = this.observers.filter(subscriber => subscriber !== fn);
    },
    notify: function(data) {
        this.observers.forEach(observer => observer(data));
    }
};
const subject = new Subject();
const observer1 = data => console.log("Observer 1: " + data);
subject.subscribe(observer1);
subject.notify("Hello");  // Output: Observer 1: Hello

Memoization:

Memoization is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs occur again, reducing redundant computations.

function memoize(fn) {
    const cache = {};
    return function(...args) {
        const key = JSON.stringify(args);
        if (cache[key]) {
            return cache[key];
        }
        const result = fn(...args);
        cache[key] = result;
        return result;
    };
}
const factorial = memoize(function(n) {
    if (n === 1) return 1;
    return n * factorial(n - 1);
});
console.log(factorial(5));  // Output: 120 (calculated)
console.log(factorial(5));  // Output: 120 (cached)

These explanations and code snippets provide a quick overview of each concept and how they are used in JavaScript.