Skip to content

Instantly share code, notes, and snippets.

@vicainelli
Last active September 30, 2024 08:45
Show Gist options
  • Save vicainelli/8f71732bc4050bd8a6c1295e5177ecff to your computer and use it in GitHub Desktop.
Save vicainelli/8f71732bc4050bd8a6c1295e5177ecff to your computer and use it in GitHub Desktop.
Most Imporant Javascript commands

Most Imporant Javascript commands

Variables declarations

let x;          // Declare a block-scope variable
const y = 2;    // Declare a block-scope, read-only constant

Functions

function myFunction() {
    // Function declaration
}

const myFunction = () => {
    // Arrow function expression
}

Conditional statements

if (condition) {
    // Execute if condition is true
} else if (otherCondition) {
    // Execute if otherCondition is true
} else {
    // Execute if neither condition is true
}

Loops

for (let i = 0; i < 10; i++) {
    // Foor loop; repeats code while a condition is true
}

while (condition) {
    // While loop; repeats code while a condition is true
}

do {
    // Executes code block at least onde, then repeats while a condition is true
} while (condition);

Array methods

let arr = [1, 2, 3];

arr.push(4);      // Adds a new element to the end of the array
arr.pop();        // Removes the last element from the array
arr.shift();      // Removes the first element from the array
arr.unshift(0);   // Adds a new element to the beginning of the array
arr.splice(2, 1); // Removes a range of elements from the array
arr.reverse();    // Reverses the order of the elements in the array
arr.sort();       // Sorts the elements in the array
arr.slice(2, 5);  // Returns a new array with a subset of the elements

Object methods

let obj = {
    name: 'John',
    age: 30,
};

obj.keys(obj);   // Returns an array of the object's keys
obj.values(obj); // Returns an array of the object's values
obj.entries(obj);// Returns an array of the object's key-value pairs

String methods

let str = 'Hello, world!';

str.length;     // Returns the length of the string
str.toUpperCase();// Converts the string to uppercase
str.toLowerCase();// Converts the string to lowercase
str.includes('o');// Checks if the string includes a specified substring

Dom manipulation

document.getElementById('myElement'); // Selects an element by its ID
document.querySelector('.myClass');   // Selects the first element that matches a specified CSS selector
document.querySelectorAll('.myClass'); // Selects all elements that match a specified CSS selector
document.createElement('div');        // Creates a new element

Event listeners

element.addEventListener('click', function(); // Attaches a click event listener to an element

JSON methods

JSON.stringify(obj); // Converts an object to a JSON string
JSON.parse(str);     // Converts a JSON string to an object

Asynchronous operations

fetch(url)
    .then(response => response.json())      // Performs a network request and returns a promise
    .then(data => console.log(data))   
    .catch(error => console.error(error));  // Catches any errors in the fetch operation

async function fetchData() {
    try {
        const response = await fetch(url);  // Waits for the fetch operation to complete
        const data = await response.json(); // Waits for the response to be parsed as JSON
        console.log(data);
    } catch (error) {
        console.error(error);               // Catches any errors in the fetch operation
    }
}

Date and time

let now = new Date();  // Creates a new Date object
now.getFullYear();     // Returns the year
now.getMonth();        // Returns the month (0-11)
now.getDate();         // Returns the day of the month
now.getHours();        // Returns the hour (0-23)
now.getMinutes();      // Returns the minute (0-59)
now.getSeconds();      // Returns the second (0-59)
now.getMilliseconds(); // Returns the millisecond (0-999)

Math methods

Math.random();  // Returns a random number between 0 and 1
Math.floor(3.7);// Returns the largest integer less than or equal to the given number
Math.ceil(3.7); // Returns the smallest integer greater than or equal to the given number
Math.round(3.7);// Returns the nearest integer to the given number
Math.abs(-3.7); // Returns the absolute value of the given number
Math.sqrt(16);  // Returns the square root of the given number
Math.pow(2, 3); // Returns the result of raising 2 to the power of 3
Math.max(1, 3); // Returns the largest of the given numbers
Math.min(1, 3); // Returns the smallest of the given numbers

Error handling

try {
    // Attempts to execute code that may throw an error
} catch (error) {
    // Handle the error
} finally {
    // Executes code regardless of whether an error was thrown or not
}

Module Impots and Exports

export const myFunction = () => { /* ... */ };  // Exports a function from the current module
import { myFunction } from './myModule';        // Imports a function from another module

JS Class

class Person {
    constructor(name, age) { // Constructor method for initializing an object
        this.name = name;
        this.age = age;
    }

    sayHello() {
        // Method that prints a greeting message
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment