JavaScript
1: JavaScript Basics
1. Introduction to JavaScript
JavaScript is a high-level, interpreted scripting language primarily used for enhancing the
interactivity of web pages. It runs in the browser and allows dynamic content updates,
form validations, animations, and much more.
It is also widely used on the backend using [Link].
Embedding JS in HTML:
<script>
[Link]("Hello, JavaScript!");
</script>
2. Variables and Data Types:
What are Variables?
A variable is a named container used to store data (values) that your program can use
and manipulate later.
Think of it like a box with a label on it—you can put something inside, change it, or read
what's inside.
JavaScript variables can be declared using var, let, or const. unlike other programming
languages those using datatype like int, String, char etc. to declare a variable.
- var: function-scoped (old, avoid using)
- let: block-scoped, reassignable
- const: block-scoped, cannot be reassigned
in modern JavaScript, we mostly use let and const instead of var. This shift happened
because let and const are more predictable, safer, and block-scoped compared to var.
Primitive and Non-Primitive Data Types:
Type Conversion:
3. Operators
Arithmetic Operators: +, -, *, /, %, **
Assignment: =, +=, -=, etc.
Comparison: ==, ===, !=, !==, >, <
Logical: && (and), || (or), ! (not)
Ternary Operator Example:
let age = 18;
let result = (age >= 18) ? "Adult" : "Minor";
4. Control Flow
Use `if`, `else if`, and `else` to control flow.
Switch case is used to handle multiple conditions.
Example:
switch(day) {
case "Monday":
[Link]("Start of the week");
break;
default:
[Link]("Another day");
}
5. Loops
JavaScript provides several loops:
- for
- while
- do...while
Use break to exit a loop and continue to skip current iteration.
6. Functions
Functions can be declared in different ways:
- Function Declaration
- Function Expression
- Arrow Functions
Example:
function add(a, b) {
return a + b;
}
const square = (n) => n * n;
2: Intermediate Core Concepts
7. Arrays
Arrays are ordered lists of data. Each item has an index, starting from 0.
Common methods include:
- push: adds to end
- pop: removes from end
- shift: removes from start
- unshift: adds to start
- splice: removes or adds at a specific index
- slice: extracts part of an array
Example:
let fruits = ['apple', 'banana'];
[Link]('mango');
8. Objects
Objects hold key-value pairs and can contain methods as well.
Use dot (.) or bracket ([]) notation to access properties.
Example:
let user = {
name: "Vishal",
age: 24,
greet: function() {
return `Hello, ${[Link]}`;
}
};
9. DOM Manipulation*
Understanding the DOM (Document Object Model)
🔸 What is the DOM?
The DOM is a tree-like structure created by the browser when it loads an HTML
page.
It represents all HTML elements as JavaScript objects which can be accessed,
modified, and manipulated using JavaScript.
This is what enables JavaScript to make web pages dynamic and interactive.
🔸 Why is DOM important in JavaScript?
It forms the bridge between HTML and JavaScript.
Without the DOM, JavaScript wouldn't be able to "see" or "control" your web page.
DOM enables JavaScript to:
o Change text or styles
o Add, remove, or modify HTML elements
o Handle user input via events (click, submit, hover, etc.)
DOM (Document Object Model) allows JavaScript to interact with HTML elements.
Selection Methods: getElementById, querySelector, querySelectorAll
Change content with innerText or innerHTML. Change style using .style property.
So, in Summary most commonly used DOM (Document Object
Model) manipulation methods in JavaScript:
Element Selection Methods
Method Description
getElementById() Selects a single element by its ID.
getElementsByClassName() Selects all elements with a specific class (HTMLCollection).
getElementsByTagName() Selects all elements with a specific tag (HTMLCollection).
querySelector() Returns the first element matching a CSS selector.
querySelectorAll() Returns all elements matching a CSS selector (NodeList).
Element Manipulation Methods
Method Use
[Link] Read/Write HTML inside an element.
Includes hidden text, ignores CSS styles and returns
[Link]
line breaks as-is.
Respects CSS styling (e.g. display:none,
[Link]
visibility:hidden). Slower than textContent.
[Link](name, value) Add/modify attribute on an element.
[Link](name) Get attribute value.
[Link](name) Remove attribute.
Method Use
[Link] Directly change inline CSS.
[Link]() Add CSS class.
[Link]() Remove CSS class.
[Link]() Toggle class on/off.
[Link]() Check if a class exists.
Creating & Inserting Elements
Method Description
[Link](tag) Create a new element.
[Link](text) Create a text node.
[Link](child) Add child at the end.
[Link](child) Add child at the very beginning.
[Link](newNode, existingNode) Insert before a specific node.
[Link](newElement) Replace element entirely.
[Link]() Delete an element from DOM.
10. Event Handling:
Code Example (Adding interactivity to web page using DOM
manipulation and Event Handling in JS):
3: Functional & Modern JS
11. ES6+ Features
Modern JavaScript (ES6+) introduced many useful features:
- let and const
- Default Parameters: function greet(name = 'Guest') {}
- Template Literals: `Hello, ${name}`
-Arrow functions
- Destructuring: const {name} = obj
- Spread Operator: [...arr]
- Rest Parameters: function (...args) {}
- Array methods:
- map and set
-Promises
-Async Await
12. Higher-Order Functions & Callbacks
Functions that accept other functions as parameters or return functions are called Higher-
Order Functions.
Common ones include: map, filter, reduce.
Callback functions are used especially in asynchronous operations.
Example:
let nums = [1, 2, 3];
let squared = [Link](n => n * n);
13. Scope and Closures
Scope defines the accessibility of variables. JavaScript has function and block scopes.
Closures are functions that remember variables from their parent scopes.
Example:
function outer() {
let count = 0;
return function inner() {
count++;
return count;
};
}
let counter = outer();
14. Asynchronous JavaScript
JavaScript handles async tasks using:
- setTimeout/setInterval: Timer-based execution
-callbacks (Traditional way)
- Promises: Represent future values
- async/await: Simplified way to handle promises
Example:
async function fetchData() {
let res = await fetch('[Link]
let data = await [Link]();
[Link](data);
}
Bonus: Mini Projects for Practice
1. To-Do List – Add/delete tasks using input field and button. Store in array or DOM.
2. Calculator – Buttons for digits and operations. Display results.
3. Form Validation – Use DOM to validate input fields on submit.
4. Digital Clock – Use Date object and setInterval to update time every second.
5. Weather App – Use fetch API to call real-time weather data and show on page.