JavaScript Basics
Quick reference guide for JavaScript fundamentals.
Variables and Data Types
JavaScript has three ways to declare variables:
// ========== Variable Declarations ==========
var oldWay = "avoid using var"; // Function-scoped (legacy)
let count = 10; // Block-scoped, can reassign
const PI = 3.14159; // Block-scoped, cannot reassign
// ========== Numbers ==========
let age = 25; // Integer
let price = 19.99; // Float (no separate type)
let distance = 1e6; // Scientific notation (1,000,000)
let infinity = Infinity; // Special number value
let notANumber = NaN; // "Not a Number"
// ========== Strings ==========
let name = "Yudi"; // Double quotes
let message = 'Hello!'; // Single quotes (same as double)
let template = `Hello, ${name}!`; // Template literals (with interpolation)
let multiline = `
This is a
multi-line string
`;
// ========== Booleans ==========
let isActive = true; // lowercase true/false
let hasPermission = false;
// ========== Arrays (ordered, mutable) ==========
let fruits = ["apple", "banana", "orange"];
let mixed = [1, "two", 3.0, true]; // Can mix types
let empty = [];
// ========== Objects (key-value pairs) ==========
let person = {
name: "Yudi",
age: 25,
city: "Jakarta",
"full name": "Yudi Nugraha" // Keys with spaces need quotes
};
// Access: person.name or person["name"] → "Yudi"
// ========== Special Values ==========
let notDefined = undefined; // Variable declared but not assigned
let empty = null; // Intentional absence of value
Type Checking and Conversion
// ========== Type Checking ==========
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (JavaScript quirk!)
typeof []; // "object"
typeof {}; // "object"
// Better array check
Array.isArray([]); // true
Array.isArray({}); // false
// ========== Type Conversion ==========
// To Number
Number("123"); // 123
parseInt("123"); // 123
parseFloat("123.45"); // 123.45
+"123"; // 123 (unary plus)
// To String
String(123); // "123"
(123).toString(); // "123"
123 + ""; // "123"
// To Boolean
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
!!"hello"; // true (double negation)
Operators
// ========== Arithmetic ==========
let sum = 5 + 3; // 8
let difference = 5 - 3; // 2
let product = 5 * 3; // 15
let quotient = 15 / 3; // 5
let remainder = 10 % 3; // 1 (modulo)
let power = 2 ** 3; // 8 (exponentiation)
// ========== Comparison ==========
5 == "5"; // true (loose equality, converts types)
5 === "5"; // false (strict equality, no conversion)
5 != "5"; // false
5 !== "5"; // true (strict inequality)
5 > 3; // true
5 >= 5; // true
// ========== Logical ==========
true && false; // false (AND)
true || false; // true (OR)
!true; // false (NOT)
// ========== Assignment ==========
let x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
// ========== Ternary (shorthand if) ==========
let status = age >= 18 ? "adult" : "minor";
Control Flow
If Statements
let age = 18;
if (age >= 18) {
console.log("Adult");
} else if (age >= 13) {
console.log("Teenager");
} else {
console.log("Child");
}
// Switch statement
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of week");
break;
case "Friday":
console.log("End of week");
break;
default:
console.log("Midweek");
}
Loops
// ========== For Loop ==========
for (let i = 0; i < 5; i++) {
console.log(i);
}
// ========== While Loop ==========
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
// ========== Do-While Loop ==========
let x = 0;
do {
console.log(x);
x++;
} while (x < 5);
// ========== For...of (iterate values) ==========
let fruits = ["apple", "banana", "orange"];
for (let fruit of fruits) {
console.log(fruit);
}
// ========== For...in (iterate keys/indices) ==========
let person = { name: "Yudi", age: 25 };
for (let key in person) {
console.log(key, person[key]);
}
// ========== forEach (array method) ==========
fruits.forEach((fruit, index) => {
console.log(index, fruit);
});
Functions
// ========== Function Declaration ==========
function greet(name) {
return `Hello, ${name}!`;
}
// ========== Function Expression ==========
const add = function(a, b) {
return a + b;
};
// ========== Arrow Function (ES6+) ==========
const multiply = (a, b) => a * b; // Implicit return
const square = x => x * x; // Single param, no parens needed
const sayHi = () => console.log("Hi!"); // No params
// ========== Default Parameters ==========
function power(base, exponent = 2) {
return base ** exponent;
}
// ========== Rest Parameters ==========
function sumAll(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
// ========== Calling Functions ==========
let message = greet("Yudi"); // "Hello, Yudi!"
let result = add(5, 3); // 8
let squared = power(5); // 25 (uses default exponent=2)
let total = sumAll(1, 2, 3, 4, 5); // 15
Array Methods
Modern JavaScript has powerful array methods:
let numbers = [1, 2, 3, 4, 5];
// ========== Map (transform each element) ==========
let doubled = numbers.map(n => n * 2);
// Result: [2, 4, 6, 8, 10]
// ========== Filter (keep elements that match condition) ==========
let evens = numbers.filter(n => n % 2 === 0);
// Result: [2, 4]
// ========== Reduce (combine into single value) ==========
let sum = numbers.reduce((acc, n) => acc + n, 0);
// Result: 15
// ========== Find (get first match) ==========
let found = numbers.find(n => n > 3);
// Result: 4
// ========== Some (check if any match) ==========
let hasEven = numbers.some(n => n % 2 === 0);
// Result: true
// ========== Every (check if all match) ==========
let allPositive = numbers.every(n => n > 0);
// Result: true
// ========== Sort ==========
let sorted = numbers.sort((a, b) => b - a);
// Result: [5, 4, 3, 2, 1] (descending)
// ========== Chaining Methods ==========
let result = numbers
.filter(n => n % 2 === 0)
.map(n => n * 2)
.reduce((acc, n) => acc + n, 0);
// Result: 12 (filter evens [2,4], double [4,8], sum 12)
Object Operations
let person = {
name: "Yudi",
age: 25,
city: "Jakarta"
};
// ========== Access Properties ==========
person.name; // "Yudi" (dot notation)
person["age"]; // 25 (bracket notation)
// ========== Add/Update Properties ==========
person.email = "yudi@example.com";
person.age = 26;
// ========== Delete Properties ==========
delete person.city;
// ========== Object Methods ==========
Object.keys(person); // ["name", "age", "email"]
Object.values(person); // ["Yudi", 26, "yudi@example.com"]
Object.entries(person); // [["name", "Yudi"], ["age", 26], ...]
// ========== Destructuring ==========
let { name, age } = person; // Extract properties to variables
let { name: fullName } = person; // Rename during destructuring
// ========== Spread Operator ==========
let clone = { ...person }; // Shallow copy
let updated = { ...person, age: 27 }; // Copy and update
// ========== Object Shorthand ==========
let name = "Yudi";
let age = 25;
let user = { name, age }; // Same as { name: name, age: age }
// ========== Method Shorthand ==========
let calculator = {
add(a, b) { // Shorthand method
return a + b;
}
};
String Methods
let text = "Hello, World!";
// ========== Case Conversion ==========
text.toLowerCase(); // "hello, world!"
text.toUpperCase(); // "HELLO, WORLD!"
// ========== Search ==========
text.includes("World"); // true
text.startsWith("Hello"); // true
text.endsWith("!"); // true
text.indexOf("World"); // 7 (position)
// ========== Extraction ==========
text.slice(0, 5); // "Hello"
text.substring(7, 12); // "World"
text.split(", "); // ["Hello", "World!"]
// ========== Modification ==========
text.replace("World", "JavaScript"); // "Hello, JavaScript!"
text.trim(); // Remove whitespace from ends
text.padStart(20, "-"); // "-------Hello, World!"
// ========== Template Literals ==========
let name = "Yudi";
let age = 25;
let message = `My name is ${name} and I'm ${age} years old.`;
Modern JavaScript Features (ES6+)
// ========== Destructuring Arrays ==========
let [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]
// ========== Default Values ==========
let { name = "Anonymous", age = 0 } = {};
// name = "Anonymous", age = 0
// ========== Optional Chaining ==========
let user = { profile: { name: "Yudi" } };
user?.profile?.name; // "Yudi"
user?.address?.street; // undefined (no error)
// ========== Nullish Coalescing ==========
let value = null ?? "default"; // "default"
let value2 = 0 ?? "default"; // 0 (only null/undefined trigger ??)
// ========== Promise (async handling) ==========
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
// ========== Async/Await ==========
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
Common Patterns
// ========== Check if value exists ==========
if (value !== null && value !== undefined) {
// Do something
}
// Shorthand:
if (value != null) { } // Only null and undefined are falsy
// ========== Default value ==========
function greet(name) {
name = name || "Guest"; // Old way
name = name ?? "Guest"; // Modern way (better)
return `Hello, ${name}!`;
}
// ========== Guard clauses (early return) ==========
function processUser(user) {
if (!user) return; // Exit early
if (!user.isActive) return;
// Main logic here
console.log("Processing", user.name);
}
// ========== Array deduplication ==========
let numbers = [1, 2, 2, 3, 3, 4];
let unique = [...new Set(numbers)]; // [1, 2, 3, 4]
// ========== Object property existence ==========
let obj = { name: "Yudi" };
"name" in obj; // true
obj.hasOwnProperty("name"); // true
Tips
const by default, let only when reassignment neededvar in modern JavaScript=== instead of == for comparisons