javascript

JavaScript Complete Tutorial โ€“ Simple Explanations & Examples | Esikhcha

๐ŸŸจ JavaScript Complete Tutorial

Big simple explanations ยท Clear syntax ยท Real code examples

๐Ÿ“– Basics & Syntax ๐Ÿ“ฆ Variables & Types โš™๏ธ Operators ๐Ÿ”„ If/Else & Loops ๐Ÿ“ Strings & Numbers ๐ŸŽฏ Functions & Objects
CHAPTER 1

What is JavaScript?

๐ŸŽฏ Big Simple Explanation: JavaScript is the programming language that makes websites come alive!

When you see animated menus, popup messages, interactive forms, or content that changes without reloading โ€” that’s JavaScript at work. HTML gives structure, CSS gives style, and JavaScript gives BEHAVIOR.

Key Facts about JavaScript:

  • Created in 1995 by Brendan Eich at Netscape
  • Runs directly in your web browser (no installation needed)
  • Also runs on servers using Node.js
  • One of the most popular programming languages in the world
  • Essential for front-end web development
๐Ÿ’ก JavaScript has nothing to do with Java โ€” they are completely different languages!
CHAPTER 2

Where To Put JavaScript

๐Ÿ“Œ Big Simple Explanation: You can write JavaScript in three places: inside HTML tags, inside a <script> tag, or in a separate .js file (best practice).

Method 1: Inline (inside HTML element)

Inline Example
<button onclick="alert('Clicked!')">Click Me</button>

Method 2: Internal (inside <script> tag)

Internal Script
<!DOCTYPE html>
<html>
<head>
  <script>
    function showMessage() {
      alert('Hello from internal script!');
    }
  </script>
</head>
<body>
  <button onclick="showMessage()">Click</button>
</body>
</html>

Method 3: External (separate .js file – BEST PRACTICE)

// script.js file
console.log('Hello from external file');
HTML Linking External File
<script src="script.js"></script>
โœ… Best Practice: Put scripts at the bottom of the body for faster page loading, or use defer attribute.
CHAPTER 3

JavaScript Output Methods

๐Ÿ–จ๏ธ Big Simple Explanation: JavaScript has 4 main ways to show output, each useful in different situations.

MethodDescriptionExample
console.log()Shows in browser’s developer consoleconsole.log("Debug message");
alert()Shows a popup alert boxalert("Warning!");
document.write()Writes directly to HTML pagedocument.write("Hello");
innerHTMLChanges content of an HTML elementelement.innerHTML = "New text";
Output Examples
// Console output (for debugging)
console.log("This appears in the console (F12)");

// Alert popup
alert("Hello! This is an alert box.");

// Writing to page
document.write("This text appears on the page");

// Changing HTML element
document.getElementById("demo").innerHTML = "Content changed!";
๐Ÿ” Tip: Press F12 in your browser to open Developer Tools and see console.log output!
CHAPTER 4

JS Syntax & Statements

๐Ÿ“ Big Simple Explanation: JavaScript syntax is the set of rules for writing correct JS code. Think of it like grammar rules for a language!

๐Ÿ“Œ Basic Rules:
// Statements end with semicolon (optional but recommended)
let x = 10;
let y = 20;

// JavaScript is case-sensitive (myVar โ‰  myvar)
let myVar = 5;
let myvar = 10;  // Different variable!

// Comments use // or /* */
// This is a single line comment
/* This is a 
   multi-line comment */

// Whitespace is ignored (you can add spaces for readability)
Syntax Examples
// Multiple statements in one line (not recommended for readability)
let a = 1; let b = 2; let c = a + b;

// Code blocks
if (true) {
    console.log("Inside a code block");
}

// Values can be literal
console.log("Hello");  // String literal
console.log(42);       // Number literal
console.log(true);     // Boolean literal
CHAPTER 5

Comments

๐Ÿ’ฌ Big Simple Explanation: Comments are text that JavaScript ignores. They help you explain your code to yourself and others!

Comments Examples
// Single-line comment - anything after // is ignored

/* 
   Multi-line comment
   Everything between /* and *\/ is ignored
   Great for longer explanations
*/

/* 
 * This is a documentation style comment
 * Often used to describe functions
 * @param {number} a - First number
 * @returns {number} Sum
 */
function add(a, b) {
    return a + b;
}

// You can also comment out code to temporarily disable it
// console.log("This won't run");
๐Ÿ’ก Good comments explain WHY, not WHAT. The code already shows WHAT!
CHAPTER 6

Variables: var, let, const

๐Ÿ“ฆ Big Simple Explanation: Variables are containers for storing data values. Think of them as labeled boxes where you keep information.

KeywordScopeCan Reassign?Can Redeclare?Best Practice
varFunction scopeโœ… Yesโœ… YesAvoid in modern JS (old way)
letBlock scope {}โœ… YesโŒ NoUse when value changes
constBlock scope {}โŒ NoโŒ NoUse for values that never change
Variable Examples
// Using let (mutable - can change)
let age = 25;
console.log(age);  // 25
age = 26;          // โœ… Allowed - value changes
console.log(age);  // 26

// Using const (immutable - cannot change)
const birthYear = 1995;
console.log(birthYear);  // 1995
// birthYear = 1996;     // โŒ Error - const cannot be reassigned

// Variable naming rules
let firstName = "John";      // camelCase (recommended)
let last_name = "Doe";       // snake_case (valid but less common)
let $price = 19.99;          // $ allowed
let _hidden = true;          // _ allowed
// let 1stName = "Error";     // โŒ Cannot start with number

// Declaring multiple variables
let x = 5, y = 10, z = 15;

// Variables without value are undefined
let emptyVar;
console.log(emptyVar);  // undefined
โœ… Golden Rule: Use const by default. Only use let when you know the value will change. Never use var in modern JavaScript!
CHAPTER 7

Data Types in JavaScript

๐Ÿท๏ธ Big Simple Explanation: Data types tell JavaScript what kind of value you’re storing. There are 8 basic data types in JavaScript.

TypeDescriptionExampletypeof Output
StringText value"Hello World""string"
NumberInteger or decimal42, 3.14"number"
BooleanTrue or falsetrue, false"boolean"
UndefinedVariable declared, not assignedlet x;"undefined"
NullIntentional empty valuelet y = null;"object"
BigIntVery large integers9007199254740991n"bigint"
SymbolUnique identifierSymbol('id')"symbol"
ObjectCollection of data{name: "John"}"object"
Data Type Examples
// Strings (use quotes)
let name = "Alice";
let message = 'Hello';
let template = `My name is ${name}`;  // Template literal

// Numbers (no quotes)
let integer = 42;
let decimal = 3.14159;
let negative = -10;
let bigNumber = 1_000_000;  // Underscore for readability

// Booleans
let isLoggedIn = true;
let isGreater = 10 > 5;  // true

// Undefined
let notAssigned;
console.log(notAssigned);  // undefined

// Null (intentionally empty)
let empty = null;

// Check type with typeof
console.log(typeof "Hello");   // "string"
console.log(typeof 42);        // "number"
console.log(typeof true);      // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null);      // "object" (JavaScript bug!)
CHAPTER 8

JavaScript Operators

๐Ÿงฎ Big Simple Explanation: Operators are symbols that perform operations on values. They’re like the verbs of JavaScript!

Arithmetic Operators

OperatorMeaningExampleResult
+Addition10 + 515
Subtraction10 – 55
*Multiplication10 * 550
/Division10 / 52
%Modulus (Remainder)10 % 31
**Exponentiation2 ** 38
++Incrementlet x=5; x++6
Decrementlet x=5; x–4

Comparison Operators

