[Go to site: main page, start]

0% found this document useful (0 votes)
13 views14 pages

JavaScript Complete Guide for Beginners

Uploaded by

spidertech1515
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)
13 views14 pages

JavaScript Complete Guide for Beginners

Uploaded by

spidertech1515
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

JavaScript: Complete Guide - Simple & Easy

1. Introduction to JavaScript
JavaScript is a programming language that makes websites interactive and
dynamic. It runs in your browser and lets you add behaviors to web pages like
responding to clicks, changing colors, or validating forms.
Think of it this way: - HTML = The skeleton (structure) - CSS = The clothes
(styling) - JavaScript = The muscles (behavior/interactivity)

2. Variables & Data Types


Variables
Variables are containers that store values. Think of them as labeled boxes where
you keep data.
var name = "John"; // Old way (avoid)
let age = 25; // Modern way - can be changed
const city = "Mumbai"; // Modern way - cannot be changed
Key Difference: - let & const are block-scoped (safer) - var is function-
scoped (can cause issues)

Data Types

Type Example What It Is


String "Hello" Text
Number 42 or 3.14 Numbers (integers & decimals)
Boolean true or false Yes or No
Array [1, 2, 3] List of values
Object {name: "John"} Collection of properties
Undefined undefined Variable declared but no value
Null null Intentionally no value

3. Operators
Arithmetic Operators
5 + 3; // 8 (Addition)
5 - 3; // 2 (Subtraction)
5 * 3; // 15 (Multiplication)
5 / 3; // 1.67 (Division)

1
5 % 3; // 2 (Remainder)
5 ** 2; // 25 (Exponentiation)

Comparison Operators (return true/false)


5 == 5; // true (equal value)
5 === "5"; // false (different type)
5 != 3; // true (not equal)
5 > 3; // true (greater than)
5 < 3; // false (less than)

Logical Operators
true && true; // true (AND - both must be true)
true || false; // true (OR - at least one true)
!true; // false (NOT - opposite)

4. Control Flow - Making Decisions


if/else Statement
if (age > 18) {
[Link]("You are an adult");
} else if (age > 13) {
[Link]("You are a teenager");
} else {
[Link]("You are a child");
}

switch Statement
let day = 3;
switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Unknown day");
}

Ternary Operator (shortcut if/else)


let status = age > 18 ? "Adult" : "Minor";

2
5. Loops - Repeating Actions
for Loop
for (let i = 0; i < 5; i++) {
[Link](i); // prints 0, 1, 2, 3, 4
}

while Loop
let i = 0;
while (i < 5) {
[Link](i);
i++;
}

for…of Loop (for lists)


let fruits = ["Apple", "Banana", "Orange"];
for (let fruit of fruits) {
[Link](fruit); // prints each fruit
}

Loop Control
break; // Exit the loop completely
continue; // Skip current iteration, go to next

6. Functions - Reusable Code


A function is a block of code that does a specific task. You can call it multiple
times.

Function Declaration
function greet(name) {
return "Hello, " + name;
}

[Link](greet("Alice")); // "Hello, Alice"

Arrow Functions (Modern Way)


const add = (a, b) => a + b;
[Link](add(3, 5)); // 8

3
// Single parameter (parentheses optional)
const square = x => x * x;

// Multiple lines (need curly braces & return)


const multiply = (x, y) => {
[Link]("Multiplying...");
return x * y;
};

Parameters & Arguments


function introduce(name = "Guest") { // Default parameter
[Link](`Hello ${name}`);
}

introduce(); // "Hello Guest"


introduce("Rahul"); // "Hello Rahul"

7. Scope - Variable Visibility


Scope = Where a variable can be accessed.

Global Scope
let global = "I'm global";

function test() {
[Link](global); // � Can access
}

test();
[Link](global); // � Can access

Local Scope
function myFunction() {
let local = "I'm local";
[Link](local); // � Can access
}

myFunction();
[Link](local); // � Error! Cannot access

4
Block Scope (let & const only)
if (true) {
let x = 5;
const y = 10;
}

[Link](x); // � Error
[Link](y); // � Error

8. Closures
A closure is a function that has access to variables from another function’s
scope. A function inside another function.
function outer() {
let count = 0; // outer variable

function inner() {
count++; // inner can access outer's variable
return count;
}

return inner;
}

const counter = outer();


