Essential JavaScript Cheat Sheet

Essential JavaScript Cheat Sheet

Once you have set up Node.js, it's crucial to have a solid foundation in JavaScript to ease your journey with Node.js. This blog post or cheat sheet provides an in-depth overview of JavaScript to help you get started. For more detailed information, refer to the official documentation or watch tutorials on platforms such as YouTube.

1. Variables and Data Types

JavaScript provides three ways to declare variables: var, let, and const. Understanding when to use each is crucial.

Variable Declarations

  • var: Function-scoped variable declaration.

      var name = "Adarsh";
      function greet() {
          var message = "Hello, " + name;
          console.log(message);
      }
      greet(); // Hello, Adarsh
    
  • let: Block-scoped variable declaration; use when the variable's value will change.

      let age = 25;
      if (age > 20) {
          let isAdult = true;
          console.log(isAdult); // true
      }
      // console.log(isAdult); // Error: isAdult is not defined
    
  • const: Block-scoped constant; use when the variable's value will remain constant.

      const birthYear = 1998;
      // birthYear = 1999; // Error: Assignment to constant variable.
    

Data Types

JavaScript supports several data types including strings, numbers, booleans, arrays, and objects.

  • String: A sequence of characters.

      let greeting = "Hello, Adarsh!";
    
  • Number: Any numerical value.

      let age = 25;
      let temperature = 36.6;
    
  • Boolean: Represents true or false.

      let isJavaScriptFun = true;
    
  • Array: An ordered list of values.

      let colors = ["red", "green", "blue"];
    
  • Object: A collection of key-value pairs.

      let person = {
          name: "Adarsh",
          age: 25
      };
    

2. Operators

JavaScript supports various operators for performing operations.

Arithmetic Operators

Used for basic mathematical operations:

let x = 10;
let y = 5;
console.log(x + y); // 15
console.log(x - y); // 5
console.log(x * y); // 50
console.log(x / y); // 2

Comparison Operators

Used to compare values:

console.log(x === y); // false
console.log(x !== y); // true
console.log(x < y); // false
console.log(x > y); // true

Logical Operators

Used for logical operations:

let a = true;
let b = false;
console.log(a && b); // false
console.log(a || b); // true
console.log(!a); // false

3. Control Flow

Mastering control flow allows you to control the execution of your code.

Conditional Statements

Used to perform different actions based on different conditions:

let age = 25;
if (age < 18) {
    console.log("Minor");
} else if (age < 65) {
    console.log("Adult");
} else {
    console.log("Senior");
}

Loops

Used to perform repeated tasks:

  • for loop:

      for (let i = 0; i < 5; i++) {
          console.log(i); // Prints 0 to 4
      }
    
  • while loop:

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

4. Functions

Functions are the building blocks of JavaScript, used to perform tasks or calculate values.

Function Declaration

A named function that can be called anywhere in the scope:

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

Function Expression

A function stored in a variable:

const add = function(a, b) {
    return a + b;
};
console.log(add(2, 3)); // 5

Arrow Functions

A shorter syntax for function expressions (introduced in ES6):

const subtract = (a, b) => a - b;
console.log(subtract(5, 2)); // 3

5. Objects and Arrays

Working with objects and arrays is a common task in JavaScript.

Objects

Used to store collections of data:

let person = {
    name: "Adarsh",
    age: 25,
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};
person.greet(); // Hello, my name is Adarsh

Arrays

Used to store multiple values in a single variable:

let colors = ["red", "green", "blue"];
colors.push("yellow"); // Adds "yellow" to the end
console.log(colors[0]); // red
colors.forEach(color => console.log(color)); // Prints all colors

6. Scope and Closures

Understanding variable scope and closures is crucial for writing maintainable and efficient code.

Scope

The context in which variables are accessible:

let globalVar = "I'm global";

function checkScope() {
    let localVar = "I'm local";
    console.log(globalVar); // Accessible
    console.log(localVar); // Accessible
}

checkScope();
// console.log(localVar); // Error: localVar is not defined

Closures

Functions that have access to the parent scope, even after the parent function has closed:

function outerFunction() {
    let outerVar = "I'm outside!";

    function innerFunction() {
        console.log(outerVar); // Can access outerVar
    }

    return innerFunction;
}

const closure = outerFunction();
closure(); // I'm outside!

7. Asynchronous JavaScript

Grasp the basics of asynchronous programming, including callbacks, promises, and async/await.

Callbacks

Functions passed as arguments to other functions:

function fetchData(callback) {
    setTimeout(() => {
        callback("Data received");
    }, 2000);
}

fetchData(data => {
    console.log(data); // Data received
});

Promises

Used to handle asynchronous operations:

let promise = new Promise((resolve, reject) => {
    let success = true;
    if (success) {
        resolve("Operation successful");
    } else {
        reject("Operation failed");
    }
});

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

Async/Await

Syntactic sugar over promises for asynchronous code:

async function fetchData() {
    let promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve("Data received"), 2000);
    });

    let result = await promise;
    console.log(result); // Data received
}

fetchData();

8. ES6+ Features

Modern JavaScript features introduced in ES6 and later.

Destructuring

Extract values from arrays or properties from objects:

const user = { name: "Adarsh", age: 25 };
const { name, age } = user; // Destructuring
console.log(`Name: ${name}, Age: ${age}`); // Name: Adarsh, Age: 25

const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first); // red

Template Literals

String literals allowing embedded expressions:

const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Adarsh!

Default Parameters

Set default values for function parameters:

function greet(name = "Guest") {
    console.log(`Hello, ${name}!`);
}
greet(); // Hello, Guest!
greet("Adarsh"); // Hello, Adarsh!

9. DOM Manipulation

Interact with the Document Object Model (DOM) to manipulate HTML elements and handle events.

Selecting Elements

Use methods like getElementById, querySelector, and querySelectorAll:

//getElementById: Selects an element by its ID attribute.
const header = document.getElementById("header");
//querySelector: Selects the first element that matches a CSS selector.
const buttons = document.querySelectorAll(".btn");
//querySelectorAll: Selects all elements that match a CSS selector.
const buttons = document.querySelectorAll('.btn');

Modifying Elements

Change the content or attributes of elements:

header.textContent = "Welcome, Adarsh!";
buttons.forEach(button => button.style.backgroundColor = "blue");

Handling Events

Add event listeners to elements:

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

10. Error Handling

Become proficient in handling errors using try...catch blocks and understanding how to throw and catch exceptions.

Try...Catch

Handle errors gracefully:

try {
    let result = riskyOperation();
} catch (error) {
    console.error("An error occurred:", error);
}

Throwing Errors

Generate custom errors:

function checkAge(age) {
    if (age < 18) {
        throw new Error("Must be at least 18 years old");
    }
    return true;
}

try {
    checkAge(16);
} catch (error) {
    console.error(error.message); // Must be at least 18 years old
}

11. JSON (JavaScript Object Notation)

Understand the basics of JSON, a lightweight data interchange format widely used in web development.

Parsing JSON

Convert a JSON string to a JavaScript object:

const jsonString = '{"name": "Adarsh", "age": 25}';
const user = JSON.parse(jsonString);
console.log(user.name); // Adarsh

Stringifying JSON

Convert a JavaScript object to a JSON string:

const user = { name: "Adarsh", age: 25 };
const jsonString = JSON.stringify(user);
console.log(jsonString); // {"name":"Adarsh","age":25}

This post hopefully covers everything and provides a concise overview of essential JavaScript concepts. For deeper learning and mastery, explore the official documentation or dive into tutorials on platforms like YouTube.