OperatorMeaningExampleResult
==Equal value5 == “5”true
===Equal value & type5 === “5”false
!=Not equal value5 != “5”false
!==Not equal value/type5 !== “5”true
>Greater than10 > 5true
<Less than10 < 5false
>=Greater than or equal10 >= 10true
<=Less than or equal10 <= 9false
Operator Examples
// Arithmetic
let sum = 10 + 5;        // 15
let difference = 20 - 8; // 12
let product = 7 * 6;     // 42
let quotient = 15 / 3;   // 5
let remainder = 17 % 5;  // 2
let power = 2 ** 4;      // 16

// Comparison (return true/false)
console.log(5 == "5");    // true (value same, type ignored)
console.log(5 === "5");   // false (type different)
console.log(10 > 5);      // true
console.log(3 <= 3);      // true

// Logical Operators
let and = (5 > 3 && 10 > 2);   // true (both true)
let or = (5 > 10 || 3 < 5);    // true (one true)
let not = !(5 > 3);            // false (inverts)

// Assignment Operators
let x = 10;
x += 5;   // x = x + 5 = 15
x -= 3;   // x = x - 3 = 12
x *= 2;   // x = x * 2 = 24
x /= 4;   // x = x / 4 = 6

// String Concatenation
let greeting = "Hello" + " " + "World";  // "Hello World"
โš ๏ธ Always use === and !== instead of == and != to avoid unexpected type coercion!
CHAPTER 9

If/Else Conditions

๐Ÿ”„ Big Simple Explanation: Conditional statements let your code make decisions. “If this happens, do that; otherwise, do something else.”

๐Ÿ“Œ Syntax:
if (condition) {
    // code runs if condition is true
} else if (anotherCondition) {
    // code runs if first condition is false and this is true
} else {
    // code runs if all conditions are false
}
If/Else Examples
// Basic if
let age = 18;
if (age >= 18) {
    console.log("You can vote!");
}

// If/Else
let temperature = 30;
if (temperature > 25) {
    console.log("It's hot outside!");
} else {
    console.log("It's cool outside.");
}

// If/Else If ladder
let score = 85;
if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");  // This runs
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

// Nested if
let isLoggedIn = true;
let isAdmin = true;
if (isLoggedIn) {
    if (isAdmin) {
        console.log("Welcome Admin!");
    } else {
        console.log("Welcome User!");
    }
}

// Ternary operator (shorthand if/else)
let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);  // "Adult"
CHAPTER 10

Loops in JavaScript

๐Ÿ” Big Simple Explanation: Loops repeat code multiple times. Instead of writing the same code 100 times, write it once inside a loop!

for Loop

for (initialization; condition; increment) {
    // code to repeat
}

while Loop

while (condition) {
    // code runs while condition is true
}

do-while Loop

do {
    // code runs at least once
} while (condition);
Loop Examples
// FOR loop - when you know how many times
console.log("For loop:");
for (let i = 1; i <= 5; i++) {
    console.log(`Count: ${i}`);  // 1, 2, 3, 4, 5
}

// Loop through array
let fruits = ["Apple", "Banana", "Orange"];
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// WHILE loop - when you don't know count
console.log("While loop:");
let count = 1;
while (count <= 5) {
    console.log(`Round ${count}`);
    count++;
}

// DO-WHILE loop - runs at least once
let num = 10;
do {
    console.log(`Number is ${num}`);  // Runs once
    num++;
} while (num < 5);

// Break (exit loop early)
for (let i = 1; i <= 10; i++) {
    if (i === 6) {
        break;  // stops at 5
    }
    console.log(i);  // 1 2 3 4 5
}

// Continue (skip current iteration)
for (let i = 1; i <= 10; i++) {
    if (i % 2 === 0) {
        continue;  // skip even numbers
    }
    console.log(i);  // 1 3 5 7 9
}

// for...of loop (for arrays)
let colors = ["red", "green", "blue"];
for (let color of colors) {
    console.log(color);
}
CHAPTER 11

Strings & String Methods

๐Ÿ“ Big Simple Explanation: Strings are text. JavaScript has many built-in methods to work with strings.

