πŸš€ JavaScript Documentation

Master the fundamentals of JavaScript with our comprehensive guide. From basic syntax to advanced concepts, everything you need to become proficient.

8 Sections
25+ Examples
100% Free

πŸ“– Introduction

JavaScript is a cross-platform, object-oriented scripting language that has become the backbone of modern web development. Originally designed to make web pages interactive, it has evolved into a powerful language used everywhere from browsers to servers, mobile apps to desktop applications.

πŸ’‘ Why Learn JavaScript?

  • 🌐 Universal: Runs in browsers, servers, and mobile apps
  • ⚑ Dynamic: Flexible and expressive syntax
  • πŸ”§ Versatile: Frontend, backend, and full-stack development
  • πŸ“ˆ In-demand: One of the most popular programming languages

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects.

πŸ–₯️ Client-side JavaScript

Extends the core language by supplying objects to control a browser and its Document Object Model (DOM). Client-side extensions allow applications to:

  • Manipulate HTML elements dynamically
  • Respond to user events (clicks, form input, navigation)
  • Create interactive user interfaces
  • Communicate with web APIs

πŸ–§ Server-side JavaScript

Extends the core language with objects relevant to running JavaScript on a server. Server-side extensions enable applications to:

  • Communicate with databases
  • Handle HTTP requests and responses
  • Perform file system operations
  • Build scalable web applications

🎯 Quick Example

// Your first JavaScript program
console.log("Hello, JavaScript World!");

// Variables and functions
const greeting = "Welcome to JavaScript!";
function showMessage(message) {
    alert(message);
}

showMessage(greeting);

βš–οΈ JavaScript and Java

Despite their similar names, JavaScript and Java are fundamentally different languages with distinct purposes, syntax, and execution models. Understanding these differences is crucial for developers working with either language.

πŸ” Key Differences

Aspect JavaScript Java
Type System Dynamic, loosely typed Static, strongly typed
Compilation Interpreted (JIT compiled) Compiled to bytecode
Object Model Prototype-based Class-based
Platform Web browsers, Node.js JVM (cross-platform)
Syntax Style Flexible, free-form Structured, verbose

πŸ“š Historical Context

JavaScript was originally named LiveScript but was renamed to JavaScript for marketing reasons when Netscape partnered with Sun Microsystems. The name similarity has caused confusion ever since, but the languages serve different purposes in the programming ecosystem.

πŸ—οΈ Object Models Compared

JavaScript: Prototype-based

// Prototype-based inheritance
function Animal(name) {
    this.name = name;
}

Animal.prototype.speak = function() {
    console.log(`${this.name} makes a sound`);
};

const dog = new Animal("Rex");
dog.speak(); // "Rex makes a sound"

Java: Class-based

// Class-based inheritance
public class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public void speak() {
        System.out.println(name + " makes a sound");
    }
}

✨ JavaScript Advantages

  • Rapid prototyping and development
  • No compilation step required
  • Dynamic and flexible
  • Excellent for web development
  • Large ecosystem (npm)

πŸ›‘οΈ Java Advantages

  • Strong type safety
  • Better performance for large applications
  • Excellent tooling and IDE support
  • Enterprise-grade frameworks
  • Platform independence

JavaScript's free-form nature means you don't need to declare all variables, classes, and methods upfront. You don't need to worry about access modifiers (public, private, protected) or implement interfaces explicitly. This flexibility makes JavaScript excellent for rapid development but requires discipline to maintain code quality in larger projects.

πŸ“¦ Variables

Variables are symbolic names for values in your application. They act as containers that store data values and allow you to reference and manipulate that data throughout your program.

🎯 Variable Naming Rules

βœ…
Must start with:
  • Letter (a-z, A-Z)
  • Underscore (_)
  • Dollar sign ($)
πŸ“
Can contain:
  • Letters
  • Digits (0-9)
  • Underscores
  • Dollar signs
⚠️
Case sensitive:
  • myVar β‰  MyVar
  • userName β‰  username

