๐จ JavaScript Complete Tutorial
Big simple explanations ยท Clear syntax ยท Real code examples
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
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)
<button onclick="alert('Clicked!')">Click Me</button>Method 2: Internal (inside <script> tag)
<!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');
<script src="script.js"></script>
defer attribute.JavaScript Output Methods
๐จ๏ธ Big Simple Explanation: JavaScript has 4 main ways to show output, each useful in different situations.
| Method | Description | Example |
|---|---|---|
console.log() | Shows in browser’s developer console | console.log("Debug message"); |
alert() | Shows a popup alert box | alert("Warning!"); |
document.write() | Writes directly to HTML page | document.write("Hello"); |
innerHTML | Changes content of an HTML element | element.innerHTML = "New text"; |
// 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!";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!
// 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)
// 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 literalVariables: var, let, const
๐ฆ Big Simple Explanation: Variables are containers for storing data values. Think of them as labeled boxes where you keep information.
| Keyword | Scope | Can Reassign? | Can Redeclare? | Best Practice |
|---|---|---|---|---|
var | Function scope | โ Yes | โ Yes | Avoid in modern JS (old way) |
let | Block scope {} | โ Yes | โ No | Use when value changes |
const | Block scope {} | โ No | โ No | Use for values that never change |
// 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
const by default. Only use let when you know the value will change. Never use var in modern JavaScript!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.
| Type | Description | Example | typeof Output |
|---|---|---|---|
| String | Text value | "Hello World" | "string" |
| Number | Integer or decimal | 42, 3.14 | "number" |
| Boolean | True or false | true, false | "boolean" |
| Undefined | Variable declared, not assigned | let x; | "undefined" |
| Null | Intentional empty value | let y = null; | "object" |
| BigInt | Very large integers | 9007199254740991n | "bigint" |
| Symbol | Unique identifier | Symbol('id') | "symbol" |
| Object | Collection of data | {name: "John"} | "object" |
// 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!)JavaScript Operators
๐งฎ Big Simple Explanation: Operators are symbols that perform operations on values. They’re like the verbs of JavaScript!
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 5 | 15 |
| – | Subtraction | 10 – 5 | 5 |
| * | Multiplication | 10 * 5 | 50 |
| / | Division | 10 / 5 | 2 |
| % | Modulus (Remainder) | 10 % 3 | 1 |
| ** | Exponentiation | 2 ** 3 | 8 |
| ++ | Increment | let x=5; x++ | 6 |
| — | Decrement | let x=5; x– | 4 |
Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal value | 5 == “5” | true |
| === | Equal value & type | 5 === “5” | false |
| != | Not equal value | 5 != “5” | false |
| !== | Not equal value/type | 5 !== “5” | true |
| > | Greater than | 10 > 5 | true |
| < | Less than | 10 < 5 | false |
| >= | Greater than or equal | 10 >= 10 | true |
| <= | Less than or equal | 10 <= 9 | false |
// 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"
=== and !== instead of == and != to avoid unexpected type coercion!If/Else Conditions
๐ Big Simple Explanation: Conditional statements let your code make decisions. “If this happens, do that; otherwise, do something else.”
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
}
// 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"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);// 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);
}Strings & String Methods
๐ Big Simple Explanation: Strings are text. JavaScript has many built-in methods to work with strings.
// 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";| Method | Description | Example |
|---|---|---|
length | Returns 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" |
Numbers & Math Operations
๐ข Big Simple Explanation: JavaScript handles numbers for calculations. It has one Number type for both integers and decimals.
// 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); // -9007199254740991JavaScript 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 name(parameters) {
// code to execute
return value; // optional
}
// 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!");
})();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).
let objectName = {
key1: value1,
key2: value2,
methodName: function() { ... }
};
// 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
Comments
๐ฌ Big Simple Explanation: Comments are text that JavaScript ignores. They help you explain your code to yourself and others!
// 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");