[Link](counter()); // 1
[Link](counter()); // 2
[Link](counter()); // 3
Why useful? Creates private variables that can’t be accessed directly from
outside.

9. Arrays - Lists of Data


let fruits = ["Apple", "Banana", "Orange"];

// Access elements
[Link](fruits[0]); // "Apple"
[Link]([Link]); // 3

// Add elements
[Link]("Mango"); // Add at end

5
[Link]("Kiwi"); // Add at start

// Remove elements
[Link](); // Remove from end
[Link](); // Remove from start

// Loop through array


[Link](fruit => [Link](fruit));

// Transform array
let upperFruits = [Link](fruit => [Link]());

// Filter array
let longNames = [Link](fruit => [Link] > 5);

// Find single element


let found = [Link](fruit => fruit === "Apple");

10. Objects - Groups of Data


An object stores related data as key-value pairs.
let person = {
name: "Rahul",
age: 25,
city: "Delhi",
greet: function() {
return "Hello, I'm " + [Link];
}
};

// Access properties
[Link]([Link]); // "Rahul"
[Link](person["age"]); // 25

// Call method
[Link]([Link]()); // "Hello, I'm Rahul"

// Add new property


[Link] = "rahul@[Link]";

// Delete property
delete [Link];

6
11. Hoisting - Declaration Moving
JavaScript automatically moves declarations to the top of their scope before
execution.

Function Hoisting
sayHi(); // � Works! Function is hoisted

function sayHi() {
[Link]("Hello!");
}

Variable Hoisting
[Link](x); // undefined (hoisted but not initialized)
var x = 5;
[Link](x); // 5

// With let/const
[Link](y); // � Error (temporal dead zone)
let y = 5;
Key Point: Only declarations are hoisted, not assignments.

12. Callbacks - Functions as Arguments


A callback is a function passed as an argument to another function.
function greet(name, callback) {
[Link]("Hello " + name);
callback();
}

function sayGoodbye() {
[Link]("Goodbye!");
}

greet("Alice", sayGoodbye);
// Output:
// Hello Alice
// Goodbye!

7
13. Promises - Future Values
A Promise handles asynchronous operations (like fetching data from server).
Three states: - Pending: Operation is happening - Fulfilled: Operation suc-
ceeded - Rejected: Operation failed
const myPromise = new Promise((resolve, reject) => {
let success = true;

if (success) {
resolve("Operation successful!"); // Success
} else {
reject("Operation failed!"); // Failure
}
});

// Handle the result


myPromise
.then(result => [Link](result)) // If fulfilled
.catch(error => [Link](error)); // If rejected

14. Async/Await - Cleaner Promises