βœ… Valid Variable Names

// Valid identifiers
let userName = "John";
let _privateVar = 42;
let $element = document.getElementById("myDiv");
let temp99 = 25.5;
let numberOfItems = 10;
let isValid = true;

// Unicode characters are allowed
let cafΓ© = "coffee";
let naΓ―ve = "innocent";
let Ο€ = 3.14159;

❌ Invalid Variable Names

// Invalid identifiers - these will cause errors
let 2names = "invalid";     // Cannot start with digit
let my-var = "invalid";     // Hyphens not allowed
let class = "invalid";      // Reserved keyword
let my var = "invalid";     // Spaces not allowed
let @symbol = "invalid";    // @ symbol not allowed

πŸ’‘ Naming Best Practices

πŸͺ Use camelCase

let firstName = "John";
let totalAmount = 100;
let isUserLoggedIn = true;

πŸ“ Be Descriptive

// Good
let userAge = 25;
let shoppingCartItems = [];

// Avoid
let x = 25;
let arr = [];

πŸ”€ Use Constants for Fixed Values

const MAX_USERS = 100;
const API_URL = "https://api.example.com";
const TAX_RATE = 0.08;

🌍 Unicode Support

JavaScript supports Unicode characters in identifiers, allowing you to use letters from various languages and special characters. You can also use Unicode escape sequences in identifiers.

// Unicode examples
let rΓ©sumΓ© = "CV document";
let ε˜ι‡ = "Chinese variable";
let \u0041pple = "Apple"; // \u0041 is Unicode for 'A'

🏷️ Data Types

JavaScript has dynamic typing, meaning variables can hold values of any type without declaring the type explicitly. The latest ECMAScript standard defines eight primitive data types plus objects.

πŸ”’ Primitive Types

βœ…
Boolean

Represents logical values: true or false

let isActive = true;
let isComplete = false;
πŸ”’
Number

Represents both integers and floating-point numbers

let age = 25;
let price = 19.99;
let infinity = Infinity;
πŸ”€
String

Represents textual data

let name = "John";
let message = 'Hello World';
let template = `Welcome ${name}!`;
❓
undefined

Variable declared but not assigned a value

let x;
console.log(x); // undefined
β­•
null

Intentional absence of any object value

let data = null;
// Note: null !== NULL !== Null
πŸ†”
Symbol

Unique identifier (ES2015+)

let sym1 = Symbol('id');
let sym2 = Symbol('id');
console.log(sym1 === sym2); // false
πŸ”’
BigInt

Large integers beyond Number.MAX_SAFE_INTEGER

let bigNumber = 123456789012345678901234567890n;
let anotherBig = BigInt("123456789012345678901234567890");

πŸ“¦ Object Type

πŸ—οΈ
Object

Complex data type that can store collections of data

let person = {
  name: "Alice",
  age: 30,
  hobbies: ["reading", "coding"]
};

let numbers = [1, 2, 3, 4, 5];
let today = new Date();

πŸ” Type Checking

Use the typeof operator to check the type of a variable:

console.log(typeof 42);          // "number"
console.log(typeof "Hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object" (this is a known quirk!)
console.log(typeof Symbol('id')); // "symbol"
console.log(typeof 123n);        // "bigint"
console.log(typeof {});          // "object"
console.log(typeof []);          // "object"
console.log(typeof function(){}); // "function"

⚠️ Important Notes

  • null quirk: typeof null returns "object" due to a historical bug
  • Arrays: Are objects, so typeof [] returns "object"
  • Functions: Are objects but typeof function(){} returns "function"
  • Case sensitivity: null β‰  NULL β‰  Null

Although JavaScript has a relatively small number of data types, they enable you to perform powerful operations in your applications. Objects and functions are the other fundamental elements that make JavaScript so versatile. Think of objects as named containers for values, and functions as reusable procedures that your application can execute.

πŸ”’ Constants

Constants are read-only named values created with the const keyword. Once declared and initialized, their value cannot be changed through reassignment, making them perfect for values that should remain fixed throughout your program.

✨ Constant Declaration

// Basic constant declaration
const PI = 3.14159;
const MAX_USERS = 100;
const API_URL = "https://api.example.com";

// Constants must be initialized
const APP_NAME = "My Application"; // βœ… Correct
// const EMPTY_CONST; // ❌ Error: Missing initializer

πŸ“‹ Constant Rules

🚫

Cannot be reassigned

const PI = 3.14;
PI = 3.14159; // ❌ TypeError: Assignment to constant variable
🚫

Cannot be redeclared

const MAX_SIZE = 100;
const MAX_SIZE = 200; // ❌ SyntaxError: Identifier 'MAX_SIZE' has already been declared
βœ…

Must be initialized

const GREETING = "Hello"; // βœ… Correct
// const MESSAGE; // ❌ SyntaxError: Missing initializer in const declaration
πŸ”’

Block scoped

if (true) {
  const TEMP = "block scoped";
}
// console.log(TEMP); // ❌ ReferenceError: TEMP is not defined

⚠️ Important: Object Mutability

While the constant binding cannot be changed, the contents of objects and arrays can still be modified. The const keyword prevents reassignment, not mutation.

// Object properties can be modified
const USER = {
  name: "John",
  age: 25
};

USER.age = 26;        // βœ… This works - modifying property
USER.city = "NYC";    // βœ… This works - adding property
// USER = {};         // ❌ This fails - reassigning the constant

// Array elements can be modified
const COLORS = ["red", "green", "blue"];
COLORS.push("yellow"); // βœ… This works - modifying array
COLORS[0] = "crimson"; // βœ… This works - changing element
// COLORS = [];        // ❌ This fails - reassigning the constant

πŸ’‘ Best Practices

πŸ”€ Naming Convention

Use UPPER_SNAKE_CASE for constants that represent fixed values:

const MAX_RETRY_ATTEMPTS = 3;
const DEFAULT_TIMEOUT = 5000;
const ERROR_MESSAGES = {
  NOT_FOUND: "Resource not found",
  UNAUTHORIZED: "Access denied"
};

🎯 Use for Configuration

Constants are perfect for configuration values:

const CONFIG = {
  API_BASE_URL: "https://api.myapp.com",
  ITEMS_PER_PAGE: 20,
  CACHE_DURATION: 300000
};

πŸ” Scope Comparison

// Function scope example
function example() {
  const LOCAL_CONST = "function scoped";

  if (true) {
    const BLOCK_CONST = "block scoped";
    console.log(LOCAL_CONST);  // βœ… Accessible
    console.log(BLOCK_CONST);  // βœ… Accessible
  }

  console.log(LOCAL_CONST);    // βœ… Accessible
  // console.log(BLOCK_CONST); // ❌ ReferenceError
}

// Global scope
const GLOBAL_CONST = "globally accessible";
example();

✨ Declaring Variables

JavaScript provides three ways to declare variables: var, let, and const. Each has different scoping rules, hoisting behavior, and use cases. Understanding these differences is crucial for writing reliable JavaScript code.

πŸ”„ var Declaration

Function-scoped or globally-scoped variable declaration

var x = 42;
var name = "John";

// Can be redeclared
var x = 100; // βœ… No error

// Function scoped
function example() {
  var localVar = "function scoped";
  if (true) {
    var localVar = "still function scoped";
  }
  console.log(localVar); // "still function scoped"
}

🎯 let Declaration

Block-scoped variable declaration (ES2015+)

let y = 13;
let message = "Hello";

// Cannot be redeclared in same scope
// let y = 20; // ❌ SyntaxError

// Block scoped
function example() {
  let blockVar = "block scoped";
  if (true) {
    let blockVar = "different block scope";
    console.log(blockVar); // "different block scope"
  }
  console.log(blockVar); // "block scoped"
}

πŸ”’ const Declaration

Block-scoped constant declaration

const PI = 3.14159;
const CONFIG = { api: "https://api.example.com" };

// Must be initialized
// const EMPTY; // ❌ SyntaxError

// Cannot be reassigned
// PI = 3.14; // ❌ TypeError

πŸ“Š Declaration Comparison

Feature var let const
Scope Function/Global Block Block
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Redeclaration Allowed Not allowed Not allowed
Reassignment Allowed Allowed Not allowed
Initialization Optional Optional Required

⚠️ Avoid Global Assignment

Assigning a value without any declaration keyword creates a global variable, which is generally considered bad practice:

// Avoid this - creates global variable
x = 42; // ❌ Bad practice

// In strict mode, this throws an error
"use strict";
y = 13; // ❌ ReferenceError: y is not defined

πŸ’‘ Modern Best Practices

πŸ₯‡
Prefer const by default

Use const for values that won't be reassigned

πŸ₯ˆ
Use let when reassignment is needed

Use let for variables that will change

🚫
Avoid var in modern JavaScript

Use let and const instead for better scoping

πŸ” Scope Demonstration

function scopeDemo() {
  console.log("=== Scope Demonstration ===");

  // var is function-scoped
  if (true) {
    var varVariable = "I'm function scoped";
    let letVariable = "I'm block scoped";
    const constVariable = "I'm also block scoped";
  }

  console.log(varVariable);    // βœ… "I'm function scoped"
  // console.log(letVariable); // ❌ ReferenceError
  // console.log(constVariable); // ❌ ReferenceError
}

scopeDemo();

⚑ Functions

Functions are reusable blocks of code that perform specific tasks. They are fundamental building blocks in JavaScript, allowing you to organize code, avoid repetition, and create modular applications.

🎭 Function Declaration Types

πŸ“ Function Declaration

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

console.log(greet("Alice")); // "Hello, Alice!"

🎯 Function Expression

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

console.log(greet("Bob")); // "Hello, Bob!"

🏹 Arrow Function (ES2015+)

// Arrow function - concise syntax
const greet = (name) => `Hello, ${name}!`;

// Multiple parameters
const add = (a, b) => a + b;

// Block body
const processData = (data) => {
  const processed = data.map(item => item * 2);
  return processed.filter(item => item > 10);
};

✨ Function Features

// Default parameters
function greet(name = "World", punctuation = "!") {
  return `Hello, ${name}${punctuation}`;
}

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

// Destructuring parameters
function createUser({name, age, email}) {
  return {
    id: Date.now(),
    name,
    age,
    email,
    createdAt: new Date()
  };
}

// Usage examples
console.log(greet());                    // "Hello, World!"
console.log(greet("Alice", "?"));        // "Hello, Alice?"
console.log(sum(1, 2, 3, 4, 5));        // 15
console.log(createUser({
  name: "John",
  age: 30,
  email: "john@example.com"
}));

πŸ’‘ Best Practices

Following JavaScript best practices helps you write cleaner, more maintainable, and more reliable code. These guidelines will improve your code quality and make collaboration easier.

πŸ“ Naming Conventions

// Use camelCase for variables and functions
const userName = "john_doe";
const calculateTotalPrice = (items) => { /* ... */ };

// Use PascalCase for constructors and classes
class UserAccount { /* ... */ }
const user = new UserAccount();

// Use UPPER_SNAKE_CASE for constants
const MAX_RETRY_ATTEMPTS = 3;
const API_BASE_URL = "https://api.example.com";

πŸ”’ Use Strict Mode

"use strict";

// Prevents common mistakes
function example() {
  // undeclaredVar = 42; // ❌ ReferenceError in strict mode
  let declaredVar = 42;   // βœ… Correct
}

🎯 Prefer Modern Syntax

// Use const/let instead of var
const items = [1, 2, 3];
let counter = 0;

// Use arrow functions for short functions
const double = x => x * 2;

// Use template literals
const message = `Hello, ${userName}!`;

// Use destructuring
const {name, age} = user;
const [first, second] = items;