JavaScript Cheat Sheet

JavaScript Cheat Sheet
Getting your Trinity Audio player ready...

JavaScript Basics

JavaScript creates dynamic online experiences. Let’s examine some essential concepts.

Variables store data, declared using var, let, or const:

JavaScript


var a;

let b = 10;

const c = 20;

Numbers offer whole numbers and decimals. Mathematical operations use operators like +, -, *, and /.

Strings hold character sequences:

JavaScript


let shortMessage = 'Hello there';

let longMessage = "Hi, how are you?";

If-else statements control code flow:

JavaScript


if (condition) {

    // Code executes if condition is true

} else {

    // Code executes if condition is false

}

Arrays organize related values:

JavaScript


let colors = ['red', 'green', 'blue'];

Functions are reusable code blocks:

JavaScript


function greet() {

    console.log('Hello World');

}

greet(); // Call the function

Operators like == and === compare values.

Loops execute code repeatedly:

JavaScript


for (let i = 0; i < 5; i++) {

    console.log(i);

}

JavaScript


let i = 0;

while (i < 5) {

    console.log(i);

    i++;

}

Single-line comments use //, while multi-line comments are wrapped in /* comment */.

JavaScript Functions

Functions are reusable code blocks. The syntax for a standard function is:

JavaScript


function add(a, b) {

    return a + b;

}

Function expressions assign functions to variables:

JavaScript


const subtract = function(a, b) {

    return a - b;

};

Arrow functions offer a concise syntax:

JavaScript


const multiply = (a, b) => a * b;

JavaScript’s first-class functions allow them to be treated like any other variable: passed as arguments, returned from other functions, or stored in data structures.

These function types—standard, expression, and arrow—are tools in your coding toolkit. Choose based on your needs to craft efficient code.

DOM Manipulation

DOM manipulation with JavaScript allows dynamic content updates. The Document Object Model is your web page’s blueprint, consisting of nodes ready for modification.

JavaScript provides methods for DOM manipulation:

JavaScript


let heading = document.querySelector('h1');

let buttons = document.querySelectorAll('.btn');
heading.innerHTML = 'Welcome to the Jungle!';

let image = document.querySelector('img');
image.setAttribute('src', 'new-image.jpg');

heading.classList.add('highlight');

let newParagraph = document.createElement('p');
newParagraph.textContent = 'JavaScript is fun!';
document.body.appendChild(newParagraph);

buttons.forEach(button => {
button.addEventListener('click', () => {
console.log('Button clicked!');
});
});

These tools allow you to create engaging, dynamic experiences.

Control Flow: Loops and Conditionals

Control flow guides code execution based on certain conditions.

If-else statements are used for decision-making:

JavaScript


if (weather === 'rainy') {

    console.log("Don't forget your umbrella!");

} else {

    console.log("Sunglasses it is!");

}

The switch statement matches values against multiple cases:

JavaScript


let fruit = 'banana';

switch (fruit) {

    case 'apple':

        console.log('Apples are red or green.');

        break;

    case 'banana':

        console.log('Bananas are yellow.');

        break;

    case 'orange':

        console.log('Oranges are orange!');

        break;

    default:

        console.log('Fruit color unknown.');

}

Loops execute code repeatedly:

JavaScript


for (let i = 0; i < 3; i++) {

    console.log(`Iteration ${i}`);

}
let count = 0;
while (count < 3) {
console.log(`Count is ${count}`);
count++;
}

let number = 0;
do {
console.log(`Number is ${number}`);
number++;
} while (number < 3);

Mastering these control flow techniques allows you to orchestrate code effectively.

Error Handling in JavaScript

Error handling ensures scripts remain stable when unexpected issues arise.

The try-catch block handles potential errors:

JavaScript


try {

    let result = someFunctionThatMightFail();

    console.log(result);

} catch (error) {

    console.error("An error occurred:", error.message);

}

The finally block always executes after a try-catch:

JavaScript


try {

    // Code that might throw an error

} catch (error) {

    // Handling the error

} finally {

    console.log("This will always run.");

}

Custom errors can be created using the throw statement:

JavaScript


function checkAge(age) {

    if (age < 18) {

        throw new Error("You must be at least 18 years old.");

    } else {

        console.log("Access granted.");

    }

}

This system of try-catch-finally helps maintain stable code and build informative applications.

A visual representation of JavaScript error handling techniques, including try-catch blocks, finally statements, and custom error creation

As you progress with JavaScript, focus on understanding its core principles. Each aspect is important for building efficient and dynamic applications. Continue experimenting and improving your skills.

Writio: The ultimate AI writer for website publishers. This article was written by Writio.

  1. Hejlsberg A. TypeScript: JavaScript that scales. Microsoft. 2012.
  2. Flanagan D. JavaScript: The Definitive Guide. 7th ed. O’Reilly Media; 2020.
  3. Simpson K. You Don’t Know JS Yet: Get Started. 2nd ed. Leanpub; 2020.
  4. Haverbeke M. Eloquent JavaScript: A Modern Introduction to Programming. 3rd ed. No Starch Press; 2018.
  5. Mozilla Developer Network. JavaScript. MDN Web Docs. 2021.