Complete JavaScript Mastery

From fundamentals to advanced techniques - master Js with our comprehensive guide covering all concepts with practical examples and modern techniques.

Complete JavaScript Tutorial

Master JavaScript - the programming language of the web

Introduction to JavaScript

JavaScript is a lightweight, interpreted programming language with first-class functions. It is most well-known as the scripting language for Web pages, but many non-browser environments also use it.

Simple JavaScript Example
// Display a greeting
function greet(name) {
    console.log(`Hello, ${name}!`);
}

greet('World'); // Output: Hello, World!

What Can JavaScript Do?

  • Create dynamic website content
  • Handle user interactions
  • Validate form data
  • Create animations and effects
  • Build web and mobile apps
  • Develop server-side applications (Node.js)
  • Create games

JavaScript Syntax

JavaScript syntax is the set of rules that define how JavaScript programs are constructed.

Basic Syntax Rules
// Variables
let x = 5;
const y = 10;

// Functions
function add(a, b) {
    return a + b;
}

// Objects
const person = {
    name: 'John',
    age: 30
};

// Arrays
const colors = ['red', 'green', 'blue'];

JavaScript Statements

JavaScript programs are composed of statements that are executed by the browser. Each statement should end with a semicolon (;).

Comments

// Single-line comment

/*
Multi-line
comment
*/

Variables

Variables are containers for storing data values.

Variable Declaration
// Using var (older, function-scoped)
var name = 'John';

// Using let (block-scoped, can be reassigned)
let age = 30;

// Using const (block-scoped, cannot be reassigned)
const PI = 3.14;

Variable Naming Rules

  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter, $ or _
  • Names are case sensitive
  • Reserved words cannot be used as names

Operators

JavaScript operators are used to assign values, compare values, perform arithmetic operations, and more.

Operator Type Operators Description
Arithmetic + - * / % ** ++ -- Perform mathematical operations
Assignment = += -= *= /= %= **= Assign values to variables
Comparison == === != !== > < >= <= Compare two values
Logical && || ! Combine conditional statements
Bitwise & | ^ ~ << >> >>> Work on 32-bit numbers
Ternary ? : Shorthand for if-else

Data Types

JavaScript variables can hold different data types: numbers, strings, objects and more.

Primitive Data Types

Type Description Example
String Textual data 'Hello', "World"
Number Integer or floating-point 42, 3.14
Boolean Logical true/false true, false
Undefined Variable not assigned let x;
Null Intentional empty value let x = null;
BigInt Large integers 123n
Symbol Unique identifier Symbol('id')

Non-Primitive Data Type

Object: Collections of key-value pairs

const person = {
    name: 'John',
    age: 30,
    isAdmin: true
};

Functions

A JavaScript function is a block of code designed to perform a particular task.

Function Declaration
// Function declaration
function greet(name) {
    return `Hello, ${name}!`;
}

// Function expression
const greet = function(name) {
    return `Hello, ${name}!`;
};

// Arrow function (ES6+)
const greet = (name) => `Hello, ${name}!`;

Function Parameters

// Default parameters
function greet(name = 'Guest') {
    console.log(`Hello, ${name}!`);
}

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b);
}

Objects

Objects are collections of properties, where each property is a key-value pair.

Object Creation
// Object literal
const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    fullName: function() {
        return `${this.firstName} ${this.lastName}`;
    }
};

// Accessing properties
console.log(person.firstName); // John
console.log(person['lastName']); // Doe
console.log(person.fullName()); // John Doe

Object Methods

const person = {
    name: 'John',
    greet: function() {
        console.log(`Hello, ${this.name}!`);
    }
};

person.greet(); // Hello, John!

Arrays

Arrays are used to store multiple values in a single variable.

Array Operations
// Creating arrays
const fruits = ['Apple', 'Banana', 'Orange'];

// Accessing elements
console.log(fruits[0]); // Apple

// Array methods
fruits.push('Mango'); // Add to end
fruits.pop(); // Remove from end
fruits.unshift('Strawberry'); // Add to beginning
fruits.shift(); // Remove from beginning

// Iterating
fruits.forEach(fruit => console.log(fruit));

Common Array Methods

Method Description
map() Creates new array with results of calling function
filter() Creates new array with elements that pass test
reduce() Reduces array to single value
find() Returns first element that passes test
sort() Sorts elements of array
slice() Returns shallow copy of portion of array
splice() Adds/removes elements from array

Conditionals

Conditional statements are used to perform different actions based on different conditions.

if...else Statement
let hour = new Date().getHours();
let greeting;