String Examples
// Creating strings
let single = 'Hello';
let double = "World";
let template = `Hello ${single}!`;  // Template literal with variable

// String length
let text = "JavaScript";
console.log(text.length);  // 10

// Access characters
console.log(text[0]);    // "J"
console.log(text[4]);    // "S"
console.log(text.charAt(4));  // "S"

// Common string methods
let str = "  Hello World  ";

console.log(str.length);           // 16
console.log(str.trim());           // "Hello World" (removes spaces)
console.log(str.toUpperCase());    // "  HELLO WORLD  "
console.log(str.toLowerCase());    // "  hello world  "

let sentence = "The quick brown fox";
console.log(sentence.indexOf("quick"));   // 4 (position)
console.log(sentence.includes("fox"));    // true
console.log(sentence.slice(4, 9));        // "quick"
console.log(sentence.substring(4, 9));    // "quick"
console.log(sentence.split(" "));         // ["The", "quick", "brown", "fox"]

// Replace text
let newSentence = sentence.replace("fox", "dog");
console.log(newSentence);  // "The quick brown dog"

// Template literals (best for combining strings)
let name = "Alice";
let age = 25;
let intro = `My name is ${name} and I am ${age} years old.`;
console.log(intro);

// String concatenation (old way)
let greeting = "Hello" + " " + "World";
MethodDescriptionExample
lengthReturns string length"Hi".length โ†’ 2
toUpperCase()Converts to uppercase"hi".toUpperCase() โ†’ "HI"
toLowerCase()Converts to lowercase"HI".toLowerCase() โ†’ "hi"
trim()Removes whitespace from both ends" hi ".trim() โ†’ "hi"
indexOf()Returns index of first occurrence"Hello".indexOf("e") โ†’ 1
includes()Checks if string contains substring"Hello".includes("ell") โ†’ true
slice(start, end)Extracts part of string"Hello".slice(1,4) โ†’ "ell"
split(separator)Splits string into array"a,b,c".split(",") โ†’ ["a","b","c"]
replace(old, new)Replaces first match"cat".replace("c","b") โ†’ "bat"
CHAPTER 12

Numbers & Math Operations

๐Ÿ”ข Big Simple Explanation: JavaScript handles numbers for calculations. It has one Number type for both integers and decimals.

Number Examples
// Basic numbers
let integer = 42;
let decimal = 3.14159;
let negative = -10;
let scientific = 5.2e6;  // 5.2 ร— 10โถ = 5,200,000

// Number methods
let num = 123.456;
console.log(num.toFixed(2));    // "123.46" (rounds to 2 decimals)
console.log(num.toPrecision(4)); // "123.5" (4 significant digits)
console.log(parseInt("42px"));   // 42 (converts string to integer)
console.log(parseFloat("3.14")); // 3.14 (converts to float)
console.log(Number("123"));      // 123 (converts string to number)

// Special number values
console.log(Infinity);           // Infinity
console.log(-Infinity);          // -Infinity
console.log(NaN);                // "Not a Number"

// Math object
console.log(Math.PI);            // 3.141592653589793
console.log(Math.round(4.7));    // 5
console.log(Math.ceil(4.2));     // 5 (rounds up)
console.log(Math.floor(4.9));    // 4 (rounds down)
console.log(Math.abs(-5));       // 5 (absolute value)
console.log(Math.pow(2, 3));     // 8 (2ยณ)
console.log(Math.sqrt(16));      // 4
console.log(Math.random());      // Random number between 0 and 1
console.log(Math.floor(Math.random() * 100) + 1);  // Random 1-100

// Checking if value is a number
let value = "hello";
if (isNaN(value)) {
    console.log("Not a number!");  // This runs
}

// Number limits
console.log(Number.MAX_SAFE_INTEGER);  // 9007199254740991
console.log(Number.MIN_SAFE_INTEGER);  // -9007199254740991
CHAPTER 13

JavaScript Functions

