javascript_basics_to_advanced
javascript_basics_to_advanced
Introduction to JavaScript
JavaScript is a lightweight, interpreted programming language used to create dynamic and
interactive web pages.
Basic Syntax
// Variables
let name = "John";
const age = 25;
// Data Types
let number = 10; // Number
let text = "Hello"; // String
let isTrue = true; // Boolean
// If-Else
if (age > 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Scope
let globalVar = "I am global";
function testScope() {
let localVar = "I am local";
console.log(globalVar); // Accessible
console.log(localVar); // Accessible
}
testScope();
// Arrays
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[1]); // Banana
// Objects
let person = {name: "Alice", age: 22};
console.log(person.name); // Alice
DOM Manipulation
ES6 Features
// Arrow Functions
const add = (a, b) => a + b;
console.log(add(5, 3)); // 8
// Template Literals
let name = "John";
console.log(`Hello, ${name}!`);
// Destructuring
let person = {name: "Alice", age: 22};
let {name, age} = person;
console.log(name, age);
Asynchronous JavaScript
// Callbacks
function fetchData(callback) {
setTimeout(() => callback("Data fetched"), 2000);
}
fetchData(console.log);
// Promises
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise resolved"), 2000);
});
promise.then(console.log);
// Async/Await
async function fetchAsyncData() {
let result = await promise;
console.log(result);
}
fetchAsyncData();
Error Handling
// Try-Catch
try {
let x = y + 1; // y is not defined
} catch (error) {
console.log("Error:", error.message);
}
// Exporting a function
export function greet(name) {
return `Hello, ${name}`;
}
Advanced Concepts
// Closures
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
};
}
let add5 = outerFunction(5);
console.log(add5(3)); // 8
// Prototypes
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
console.log("Hello, " + this.name);
};
let person1 = new Person("Alice");
person1.sayHello(); // Hello, Alice
// Fetch API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
Frameworks Overview
// React Example
function App() {
return <h1>Hello, React!</h1>;
}