if (hour < 12) {
    greeting = 'Good morning';
} else if (hour < 18) {
    greeting = 'Good afternoon';
} else {
    greeting = 'Good evening';
}

console.log(greeting);

switch Statement

let day;
switch (new Date().getDay()) {
    case 0:
        day = 'Sunday';
        break;
    case 1:
        day = 'Monday';
        break;
    // ... other cases ...
    default:
        day = 'Unknown';
}

Ternary Operator

let age = 20;
let canVote = (age >= 18) ? 'Yes' : 'No';

Loops

Loops can execute a block of code a number of times.

Different Loop Types
// for loop
for (let i = 0; i < 5; i++) {
    console.log(i);
}

// while loop
let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

// do...while loop
let j = 0;
do {
    console.log(j);
    j++;
} while (j < 5);

// for...of loop (arrays)
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
    console.log(color);
}

// for...in loop (objects)
const person = {name: 'John', age: 30};
for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

Events

HTML events are "things" that happen to HTML elements. JavaScript can "react" on these events.

Event Handling
// HTML: <button id="myBtn">Click me</button>

// Get the button element
const btn = document.getElementById('myBtn');

// Add click event listener
btn.addEventListener('click', function() {
    alert('Button was clicked!');
});

Common HTML Events

Event Description
click When mouse clicks an element
mouseover When mouse moves over an element
mouseout When mouse moves out of an element
keydown When keyboard key is pressed
load When page has finished loading
submit When form is submitted
change When element value changes

DOM Manipulation

The Document Object Model (DOM) is a programming interface for HTML and XML documents.

DOM Methods
// Selecting elements
document.getElementById('id');
document.querySelector('.class');
document.querySelectorAll('p');

// Creating elements
const div = document.createElement('div');
div.textContent = 'Hello World';
document.body.appendChild(div);

// Modifying elements
const element = document.getElementById('demo');
element.innerHTML = 'New content';
element.style.color = 'red';
element.classList.add('active');

// Event handling
element.addEventListener('click', function() {
    this.style.display = 'none';
});

DOM Traversal

// Get parent
const parent = element.parentNode;

// Get children
const children = element.children;

// Get siblings
const nextSibling = element.nextElementSibling;
const prevSibling = element.previousElementSibling;

ES6+ Features

ECMAScript 2015 (ES6) introduced major changes to JavaScript. Here are some key features:

let and const

let x = 10; // Block-scoped, can be reassigned
const y = 20; // Block-scoped, cannot be reassigned

Arrow Functions

// Traditional function
function add(a, b) {
    return a + b;
}

// Arrow function
const add = (a, b) => a + b;

Template Literals

const name = 'John';
console.log(`Hello, ${name}!`); // Hello, John!

Destructuring

// Array destructuring
const [first, second] = [1, 2];

// Object destructuring
const {name, age} = {name: 'John', age: 30};

Spread/Rest Operator

// Spread
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((a, b) => a + b);
}

Asynchronous JavaScript

JavaScript is single-threaded, but can handle asynchronous operations.

Callbacks

function fetchData(callback) {
    setTimeout(() => {
        callback('Data received');
    }, 1000);
}

fetchData(data => {
    console.log(data); // After 1 second: "Data received"
});

Promises

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('Promise resolved');
    }, 1000);
});

promise.then(result => {
    console.log(result); // After 1 second: "Promise resolved"
}).catch(error => {
    console.error(error);
});

Async/Await

async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchData();

Error Handling

JavaScript provides error handling with try...catch statements.

try...catch
try {
    // Code that may throw an error
    nonExistentFunction();
} catch (error) {
    console.error('An error occurred:', error.message);
} finally {
    console.log('This always runs');
}

Throwing Errors

function divide(a, b) {
    if (b === 0) {
        throw new Error('Cannot divide by zero');
    }
    return a / b;
}

try {
    console.log(divide(10, 0));
} catch (error) {
    console.error(error.message); // "Cannot divide by zero"
}

JavaScript Best Practices

  • Use const by default, let when rebinding is needed
  • Avoid global variables
  • Use strict equality (===) instead of loose equality (==)
  • Use template literals for string concatenation
  • Follow consistent naming conventions (camelCase for variables/functions, PascalCase for constructors/classes)
  • Always declare variables at the top of their scope
  • Use arrow functions when appropriate
  • Handle errors properly with try/catch
  • Comment your code when necessary
  • Use modern ES6+ features when possible
  • Modularize your code into smaller functions
  • Use promises/async-await instead of callbacks for async code