Skip to main content

Basics

Variables & Scope

Variable Declarations

// ES6+ preferred
let name = 'John'; // Block-scoped, reassignable
const age = 25; // Block-scoped, immutable
var oldStyle = 'avoid'; // Function-scoped, hoisted

// Multiple declarations
let x = 1,
y = 2,
z = 3;

Scope Rules

// Block scope
if (true) {
let blockVar = 'only here';
const CONSTANT = 'immutable';
}

// Function scope
function example() {
var functionVar = 'accessible throughout function';
}

Data Types

Primitive Types

// String
let str = 'Hello World';
let template = `Hello ${name}`;

// Number
let int = 42;
let float = 3.14;
let scientific = 1e6;

// Boolean
let isTrue = true;
let isFalse = false;

// Special values
let nothing = null;
let undefined = undefined;
let symbol = Symbol('unique');
let bigInt = 123n;

Type Checking

typeof 'hello'; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof {}; // "object"
typeof []; // "object"
typeof null; // "object" (JavaScript quirk)
typeof undefined; // "undefined"

// Better array check
Array.isArray([]); // true

Useful Built-in Methods

String Methods

str.slice(0, 5); // Extract substring
str.split(','); // Split into array
str.trim(); // Remove whitespace
str.toLowerCase(); // Convert case
str.includes('test'); // Check if contains

Number Methods

Number.isInteger(42); // Check if integer
Number.parseFloat('3.14'); // Parse float
Math.round(3.7); // Round number
Math.random(); // Random 0-1

Date Methods

new Date(); // Current date
Date.now(); // Current timestamp
date.getFullYear(); // Get year
date.toISOString(); // ISO format

Regular Expressions

const regex = /pattern/flags;
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

// Test
emailRegex.test('user@example.com'); // true

// Match
'hello world'.match(/world/); // ['world']
'hello world'.replace(/world/, 'JS'); // 'hello JS'

JSON Operations

// Parse JSON
const obj = JSON.parse('{"name": "John", "age": 30}');

// Stringify
const json = JSON.stringify({ name: 'John', age: 30 });

// Pretty print
const prettyJson = JSON.stringify(obj, null, 2);