JavaScript Cheatsheet - ProX Edition

A comprehensive guide to JavaScript with detailed explanations, practical examples, and best practices for building interactive websites.

What is JavaScript?

JavaScript is a programming language that adds interactivity to websites. It runs in browsers to control webpage behavior, such as updating content, handling user inputs, and communicating with servers.

It works alongside HTML (structure) and CSS (styling) to create dynamic, user-friendly web experiences.

JavaScript Syntax

JavaScript code consists of statements that perform tasks. It uses variables, functions, and logic to manipulate data and interact with users.

console.log("Hello, World!");
let name = "Kanishk";
alert(`Welcome, ${name}!`);

This code logs a message to the console and displays a browser alert with a name.

Variables

Variables store data for later use. JavaScript has three ways to declare variables:

let age = 25;
const name = "Kanishk";
age = 26; // Works
// name = "John"; // Error: Cannot reassign const
console.log(name, age);

This declares a changeable age and a fixed name, then logs them.

Data Types

JavaScript has several data types to represent different kinds of values:

let num = 100;
let text = "JavaScript";
let isActive = true;
let list = [1, 2, 3];
let person = { name: "Kanishk", age: 15 };
let empty = null;

This shows different data types assigned to variables.

Functions

Functions are reusable blocks of code that perform specific tasks. They can take inputs (parameters) and return outputs.

Function Declaration

function greet(name) {
  return `Hello, ${name}!`;
}
console.log(greet("Kanishk"));

Arrow Function (ES6)

const add = (a, b) => a + b;
console.log(add(5, 3)); // 8

The first example greets a user, while the second adds two numbers using a concise arrow function.

Arrays

Arrays store ordered lists of data. They come with methods to manipulate the list.

let fruits = ["apple", "banana"];
fruits.push("orange");
fruits.pop();
console.log(fruits); // ["apple", "banana"]
let doubled = fruits.map(item => item.toUpperCase());
console.log(doubled); // ["APPLE", "BANANA"]

This adds and removes items from an array and transforms it.

Objects

Objects store data as key-value pairs, ideal for structured information.

const user = {
  name: "Kanishk",
  age: 15,
  greet() {
    return `Hi, I'm ${this.name}`;
  }
};
console.log(user.name); // Kanishk
console.log(user.greet()); // Hi, I'm Kanishk

This creates an object with properties and a method, then accesses them.

Conditionals

Conditionals control program flow based on conditions using if, else, or switch.

let age = 15;
if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Minor");
}

This checks if a user is an adult or minor based on age.

Loops

Loops repeat code until a condition is met. Common types include for, while, and forEach.

for (let i = 0; i < 3; i++) {
  console.log(i); // 0, 1, 2
}
let numbers = [1, 2, 3];
numbers.forEach(num => console.log(num));

This demonstrates a for loop and a forEach loop for arrays.

DOM Manipulation

The Document Object Model (DOM) lets JavaScript interact with HTML elements.

const title = document.getElementById("title");
title.innerHTML = "Welcome!";
title.style.color = "blue";

This changes the text and color of an element with ID title.

Events

Events handle user actions like clicks, keypresses, or mouse movements.

const button = document.querySelector("button");
button.addEventListener("click", () => {
  alert("Button clicked!");
});

This shows an alert when a button is clicked.

Async JavaScript

Asynchronous JavaScript handles tasks like fetching data without blocking the program.

Promises

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("Success!"), 1000);
});
myPromise.then(result => console.log(result));

Async/Await

async function fetchData() {
  let response = await fetch("https://api.example.com/data");
  let data = await response.json();
  console.log(data);
}

These examples show a Promise resolving after 1 second and an async function fetching data.

Error Handling

Use try/catch to handle errors gracefully.

try {
  let data = JSON.parse("invalid json");
} catch (error) {
  console.error("Error:", error.message);
}

This catches and logs an error when parsing invalid JSON.

Modules

Modules organize code by splitting it into reusable files.

// math.js
export const add = (a, b) => a + b;

// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5

This exports a function from one file and imports it in another.

ES6 Features

ES6 (ECMAScript 2015) introduced modern JavaScript features.

const [a, b] = [1, 2];
const { name, age } = { name: "Kanishk", age: 15 };
console.log(a, b, name, age); // 1, 2, Kanishk, 15

This demonstrates destructuring to extract values.

JSON

JSON (JavaScript Object Notation) is a format for storing and exchanging data.

const jsonString = '{"name": "Kanishk", "age": 15}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Kanishk
const backToJson = JSON.stringify(obj);
console.log(backToJson);

This converts JSON to an object and back to JSON.

Fetch API

The Fetch API makes HTTP requests to fetch data from servers.

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error:", error));

This fetches data from an API and logs it, handling errors if they occur.

Best Practices

Write clean, efficient, and maintainable JavaScript with these tips: