JavaScript Basics - Complete Programming Fundamentals Tutorial
JavaScript is one of the core languages of modern web development and the most popular programming language in the world. This comprehensive tutorial will take you from zero to mastering the fundamentals of JavaScript programming, covering everything from basic syntax to advanced concepts.
Why Learn JavaScript?
JavaScript is essential for modern web development because it:
- Powers Interactive Websites: Creates dynamic, responsive user interfaces
- Runs Everywhere: Works in browsers, servers (Node.js), mobile apps, and desktop applications
- High Demand: One of the most sought-after skills in the tech industry
- Versatile: Used for frontend, backend, mobile, and desktop development
- Easy to Learn: Beginner-friendly syntax and extensive community support
Learning Objectives
Through this tutorial, you will learn:
- JavaScript basic syntax and data types
- Variable declaration and scope
- Function definition and invocation
- Object and array operations
- Control flow statements
What is JavaScript?
JavaScript is a high-level, interpreted programming language. It was originally designed to create dynamic web pages in browsers, but is now widely used in server-side development, mobile app development, and other fields.
Official Resources
- MDN JavaScript Guide - Comprehensive JavaScript documentation
- ECMAScript Specification - Official JavaScript language specification
- JavaScript.info - Modern JavaScript tutorial
- Node.js Official Documentation - Server-side JavaScript runtime
Basic Syntax
Variable Declaration
JavaScript provides three ways to declare variables, each with different scoping and mutability characteristics:
var
- Function-Scoped Variables
// var is function-scoped and can be redeclared
var name = "John";
var name = "Jane"; // This is allowed
function example() {
var localVar = "I'm function-scoped";
if (true) {
var blockVar = "I'm still function-scoped";
}
console.log(blockVar); // Accessible here
}
let
- Block-Scoped Variables
// let is block-scoped and cannot be redeclared
let age = 25;
// let age = 30; // Error: Identifier 'age' has already been declared
if (true) {
let blockScoped = "I'm block-scoped";
console.log(blockScoped); // Works
}
// console.log(blockScoped); // Error: blockScoped is not defined
const
- Block-Scoped Constants
// const is block-scoped and cannot be reassigned
const PI = 3.14159;
// PI = 3.14; // Error: Assignment to constant variable
// However, object properties can be modified
const person = { name: "John", age: 25 };
person.age = 26; // This is allowed
// person = {}; // This would cause an error
Variable Naming Rules
// Valid variable names
let userName = "john_doe";
let userAge = 25;
let $special = "starts with dollar";
let _private = "starts with underscore";
// Invalid variable names
// let 2user = "invalid"; // Cannot start with number
// let user-name = "invalid"; // Cannot contain hyphens
// let class = "invalid"; // Cannot use reserved words
Useful Tools and References
- JavaScript Variable Naming Conventions - MDN naming guidelines
- ESLint - JavaScript linting tool for code quality
- Prettier - Code formatter for consistent style
- JavaScript Reserved Words - Complete list of reserved keywords
Variable Hoisting
// var declarations are hoisted (but not their values)
console.log(hoistedVar); // undefined (not ReferenceError)
var hoistedVar = "I'm hoisted";
// let and const are in temporal dead zone
// console.log(hoistedLet); // ReferenceError
let hoistedLet = "I'm not accessible yet";
var vs let vs const: Complete Comparison
Understanding the differences between var
, let
, and const
is crucial for writing modern JavaScript. Here's a comprehensive comparison:
1. Scope Differences
// var - Function-scoped
function varExample() {
if (true) {
var functionScoped = "I'm accessible throughout the function";
}
console.log(functionScoped); // Works - accessible here
}
// let/const - Block-scoped
function blockExample() {
if (true) {
let blockScoped = "I'm only accessible in this block";
const alsoBlockScoped = "Same for const";
}
// console.log(blockScoped); // Error: blockScoped is not defined
// console.log(alsoBlockScoped); // Error: alsoBlockScoped is not defined
}
2. Redeclaration Rules
// var - Can be redeclared
var name = "John";
var name = "Jane"; // No error - allowed
// let - Cannot be redeclared in same scope
let age = 25;
// let age = 30; // SyntaxError: Identifier 'age' has already been declared
// const - Cannot be redeclared
const PI = 3.14159;
// const PI = 3.14; // SyntaxError: Identifier 'PI' has already been declared
3. Reassignment Rules
// var - Can be reassigned
var count = 1;
count = 2; // Allowed
// let - Can be reassigned
let score = 100;
score = 200; // Allowed
// const - Cannot be reassigned
const MAX_SIZE = 1000;
// MAX_SIZE = 2000; // TypeError: Assignment to constant variable
4. Hoisting Behavior
// var - Hoisted and initialized with undefined
console.log(varHoisted); // undefined (not ReferenceError)
var varHoisted = "I'm hoisted";
// let/const - Hoisted but in temporal dead zone
// console.log(letHoisted); // ReferenceError: Cannot access before initialization
let letHoisted = "I'm in temporal dead zone";
// console.log(constHoisted); // ReferenceError: Cannot access before initialization
const constHoisted = "I'm also in temporal dead zone";
5. Loop Behavior (Important Difference)
// var in loops - Creates closure issues
console.log("=== var in loop ===");
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints: 3, 3, 3
}
// let in loops - Creates proper block scope
console.log("=== let in loop ===");
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // Prints: 0, 1, 2
}
6. Object and Array Mutability with const
// const prevents reassignment, not mutation
const person = { name: "John", age: 25 };
const numbers = [1, 2, 3];
// These are allowed - modifying object/array contents
person.age = 26; // Allowed
person.city = "New York"; // Allowed
numbers.push(4); // Allowed
numbers[0] = 10; // Allowed
// These would cause errors - reassigning the variable
// person = { name: "Jane" }; // TypeError
// numbers = [5, 6, 7]; // TypeError
7. Best Practices and Recommendations
// ✅ RECOMMENDED: Use const by default
const API_URL = "https://api.example.com";
const userPreferences = { theme: "dark", language: "en" };
// ✅ Use let when you need to reassign
let currentUser = null;
let isLoading = false;
// ❌ AVOID: Using var in modern JavaScript
// var oldStyle = "Don't use this in new code";
// ✅ Good: Block-scoped variables
function processData(data) {
const result = [];
for (let i = 0; i < data.length; i++) {
const item = data[i];
if (item.isValid) {
result.push(item);
}
}
return result;
}
8. When to Use Each
Declaration | When to Use | Example |
---|---|---|
const | Default choice for all variables | const userName = "john_doe"; |
let | When you need to reassign the variable | let counter = 0; counter++; |
var | Legacy code only - avoid in new projects | Not recommended |
9. Common Pitfalls and Solutions
// ❌ Problem: var hoisting can cause confusion
function problematicFunction() {
console.log(x); // undefined (not ReferenceError)
var x = 5;
}
// ✅ Solution: Use let/const for clearer behavior
function betterFunction() {
// console.log(y); // ReferenceError - clearer error
let y = 5;
}
// ❌ Problem: var in loops
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
// ✅ Solution: Use let for proper scoping
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
10. Modern JavaScript Style Guide
// ✅ Modern JavaScript best practices
const config = {
apiUrl: "https://api.example.com",
timeout: 5000
};
let isConnected = false;
function connect() {
isConnected = true;
console.log("Connected to", config.apiUrl);
}
// Use const for functions that won't be reassigned
const calculateTotal = (items) => {
return items.reduce((sum, item) => sum + item.price, 0);
};
// Use let for variables that change
let currentIndex = 0;
const nextItem = () => {
currentIndex++;
return items[currentIndex];
};
Data Types
JavaScript has several primitive data types:
// Numbers
let num = 42;
let float = 3.14;
// Strings
let str = "Hello, World!";
let template = `Hello, ${name}!`;
// Booleans
let isTrue = true;
let isFalse = false;
// Undefined
let undefinedVar;
// Null
let nullVar = null;
// Symbols (ES6)
let sym = Symbol('id');
// BigInt (ES2020)
let bigNum = 123n;
Objects and Arrays
// Objects
let person = {
name: "Alice",
age: 30,
city: "London",
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
// Arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
// Accessing elements
console.log(person.name); // "Alice"
console.log(fruits[0]); // "apple"
Functions
Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World")); // "Hello, World!"
Function Expression
const greet = function(name) {
return `Hello, ${name}!`;
};
console.log(greet("World")); // "Hello, World!"
Arrow Functions (ES6)
const greet = (name) => {
return `Hello, ${name}!`;
};
// Simplified syntax
const greet = name => `Hello, ${name}!`;
console.log(greet("World")); // "Hello, World!"
Control Flow
Conditional Statements
let age = 18;
if (age >= 18) {
console.log("You are an adult");
} else if (age >= 13) {
console.log("You are a teenager");
} else {
console.log("You are a child");
}
// Ternary operator
let status = age >= 18 ? "adult" : "minor";
Loops
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// For...of loop (ES6)
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// For...in loop
let person = { name: "John", age: 30 };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Array Methods
Common Array Methods
let numbers = [1, 2, 3, 4, 5];
// map - transform each element
let doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter - select elements based on condition
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
// reduce - reduce array to single value
let sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15
// find - find first element matching condition
let found = numbers.find(n => n > 3);
console.log(found); // 4
// includes - check if array contains element
let hasThree = numbers.includes(3);
console.log(hasThree); // true
Object Methods
Object Manipulation
let person = {
name: "John",
age: 30,
city: "New York"
};
// Object.keys() - get all keys
let keys = Object.keys(person);
console.log(keys); // ["name", "age", "city"]
// Object.values() - get all values
let values = Object.values(person);
console.log(values); // ["John", 30, "New York"]
// Object.entries() - get key-value pairs
let entries = Object.entries(person);
console.log(entries); // [["name", "John"], ["age", 30], ["city", "New York"]]
// Object.assign() - copy properties
let newPerson = Object.assign({}, person, { age: 31 });
console.log(newPerson); // { name: "John", age: 31, city: "New York" }
Error Handling
Try-Catch
try {
// Code that might throw an error
let result = riskyOperation();
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
} finally {
// Code that always runs
console.log("Cleanup code");
}
Practice Project: Simple Calculator
Let's create a simple calculator to practice what we've learned:
class Calculator {
constructor() {
this.history = [];
}
add(a, b) {
const result = a + b;
this.history.push(`${a} + ${b} = ${result}`);
return result;
}
subtract(a, b) {
const result = a - b;
this.history.push(`${a} - ${b} = ${result}`);
return result;
}
multiply(a, b) {
const result = a * b;
this.history.push(`${a} * ${b} = ${result}`);
return result;
}
divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
const result = a / b;
this.history.push(`${a} / ${b} = ${result}`);
return result;
}
getHistory() {
return this.history;
}
clearHistory() {
this.history = [];
}
}
// Usage example
const calc = new Calculator();
console.log(calc.add(10, 5)); // 15
console.log(calc.multiply(3, 4)); // 12
console.log(calc.getHistory());
// ["10 + 5 = 15", "3 * 4 = 12"]
Summary
This tutorial covered the basics of JavaScript, including:
- Variable declaration and data types
- Functions and control flow
- Objects and arrays
- Common array and object methods
- Error handling
- A practical calculator project
JavaScript is a powerful and flexible language that forms the foundation of modern web development. With these basics, you're ready to explore more advanced concepts!
Next Steps
Further Reading and Resources
Official Documentation
- MDN JavaScript Reference - Complete JavaScript API reference
- ECMAScript 2023 Specification - Latest JavaScript language specification
- Node.js Documentation - Server-side JavaScript runtime
Learning Platforms
- JavaScript.info - Modern JavaScript tutorial with interactive examples
- FreeCodeCamp JavaScript Course - Free interactive coding course
- Codecademy JavaScript Course - Interactive JavaScript learning platform
Development Tools
- VS Code - Popular code editor with excellent JavaScript support
- Chrome DevTools - Browser debugging tools
- Babel - JavaScript compiler for modern features
- Webpack - Module bundler for JavaScript applications
Community and Forums
- Stack Overflow - JavaScript Q&A community
- Reddit r/javascript - JavaScript community discussions
- JavaScript Weekly - Weekly JavaScript newsletter
- GitHub JavaScript Trending - Popular JavaScript repositories
Practice and Challenges
- LeetCode JavaScript Problems - Coding challenges
- HackerRank JavaScript - Programming challenges
- Codewars - JavaScript kata challenges
- Exercism JavaScript Track - Practice exercises with mentoring