Bytes
Web DevelopmentJavaScript

JavaScript Cheat Sheet (Basics to Advanced JS Cheat Sheet)

Last Updated: 10th October, 2024
icon

Jay Abhani

Senior Web Development Instructor at almaBetter

Master JavaScript from basics to advanced with our ultimate JavaScript cheat sheet! Enhance your coding skills and boost productivity with this JS cheat sheet

JavaScript is a versatile and widely-used programming language for web development, from handling basic operations to complex server-side functionalities. In this comprehensive JavaScript cheat sheet, we'll cover essential topics, starting from the basics and moving to more advanced concepts. Along the way, we'll look at JavaScript array methods cheat sheet, JavaScript string methods cheat sheet, and more, making it a useful reference for interviews and solving DSA problems.

Understanding the JavaScript Basics

What is JavaScript?

JavaScript (JS) is a high-level, interpreted programming language, primarily used to add interactivity and functionality to web pages. It's an essential part of the web development triad along with HTML and CSS.

How JavaScript Works

JavaScript runs in the browser and can manipulate HTML elements in real-time. It uses event-driven programming, where user actions like clicking a button trigger specific pieces of code to run.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JavaScript Basics</title>
  </head>
  <body>
    <h1 id="greeting">Hello, World!</h1>
    <button onclick="changeText()">Click me</button>

    <script>
      function changeText() {
        document.getElementById("greeting").innerText = "Hello, JavaScript!";
      }
    </script>
  </body>
</html>

Hello, World!

The first program in any language is typically to print "Hello, World!" in some form. In JavaScript, you can print output using console.log().

console.log("Hello, World!");

Variables and Data Types

Variables

Variables store data that can be manipulated. JavaScript offers three ways to declare variables: var, let, and const.

let name = "John"// Mutable variable
const age = 30;     // Immutable constant
  • var: Function-scoped, can be re-declared and updated.
  • let: Block-scoped, can be updated but not re-declared within the same scope.
  • const: Block-scoped, cannot be updated or re-declared.

Data Types

JavaScript has several data types:

  • Primitive Types: string, number, boolean, null, undefined, symbol
  • Complex Types: object, array, function

Example:

let stringType = "Hello";
let numberType = 25;
let booleanType = true;
let objectType = { name: "John", age: 25 };
let arrayType = [1, 2, 3];

JS Operators

JavaScript provides a variety of operators for performing calculations and comparisons:

Arithmetic Operators

let x = 10;
let y = 5;

console.log(x + y); // Addition
console.log(x - y); // Subtraction
console.log(x * y); // Multiplication
console.log(x / y); // Division
console.log(x % y); // Modulus

Comparison Operators

console.log(10 > 5);  // Greater than
console.log(10 < 5);  // Less than
console.log(10 == 5); // Equal to (abstract comparison)
console.log(10 === 5); // Strict equality
console.log(10 != 5);  // Not equal
console.log(10 !== 5); // Strict inequality

Logical Operators

console.log(true && false); // AND
console.log(true || false); // OR
console.log(!true);         // NOT

Control Structures

Conditional Statements

Use if, else if, and else to execute blocks of code based on conditions.

let age = 18;

