0% found this document useful (0 votes)
16 views7 pages

Maths

The document is a comprehensive guide to JavaScript, covering its fundamentals from basic syntax to advanced concepts like asynchronous programming and design patterns. It includes sections on setting up JavaScript, variables, data types, control flow, functions, objects, event handling, and more. The guide is structured to help beginners progress to advanced users with practical examples and explanations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views7 pages

Maths

The document is a comprehensive guide to JavaScript, covering its fundamentals from basic syntax to advanced concepts like asynchronous programming and design patterns. It includes sections on setting up JavaScript, variables, data types, control flow, functions, objects, event handling, and more. The guide is structured to help beginners progress to advanced users with practical examples and explanations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Complete JavaScript Guide: Beginner to Advanced

Introduction to JavaScript
JavaScript is a high-level, dynamically typed programming language widely used for web
development. It enables interactive web pages and is an essential technology alongside HTML and
CSS. JavaScript can be executed in web browsers and server-side environments like Node.js.

Setting Up JavaScript
To write JavaScript, you can use:

1. **Browser Console** (F12 in Chrome, Firefox, Edge)


2. **Script Tag in HTML** (`<script>console.log('Hello');</script>`)
3. **External JavaScript File** (`script.js` linked with `<script src='script.js'></script>`)
4. **Node.js Runtime** (`node script.js` in terminal)

Variables and Data Types

// Declaring variables
var globalVar = "I am global"; // Function-scoped
let blockVar = "I am block-scoped"; // Block-scoped
const constantVar = "Cannot change"; // Constant value

// Primitive Data Types


let num = 42; // Number
let text = "Hello"; // String
let isTrue = true; // Boolean
let nothing = null; // Null
let notDefined; // Undefined
let uniqueId = Symbol("id"); // Symbol

// Complex Data Types


let array = [1, 2, 3]; // Array
let object = {name: "Alice", age: 25}; // Object
Operators in JavaScript

// Arithmetic Operators
let sum = 10 + 5;
let product = 10 * 5;

// Comparison Operators
console.log(5 == "5"); // true (loose equality)
console.log(5 === "5"); // false (strict equality)

// Logical Operators
console.log(true && false); // false
console.log(true || false); // true
console.log(!true); // false

Control Flow: Conditional Statements

// If-Else Statement
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}

// Ternary Operator
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message);

// Switch Case
let fruit = "banana";
switch (fruit) {
case "apple":
console.log("It's an apple!");
break;
case "banana":
console.log("It's a banana!");
break;
default:
console.log("Unknown fruit");
}

Loops: For, While, Do-While

// For Loop
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i);
}

// While Loop
let count = 0;
while (count < 3) {
console.log("Count:", count);
count++;
}

// Do-While Loop
let num = 0;
do {
console.log("Number:", num);
num++;
} while (num < 3);

Functions: Declaring and Calling

// Function Declaration
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));

// Function Expression
const add = function(a, b) {
return a + b;
};
console.log(add(4, 5));

// Arrow Function
const multiply = (a, b) => a * b;
console.log(multiply(3, 5));

JavaScript Objects and Prototypes

// Object Creation
let person = {
name: "Alice",
age: 22,
greet: function() {
return "Hello, " + this.name;
}
};
console.log(person.greet());

// Adding Properties
person.city = "New York";
console.log(person.city);

// Prototype Example
function Car(model, year) {
this.model = model;
this.year = year;
}

Car.prototype.getCarInfo = function() {
return `${this.model}, ${this.year}`;
};

let car1 = new Car("Toyota", 2022);


console.log(car1.getCarInfo());

Asynchronous JavaScript

// setTimeout Example
setTimeout(() => console.log("Executed after 2 seconds"), 2000);

// Fetch API Example


fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data));

// Async-Await Example
async function fetchData() {
let response = await fetch("https://jsonplaceholder.typicode.com/users");
let users = await response.json();
console.log(users);
}
fetchData();

Advanced Concepts: Closures

// Closure Example
function outerFunction(outerVar) {
return function innerFunction(innerVar) {
return `Outer: ${outerVar}, Inner: ${innerVar}`;
};
}

const newFunc = outerFunction("Hello");


console.log(newFunc("World")); // "Outer: Hello, Inner: World"

Event Handling and the DOM

// Selecting an Element
let button = document.getElementById("btn");

// Adding an Event Listener


button.addEventListener("click", function() {
alert("Button clicked!");
});

// Changing DOM Elements


document.getElementById("title").innerHTML = "New Title";

JavaScript Design Patterns

// Singleton Pattern
const Singleton = (function() {
let instance;
function createInstance() {
return { message: "I am the only instance" };
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
console.log(Singleton.getInstance());

// Observer Pattern
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}

class Observer {
update(data) {
console.log("Observer received:", data);
}
}

const subject = new Subject();


const observer1 = new Observer();
subject.subscribe(observer1);
subject.notify("New Event!");

You might also like