Easier way to work with promises (looks like synchronous code).
async function fetchData() {
try {
const response = await fetch("[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link]("Error:", error);
}
}

fetchData();
Why simpler? No .then() chains needed. Code looks like normal syn-
chronous code.

15. DOM - Controlling HTML


The DOM (Document Object Model) is your HTML page in JavaScript. You
can select and modify elements.

8
Select Elements
// By ID
let element = [Link]("myId");

// By class name
let elements = [Link]("myClass");

// Modern way (recommended)


let div = [Link](".myClass");
let allDivs = [Link](".myClass");

Modify Elements
let div = [Link]("#content");

// Change text
[Link] = "New text";
[Link] = "<h1>New HTML</h1>";

// Change styles
[Link] = "red";
[Link] = "20px";

// Add/remove classes
[Link]("active");
[Link]("inactive");

Create & Add Elements


let newDiv = [Link]("div");
[Link] = "I'm new!";
[Link](newDiv);

16. Events - User Interactions


Events are things users do: clicking, typing, scrolling, etc.
let button = [Link]("button");

// Listen for click event


[Link]("click", function() {
[Link]("Button clicked!");
});

// Common events

9
[Link]("mouseover", handleMouseOver);
[Link]("mouseout", handleMouseOut);
[Link]("change", handleChange); // input changed
[Link]("submit", handleSubmit); // form submitted

Event Object
[Link]("click", function(event) {
[Link](); // Stop default behavior
[Link](); // Stop event bubbling
[Link]([Link]); // Which element triggered it?
});

17. String Methods


let text = "JavaScript";

[Link]; // 10
[Link](); // "JAVASCRIPT"
[Link](); // "javascript"
[Link](0); // "J"
[Link]("Script"); // 4
[Link](0, 4); // "Java"
[Link]("Script"); // true
[Link](""); // ["J", "a", "v", ...]
[Link](); // Remove whitespace
[Link]("Java", "Type"); // "TypeScript"

18. Number Methods


let num = 3.14159;

[Link](num); // 3
[Link](num); // 4
[Link](num); // 3
[Link](-5); // 5
[Link](1, 5, 3); // 5
[Link](1, 5, 3); // 1
[Link](); // Random number 0-1
[Link](2, 3); // 8 (2³)
[Link](16); // 4

10
19. Object Methods
let person = {
name: "Rahul",
age: 25,
city: "Delhi"
};

// Get all keys


[Link](person); // ["name", "age", "city"]

// Get all values


[Link](person); // ["Rahul", 25, "Delhi"]

// Get key-value pairs


[Link](person); // [["name", "Rahul"], ["age", 25], ...]

// Copy object
let copy = [Link]({}, person);
let copy2 = {...person}; // Spread operator

20. Template Literals - Easy String Interpolation


let name = "Rahul";
let age = 25;

// Old way
let message = "Hello, " + name + "! You are " + age + " years old.";

// New way (backticks)


let message = `Hello, ${name}! You are ${age} years old.`;

// Multi-line strings
let poem = `
Roses are red
Violets are blue
JavaScript is fun
And useful too
`;

11
21. Destructuring - Extract Values Easily
// Array destructuring
let [a, b, c] = [1, 2, 3];
[Link](a); // 1

// Object destructuring
let {name, age} = {name: "Rahul", age: 25};
[Link](name); // "Rahul"

// With defaults
let {name = "Guest", country = "India"} = {name: "Rahul"};

22. Spread Operator (…)


// Copy array
let arr1 = [1, 2, 3];
let arr2 = [...arr1];

// Combine arrays
let combined = [0, ...arr1, 4]; // [0, 1, 2, 3, 4]

// Copy object
let obj1 = {a: 1, b: 2};
let obj2 = {...obj1};

// Function arguments
function sum(a, b, c) {
return a + b + c;
}
let numbers = [1, 2, 3];
[Link](sum(...numbers)); // 6

23. Try/Catch - Handle Errors


try {
// Code that might have an error
let result = riskyFunction();
} catch (error) {
// Code runs if error happens
[Link]("Error occurred:", [Link]);
} finally {
// Code runs regardless (optional)

12
[Link]("Cleanup done");
}

24. Local Storage - Save Data in Browser


// Save data
[Link]("username", "Rahul");

// Get data
let username = [Link]("username"); // "Rahul"

// Delete data
[Link]("username");

// Clear all
[Link]();

// Save object (convert to JSON first)


let person = {name: "Rahul", age: 25};
[Link]("person", [Link](person));

// Retrieve object
let retrieved = [Link]([Link]("person"));

25. JSON - Data Format


JSON = JavaScript Object Notation (lightweight data format)
// Convert object to JSON string
let person = {name: "Rahul", age: 25};
let jsonString = [Link](person);
// Result: '{"name":"Rahul","age":25}'

// Convert JSON string to object


let jsonString = '{"name":"Rahul","age":25}';
let person = [Link](jsonString);
[Link]([Link]); // "Rahul"

Quick Comparison Table

13
Feature var let const
Scope Function Block Block
Hoisting Hoisted, undefined Hoisted, error Hoisted, error
Re-declare � Yes � No � No
Update � Yes � Yes � No
Best For (Avoid) Variables that change Constants

Tips for Learning JavaScript


1. Practice Often: Write code every day, even small scripts
2. Read Code: Look at others’ code to learn patterns
3. Understand Why: Don’t just memorize, understand concepts
4. Build Projects: Make real things - to-do apps, calculators, etc.
5. Debug: Use [Link]() to see what’s happening
6. Read Errors: Error messages tell you what’s wrong
7. Ask Questions: Use MDN Web Docs when confused
8. Be Patient: JavaScript takes time to master, that’s normal!

Resources for More Learning


• MDN Web Docs: Official documentation
• Wes Bos’ Beginner JavaScript: Free video course
• [Link]: Interactive tutorials
• GeeksforGeeks JavaScript: Detailed articles
• Practice on: Codewars, LeetCode, HackerRank

Remember: The best way to learn JavaScript is by writing code and building
projects. Start small, understand concepts deeply, and gradually build complex-
ity. Happy coding! �

14

You might also like