Language: EN

cheatsheet-javascript

JavaScript Cheatsheet

JavaScript is a dynamic and versatile programming language primarily used for web development, but also in servers, mobile applications, and more. This cheatsheet covers everything from the basics to advanced concepts.

Basic Concepts

Variable Declaration

Variables in JavaScript can be declared with let and const.

let name = 'Luis'; // Variable that can change
const age = 20; // Constant, cannot change

Data Types

Primitive Data Types in JavaScript

  • Number: Represents numbers, both integers and decimals.
  • String: Strings of text.
  • Boolean: True (true) or false (false).
  • Null: Absence of value.
  • Undefined: Unassigned value.
  • Symbol: Unique and immutable value.
  • BigInt: For large integers.
let number = 100;
let text = "Hello World";
let isTrue = true;
let noValue = undefined;

Operators

Assignment Operators

  • Assignment =
  • Assignment with operation +=, -=, *=, /=

Arithmetic Operators

  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulus %

Comparison Operators

  • Equality ==
  • Strict equality ===
  • Inequality !=
  • Greater >
  • Less <
console.log(10 + 2); // Addition
console.log(3 === 3); // true

Logical Operators

  • Logical AND &&
  • Logical OR ||
  • Logical NOT !

Functions

Function Declaration

Functions allow encapsulating code that can be reused.

function add(a, b) {
  return a + b;
}

let result = add(5, 7); // Function call

Anonymous Functions and Arrow Functions

const multiply = (x, y) => x * y;

Closures

A closure is a function that remembers the environment in which it was created.

function createCounter() {
  let counter = 0;
  return function() {
    counter++;
    return counter;
  };
}

const counter1 = createCounter();
console.log(counter1()); // 1
console.log(counter1()); // 2

Control Flow

Conditionals

Basic Structure

if (condition) {
  // Code if the condition is true
} else {
  // Code if it is false
}

Ternary Operator

It is a compact way to write conditionals.

let result = (age >= 18) ? 'Adult' : 'Minor';

Loops

For

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

While

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

ForEach

let numbers = [1, 2, 3, 4];
numbers.forEach(number => {
  console.log(number);
});

Objects and Arrays

Object Declaration

An object in JavaScript is a collection of key-value pairs.

let person = {
  name: 'Luis',
  age: 30,
  greet: function() {
    return `Hello, I am ${this.name}`;
  }
};

console.log(person.greet());

Array Declaration

An array is an ordered list of elements.

let fruits = ['Apple', 'Orange', 'Banana'];
console.log(fruits[1]); // Access the second fruit

Useful Array Methods

MethodDescription
push()Adds an element to the end of the array
pop()Removes the last element
shift()Removes the first element
unshift()Adds an element to the beginning
map()Applies a function to each element
filter()Filters elements based on a condition
reduce()Reduces the array to a single value
let numbers = [1, 2, 3, 4];
let doubles = numbers.map(num => num * 2); // [2, 4, 6, 8]

Object-Oriented Programming

Class Declaration

In ES6, classes allow creating objects with methods and properties.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    return `Hello, I am ${this.name}`;
  }
}

let luis = new Person('Luis', 30);
console.log(luis.greet());

Inheritance in Classes

Allows one class to inherit properties and methods from another.

class Student extends Person {
  constructor(name, age, course) {
    super(name, age);
    this.course = course;
  }
  study() {
    return `${this.name} is studying ${this.course}`;
  }
}

let maria = new Student('Maria', 22, 'Mathematics');
console.log(maria.study());

Asynchronous Programming

Callback Functions

A function passed as an argument to another function.

function process(word, callback) {
  console.log(`Processing: ${word}`);
  callback();
}

process('JavaScript', () => console.log('Process completed'));

Promise Handling

Promises handle asynchronous operations.

let promise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve('Success!');
  } else {
    reject('Error');
  }
});

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

Async/Await Syntax

A more readable way to handle promises.

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

DOM and Events

Selecting Elements

let title = document.getElementById('title');
let items = document.querySelectorAll('.item');

Modifying Content

title.textContent = 'New Title';

Modifying Styles

title.style.color = 'blue';

Adding Events to Elements

let button = document.getElementById('button');
button.addEventListener('click', function() {
  alert('Button clicked');
});

Common Operations

Fetch API

Making an HTTP Request

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

JSON

Convert to JSON and from JSON

let object = { name: "Luis", age: 30 };
let json = JSON.stringify(object); // Convert to JSON
let newObject = JSON.parse(json); // Convert from JSON

Modules

Exporting Modules

// file.js
export const PI = 3.14;
export function add(a, b) {
  return a + b;
}

Importing Modules

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