Basics
1.1. Introduction
JavaScript: A scripting language that runs in web browsers and on servers (with Node.js). It's
essential for adding interactivity to web pages.
1.2. Syntax
Comments: // Single line, /* Multi-line */
Variables: Declared using var, let, or const.
let name = "John"; // 'let' for mutable variables
const age = 30; // 'const' for immutable variables
1.3. Data Types
Primitive Types: number, string, boolean, undefined, null, symbol, bigint.
Non-Primitive Types: object, array, function.
let number = 42; // Number
let text = "Hello"; // String
let isTrue = true; // Boolean
let nothing = null; // Null
let undefinedVar; // Undefined
let bigNumber = 12345678901234567890n; // BigInt
1.4. Operators
Arithmetic: +, -, *, /, %
Comparison: ==, ===, !=, !==, >, <, >=, <=
Logical: &&, ||, !
let result = 10 + 5; // 15
let isEqual = (5 === 5); // true
let isTrue = (true || false); // true
2. Control Structures
2.1. Conditional Statements
if: Used for conditional execution.
if (age > 18) {
console.log("Adult");
} else {
console.log("Not an Adult");
switch: Used for multiple conditions.
switch (day) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
// more cases
default:
console.log("Invalid day");
2.2. Loops
for: Standard loop.
for (let i = 0; i < 5; i++) {
console.log(i);
while: Loop while condition is true.
let i = 0;
while (i < 5) {
console.log(i);
i++;
do...while: Loop with post-test condition.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
3. Functions
3.1. Function Declaration
function greet(name) {
return `Hello, ${name}!`;
console.log(greet("Alice")); // Hello, Alice!
3.2. Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("Bob")); // Hello, Bob!
3.3. Arrow Functions
const greet = name => `Hello, ${name}!`;
console.log(greet("Charlie")); // Hello, Charlie!
3.4. Parameters and Arguments
function sum(a, b = 5) {
return a + b;
console.log(sum(3)); // 8
4. Objects
4.1. Object Literal
let person = {
name: "John",
age: 30,
greet() {
return `Hello, ${this.name}`;
};
console.log(person.greet()); // Hello, John
4.2. Constructor Functions
function Person(name, age) {
this.name = name;
this.age = age;
let john = new Person("John", 30);
console.log(john.name); // John
4.3. Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
greet() {
return `Hello, ${this.name}`;
let john = new Person("John", 30);
console.log(john.greet()); // Hello, John
5. Arrays
5.1. Array Creation
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // banana
5.2. Array Methods
fruits.push("date"); // Add to end
fruits.pop(); // Remove from end
fruits.shift(); // Remove from start
fruits.unshift("fig"); // Add to start
console.log(fruits.join(", ")); // fig, banana, cherry
6. DOM Manipulation
6.1. Selecting Elements
let element = document.getElementById("myId");
let elements = document.getElementsByClassName("myClass");
let queryElement = document.querySelector(".myClass");
let queryAllElements = document.querySelectorAll(".myClass");
6.2. Modifying Elements
element.innerHTML = "New Content";
element.style.color = "red";
6.3. Event Handling
element.addEventListener("click", function() {
alert("Element clicked!");
});
7. Asynchronous JavaScript
7.1. Callbacks
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
fetchData(data => console.log(data)); // Data fetched
7.2. Promises
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
promise.then(data => console.log(data)); // Data fetched
7.3. Async/Await
async function fetchData() {
let response = await new Promise((resolve) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
console.log(response);
}
fetchData(); // Data fetched
8. Error Handling
8.1. Try/Catch
try {
let result = riskyOperation();
} catch (error) {
console.error("Error occurred:", error);
9. Modules
9.1. Export/Import
Exporting:
// math.js
export function add(a, b) {
return a + b;
Importing:
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
10. Advanced Topics
10.1. Closures
function makeCounter() {
let count = 0;
return function() {
count += 1;
return count;
};
let counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
10.2. Prototypes
function Person(name) {
this.name = name;
Person.prototype.greet = function() {
return `Hello, ${this.name}`;
};
let john = new Person("John");
console.log(john.greet()); // Hello, John
10.3. Event Loop and Concurrency
Call Stack: Executes code line by line.
Task Queue: Holds asynchronous tasks.
Event Loop: Moves tasks from the queue to the call stack.
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
Output:
Start
End
Timeout
11. Web APIs
11.1. Fetch API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
11.2. Local Storage
localStorage.setItem('key', 'value');
let value = localStorage.getItem('key');
console.log(value); // value
11.3. Session Storage
sessionStorage.setItem('key', 'value');
let value = sessionStorage.getItem('key');
console.log(value); // value
12. Testing and Debugging
12.1. Debugging Tools
Browser Developer Tools: Inspect, debug, and profile code.
console.log(): Print messages for debugging.
12.2. Testing Frameworks
Jest: Testing framework with built-in assertion library.
Mocha: Test framework with various assertion libraries.
// Jest Example
test('adds 1 + 2 to equal 3', () => {
expect(1 + 2).toBe(3);
});