JavaScript

JavaScript is a versatile and widely-used programming language primarily used for web development. It empowers developers to enhance the interactivity and functionality of web pages by adding dynamic elements, manipulating HTML and CSS, and handling user events. JavaScript can be seamlessly integrated into both client-side and server-side environments, making it a crucial tool for creating robust and interactive web applications.

Module 1: JavaScript Basics

Introduction to JavaScript

JavaScript is a high-level, interpreted programming language that is mainly used as a scripting language for web pages. It allows you to make web pages interactive by creating functionality that executes on the client's computer, rather than on the server-side.

Variables and Data Types

JavaScript has various data types including Number, String, Boolean, Object, Null, and Undefined. The 'var' keyword is used to declare a variable, or 'let' and 'const' in modern JavaScript syntax. 'let' is for variables that will change, and 'const' is for variables that will not change.

let name = 'John';
const age = 30;
let isLearning = true;
let x = null;
let y;

Control Structures

Control structures in JavaScript include if-else statements, switch-case, and loops like for, while, do-while. They are used to perform different actions based on different conditions.

let num = 10;
if(num > 5) {
	console.log('Number is greater than 5');
} else {
	console.log('Number is less than or equal to 5');
}

Functions

A JavaScript function is a block of code designed to perform a particular task. It is executed when something invokes it.

function greet() {
	console.log('Hello, World!');
}
greet();

Module 2: JavaScript Objects and Arrays

JavaScript Objects

Objects in JavaScript, just as in many other programming languages, can be compared to objects in real life. An object is a standalone entity with properties and types. It is composed of key-value pairs.

let person = {
	firstName: 'John',
	lastName: 'Doe',
	age: 30
};
console.log(person.firstName);

JavaScript Arrays

An array is a special variable, which can hold more than one value at a time. JavaScript arrays are used to store multiple values in a single variable.

let fruits = ['Apple', 'Banana', 'Mango'];
console.log(fruits[0]);

Array Methods

JavaScript provides many functions that can be used with arrays. These functions include push, pop, shift, unshift, and many more.

let fruits = ['Apple', 'Banana'];
fruits.push('Mango');
console.log(fruits);

Module 3: JavaScript DOM Manipulation

What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of the documents and it can be manipulated with JavaScript so as to change the document structure, style, and content.

Selecting Elements

You can select HTML elements from the DOM with various methods including getElementById, getElementsByClassName, getElementsByTagName, querySelector and querySelectorAll.

let title = document.getElementById('title');
let listItems = document.getElementsByClassName('list-item');
let paragraphs = document.getElementsByTagName('p');

Changing Elements

After selecting elements, you can manipulate them. You can change the content of the element with innerHTML, change the style with style.property, and change attribute values with setAttribute method.

let title = document.getElementById('title');
title.innerHTML = 'New Title';
title.style.color = 'red';
title.setAttribute('name', 'titleName');

Module 4: JavaScript Events

JavaScript Events

JavaScript can be executed when an event occurs, like when a user clicks on an HTML element, moves the mouse, or submits a form. Functions or blocks of code can be set to run when specific events occur.

let button = document.getElementById('myButton');
button.addEventListener('click', function() {
	alert('Button clicked!');
});

Event Propagation: Bubbling and Capturing

In the bubbling phase, the event starts from the target element and 'bubbles up' to the root of the DOM tree. In the capturing phase, the event starts from the root and 'goes down' to the target element.

let parent = document.getElementById('parent');
let child = document.getElementById('child');

parent.addEventListener('click', function() {
	console.log('Parent clicked!');
}, false);

child.addEventListener('click', function(event) {
	event.stopPropagation();
	console.log('Child clicked!');
}, false);

Event Delegation

Event delegation is a technique in JavaScript where you delegate a parent element as the event listener for all of its children. This is useful when you have code that should run when an event on a particular element within a parent element is triggered.

let ul = document.querySelector('ul');
ul.addEventListener('click', function(event) {
	let target = event.target;
	alert(target.innerHTML);
});

Custom Events

Custom events are events initialized by the developer, not the user or the system. Custom events can be used to create more complex event handling systems in your applications.

let event = new CustomEvent('build', { detail: { color: 'blue' } });
document.addEventListener('build', function (e) {
	console.log('Custom event fired with color:', e.detail.color);
}, false);
document.dispatchEvent(event);

Module 5: Asynchronous JavaScript

Asynchronous Programming

JavaScript is single threaded. Asynchronous programming in JavaScript is a way of performing long-running tasks (like fetching data from a server) without blocking the main thread. JavaScript uses 'callbacks', 'promises', and 'async/await' for asynchronous operations.

Callbacks

A callback is a function passed as an argument to another function. This technique allows a function to call another function. Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed.

function greeting(name) {
	alert('Hello ' + name);
}
function processUserInput(callback) {
	let name = prompt('Please enter your name.');
	callback(name);
}
processUserInput(greeting);

Promises

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

let promise = new Promise(function(resolve, reject) {
	let value = true;
	if (value) {
		resolve('Value is true.');
	} else {
		reject('Value is false.');
	}
});
promise.then((message) => {
	console.log(message);
}).catch((message) => {
	console.log(message);
});

Async/Await

Async/await is a modern way of handling promises. It is non-blocking and makes asynchronous code look and behave a little more like synchronous code.

async function exampleFunction() {
	let response = await fetch('https://api.github.com/users');
	let users = await response.json();
	console.log(users);
}
exampleFunction();

Module 6: JavaScript and ES6

ES6 and Beyond

ES6, or ECMAScript 2015, introduced a major update to JavaScript with new features and ways of coding. It includes features like let/const, arrow functions, template strings, destructuring, default parameters and many more.

Arrow Functions

ES6 introduced arrow functions, which provide a concise way to write functions in JavaScript.

const add = (a, b) => a + b;
console.log(add(1, 2));

Classes

ES6 introduced a new set of keywords implementing classes. JavaScript classes are a template for creating objects. They encapsulate data with code.

class Rectangle {
	constructor(height, width) {
		this.height = height;
		this.width = width;
	}
	calcArea() {
		return this.height * this.width;
	}
}
const square = new Rectangle(5, 5);
console.log(square.calcArea());

Modules

Modules are an integral piece of any robust application's architecture and typically help in keeping the code for a project both clean and maintainable. A module is essentially a separate script that can be used in other JavaScript files using import/export statements.

// lib.js
export const pi = 3.1416;

// app.js
import { pi } from './lib';
console.log(pi);