if (age < 18) {
  console.log("Underage");
else if (age == 18) {
  console.log("Just turned 18!");
else {
  console.log("Adult");
}

Switch Statements

Use switch to select one of many code blocks to be executed.

let day = 3;

switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Invalid day");
}

Loops

Loops are used to repeat actions:

for Loop

for (let i = 0; i < 5; i++) {
  console.log(i);
}

while Loop

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

Functions

Function Declaration

A function can be defined using the function keyword.

function greet(name) {
  return "Hello, " + name;
}

console.log(greet("John"));

Arrow Functions

Introduced in ES6, arrow functions offer a shorter syntax.

const greet = (name) => "Hello, " + name;
console.log(greet("John"));

JavaScript Array Methods Cheat Sheet

Arrays are used to store multiple values in a single variable. Here’s a quick JS array methods cheat sheet:

let fruits = ["Apple""Banana""Orange"];

push(): Adds an element to the end of an array.

fruits.push("Grapes");

pop(): Removes the last element.

fruits.pop();

shift(): Removes the first element.

fruits.shift();

unshift(): Adds an element to the beginning.

fruits.unshift("Mango");

map(): Returns a new array by applying a function to each element.

let upperFruits = fruits.map(fruit => fruit.toUpperCase());

filter(): Filters elements based on a condition.

let shortFruits = fruits.filter(fruit => fruit.length > 5);

reduce(): Reduces the array to a single value.

let total = [10, 20, 30].reduce((sum, value) => sum + value, 0);

JavaScript String Methods Cheat Sheet

Strings in JavaScript come with a variety of methods. Here's a JavaScript string methods cheat sheet:

let text = "Hello, World!";

charAt(): Returns the character at a specified index.

console.log(text.charAt(0)); // H

includes(): Checks if a string contains another string.

console.log(text.includes("Hello")); // true

substring(): Returns a portion of the string.

console.log(text.substring(0, 5)); // Hello

split(): Splits the string into an array of substrings.

let words = text.split(", ");

replace(): Replaces a substring with a new one.

console.log(text.replace("World""JavaScript")); // Hello, JavaScript!

JavaScript DOM Manipulation Cheat Sheet

DOM (Document Object Model) allows us to manipulate HTML and CSS using JavaScript. Here’s a JavaScript DOM manipulation cheat sheet:

Accessing Elements

getElementById(): Selects an element by ID.

let header = document.getElementById("header");

querySelector(): Selects the first element that matches a CSS selector.

let header = document.querySelector(".header");

Changing Content

innerText: Changes the text content.

header.innerText = "New Heading";

innerHTML: Changes the HTML content.

header.innerHTML = "<h1>New Heading</h1>";

Adding/Removing Classes

classList.add(): Adds a class to an element.

header.classList.add("highlight");

classList.remove(): Removes a class.

header.classList.remove("highlight");

Advanced JavaScript Concepts

Closures

A closure is a function that remembers the variables from the outer scope.

function outerFunction() {
  let outerVariable = "I'm from the outer function";
  return function innerFunction() {
    console.log(outerVariable);
  };
}

let closure = outerFunction();
closure(); // Outputs: I'm from the outer function

Promises and Async/Await

Promises are used for handling asynchronous operations in JavaScript.

let promise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("Promise fulfilled");
  } else {
    reject("Promise rejected");
  }
});

promise.then(result => console.log(result)).catch(error => console.log(error));

Async/await allows us to write asynchronous code in a more readable manner.

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

JavaScript Cheat Sheet for Interview

When preparing for a JavaScript interview, focus on commonly asked questions around arrays, strings, and basic DOM manipulation. Be ready to discuss:

  1. Array manipulation using methods like map(), reduce(), filter().
  2. String manipulation techniques.
  3. Promises, async/await, and their use in handling asynchronous operations.
  4. Basic DOM manipulation using getElementById() and querySelector().

JavaScript DSA Cheat Sheet

For coding interviews, you should also focus on data structures and algorithms (DSA). Key concepts include:

  • Array Sorting: Understand sorting methods like Bubble Sort, Quick Sort, and Merge Sort.
  • Search Algorithms: Binary Search is essential.
  • Data Structures: Familiarize yourself with common structures like stacks, queues, linked lists, trees, and graphs.
  • Recursion: Be prepared to solve problems using recursion.
  • Dynamic Programming: Learn to solve problems like the Fibonacci sequence using dynamic programming.
// Example of recursion for finding factorial
function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5)); // 120

Array Sorting Example

let arr = [5, 3, 8, 1, 2];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3, 5, 8]

Conclusion

JavaScript is a powerful and versatile language that is essential for both front-end and back-end web development. This JavaScript cheat sheet provides a comprehensive overview of the language, from basic syntax and data types to advanced concepts like closures and asynchronous programming. With sections on JavaScript array methods, string methods, and DOM manipulation, this cheat sheet serves as a valuable resource for anyone looking to sharpen their JavaScript skills, whether for personal projects, interviews, or data structures and algorithms (DSA) challenges.

As you dive deeper into JavaScript, remember that practice is key. Use this cheat sheet as a quick reference, but also make sure to apply these concepts in real-world projects and coding exercises. Whether you're preparing for an interview with a JavaScript cheat sheet for interview or mastering concepts for JavaScript DSA, continually honing your skills will keep you ahead in the world of web development.

More Cheat Sheets and Top Picks

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter