π JavaScript Documentation
Master the fundamentals of JavaScript with our comprehensive guide. From basic syntax to advanced concepts, everything you need to become proficient.
π 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
- Letter (a-z, A-Z)
- Underscore (_)
- Dollar sign ($)
- Letters
- Digits (0-9)
- Underscores
- Dollar signs
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
Represents logical values: true
or
false
let isActive = true;
let isComplete = false;
Represents both integers and floating-point numbers
let age = 25;
let price = 19.99;
let infinity = Infinity;
Represents textual data
let name = "John";
let message = 'Hello World';
let template = `Welcome ${name}!`;
Variable declared but not assigned a value
let x;
console.log(x); // undefined
Intentional absence of any object value
let data = null;
// Note: null !== NULL !== Null
Unique identifier (ES2015+)
let sym1 = Symbol('id');
let sym2 = Symbol('id');
console.log(sym1 === sym2); // false
Large integers beyond Number.MAX_SAFE_INTEGER
let bigNumber = 123456789012345678901234567890n;
let anotherBig = BigInt("123456789012345678901234567890");
π¦ Object Type
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
Use const
for values that won't be reassigned
Use let
for variables that will change
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;