๐ŸŽฏ Big Simple Explanation: Functions are reusable blocks of code. Like a recipe โ€” you write it once, then use it whenever you need it!

๐Ÿ“Œ Function Syntax:
function name(parameters) {
    // code to execute
    return value;  // optional
}
Function Examples
// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}
console.log(greet("Alice"));  // "Hello, Alice!"

// Function with multiple parameters
function add(a, b) {
    return a + b;
}
console.log(add(5, 3));  // 8

// Function without return (returns undefined)
function sayHello() {
    console.log("Hello!");
}
sayHello();

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

// Arrow Function (modern, shorter)
const subtract = (a, b) => a - b;
console.log(subtract(10, 3));  // 7

// Arrow function with multiple lines
const divide = (a, b) => {
    if (b === 0) return "Cannot divide by zero";
    return a / b;
};

// Default parameters
function greetWithTitle(name, title = "Guest") {
    return `Welcome, ${title} ${name}`;
}
console.log(greetWithTitle("John"));        // "Welcome, Guest John"
console.log(greetWithTitle("John", "Mr.")); // "Welcome, Mr. John"

// Rest parameters (...args)
function sumAll(...numbers) {
    let total = 0;
    for (let num of numbers) {
        total += num;
    }
    return total;
}
console.log(sumAll(1, 2, 3, 4, 5));  // 15

// Callback function (function passed as argument)
function processUser(name, callback) {
    callback(name);
}
processUser("Alice", (n) => console.log(`Hello ${n}`));

// Immediately Invoked Function Expression (IIFE)
(function() {
    console.log("This runs immediately!");
})();
CHAPTER 14

JavaScript Objects

๐Ÿ“ฆ Big Simple Explanation: Objects store collections of data in key-value pairs. They're like filing cabinets where each drawer (key) contains something (value).

๐Ÿ“Œ Object Syntax:
let objectName = {
    key1: value1,
    key2: value2,
    methodName: function() { ... }
};
Object Examples
// Creating an object
let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30,
    isStudent: false,
    // Method (function inside object)
    fullName: function() {
        return this.firstName + " " + this.lastName;
    },
    // Shorthand method
    greet() {
        return `Hello, I'm ${this.firstName}`;
    }
};

// Accessing properties (two ways)
console.log(person.firstName);     // "John" (dot notation)
console.log(person["lastName"]);   // "Doe" (bracket notation)

// Modifying properties
person.age = 31;
person.city = "New York";  // Add new property

// Deleting property
delete person.isStudent;

// Calling object methods
console.log(person.fullName());  // "John Doe"
console.log(person.greet());     // "Hello, I'm John"

// Object with nested objects
let company = {
    name: "TechCorp",
    address: {
        street: "123 Main St",
        city: "Boston",
        zip: "02101"
    },
    employees: ["Alice", "Bob", "Charlie"]
};
console.log(company.address.city);      // "Boston"
console.log(company.employees[1]);      // "Bob"

// Constructor function (creating multiple similar objects)
function Car(brand, model, year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
    this.getInfo = function() {
        return `${this.brand} ${this.model} (${this.year})`;
    };
}
let car1 = new Car("Toyota", "Camry", 2022);
let car2 = new Car("Honda", "Civic", 2023);
console.log(car1.getInfo());

// Object.keys(), values(), entries()
console.log(Object.keys(person));    // ["firstName", "lastName", "age", ...]
console.log(Object.values(person));  // ["John", "Doe", 31, ...]

// Looping through object properties
for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(`${key}: ${person[key]}`);
    }
}

// Object destructuring
let { firstName, age } = person;
console.log(firstName);  // "John"
console.log(age);        // 31
โœ… You've completed the JavaScript tutorial! Practice each concept by building small projects.

๐ŸŸจ Complete JavaScript Tutorial โ€” Big simple explanations ยท Syntax ยท Tables ยท Code Examples

ยฉ Esikhcha ยท JavaScript Mastery โ€” Open your browser console (F12) to experiment