JavaScript Basics
Learn JavaScript programming fundamentals
JavaScript Basics
JavaScript is a versatile programming language used for web development, both on the client and server side. This guide covers the fundamentals of modern JavaScript (ES6+).
Variables
JavaScript has three ways to declare variables:
// var (function-scoped, avoid in modern code)
var oldVariable = "avoid";
// let (block-scoped, can be reassigned)
let name = "JavaScript";
name = "JS"; // OK
// const (block-scoped, cannot be reassigned)
const PI = 3.14159;
// PI = 3.14; // Error!
// Multiple assignment
let x = 1, y = 2, z = 3;
const [a, b, c] = [1, 2, 3]; // Destructuring
Data Types
JavaScript has dynamic typing:
// Primitives
let string = "Hello, World!";
let number = 42;
let float = 3.14;
let boolean = true;
let nullValue = null;
let undefinedValue = undefined;
let symbol = Symbol('unique');
// Template literals (ES6+)
let name = "JavaScript";
let greeting = `Hello, ${name}!`;
let multiline = `This is a
multiline string`;
Arrays
Arrays are ordered collections:
// Creating arrays
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", 3.14, true];
// Accessing elements
fruits[0] // "apple" (first element)
fruits[fruits.length - 1] // "orange" (last element)
fruits.at(-1) // "orange" (ES2022, negative index)
// Adding elements
fruits.push("grape"); // Add to end
fruits.unshift("kiwi"); // Add to beginning
fruits.splice(1, 0, "mango"); // Insert at index
// Removing elements
fruits.pop(); // Remove last
fruits.shift(); // Remove first
fruits.splice(1, 1); // Remove at index
// Array methods
fruits.length // Get length
fruits.includes("apple") // Check if contains
fruits.indexOf("banana") // Find index
fruits.join(", ") // Join with separator
fruits.slice(1, 3) // Get subarray
Objects
Objects are key-value pairs:
// Creating objects
let person = {
name: "John",
age: 30,
city: "New York"
};
// Or with Object constructor
let person2 = new Object();
person2.name = "Jane";
// Accessing properties
person.name // "John"
person["name"] // "John"
person["first name"] // Use brackets for special keys
// Adding/updating
person.email = "john@example.com";
person["age"] = 31;
// Object methods
Object.keys(person) // ["name", "age", "city"]
Object.values(person) // ["John", 30, "New York"]
Object.entries(person) // [["name", "John"], ...]
"name" in person // true
// Destructuring (ES6+)
const { name, age } = person;
const { name: personName, age: personAge } = person;
Loops
JavaScript offers several iteration methods:
let fruits = ["apple", "banana", "orange"];
// For loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// For...of loop (ES6+)
for (let fruit of fruits) {
console.log(fruit);
}
// For...in loop (for objects)
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
// While loop
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// Do...while loop
do {
console.log(count);
count--;
} while (count > 0);
// Array methods
fruits.forEach((fruit, index) => {
console.log(`${index}: ${fruit}`);
});
// Map (transform)
let numbers = [1, 2, 3, 4];
let squared = numbers.map(n => n * n); // [1, 4, 9, 16]
// Filter
let evens = numbers.filter(n => n % 2 === 0); // [2, 4]
// Reduce
let sum = numbers.reduce((acc, n) => acc + n, 0); // 10
Conditionals
Control flow with if/else statements:
// If/else
let age = 20;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}
// Ternary operator
let status = age >= 18 ? "Adult" : "Minor";
// Logical operators
if (age >= 18 && hasLicense) {
console.log("Can drive");
}
if (isWeekend || isHoliday) {
console.log("Day off");
}
if (!isComplete) {
console.log("Not done yet");
}
// Switch statement
let grade = "B";
switch (grade) {
case "A":
console.log("Excellent");
break;
case "B":
console.log("Good");
break;
case "C":
console.log("Average");
break;
default:
console.log("Needs improvement");
}
// Nullish coalescing (ES2020)
let name = username ?? "Guest";
// Optional chaining (ES2020)
let email = person?.contact?.email;
Functions
Functions are first-class citizens in JavaScript:
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const greet2 = function(name) {
return `Hello, ${name}!`;
};
// Arrow function (ES6+)
const greet3 = (name) => {
return `Hello, ${name}!`;
};
// Arrow function (shorthand)
const greet4 = name => `Hello, ${name}!`;
// Default parameters
function greet(name = "World") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((acc, n) => acc + n, 0);
}
sum(1, 2, 3, 4); // 10
// Higher-order functions
function createMultiplier(factor) {
return function(number) {
return number * factor;
};
}
const double = createMultiplier(2);
double(5); // 10
Classes
ES6 introduced class syntax:
// Class definition
class Person {
// Constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance method
introduce() {
return `Hi, I'm ${this.name} and I'm ${this.age} years old`;
}
// Getter
get info() {
return `${this.name} (${this.age})`;
}
// Setter
set age(newAge) {
if (newAge > 0) {
this._age = newAge;
}
}
}
// Creating objects
const person = new Person("John", 30);
console.log(person.introduce());
console.log(person.info);
// Inheritance
class Student extends Person {
constructor(name, age, school) {
super(name, age);
this.school = school;
}
study() {
return `${this.name} is studying at ${this.school}`;
}
}
Modern JavaScript Features
// Destructuring
const [first, second] = [1, 2];
const { name, age } = person;
// Spread operator
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5]; // [1, 2, 3, 4, 5]
const personCopy = { ...person, email: "new@email.com" };
// Template literals
const message = `Hello, ${name}! You are ${age} years old.`;
// Promises
const fetchData = () => {
return new Promise((resolve, reject) => {
// Async operation
setTimeout(() => resolve("Data"), 1000);
});
};
// Async/await
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}