0% found this document useful (0 votes)
364 views5 pages

Modern JavaScript Cheat Sheet PDF

This document provides a cheat sheet overview of modern JavaScript concepts including variables, data types, arrays, array functions, objects, functions, arrow functions, template literals, destructuring, loops, conditional statements, promises, async/await, the Fetch API, and DOM selection and manipulation. It contains code examples for working with each concept.

Uploaded by

mukta.sairatna1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
364 views5 pages

Modern JavaScript Cheat Sheet PDF

This document provides a cheat sheet overview of modern JavaScript concepts including variables, data types, arrays, array functions, objects, functions, arrow functions, template literals, destructuring, loops, conditional statements, promises, async/await, the Fetch API, and DOM selection and manipulation. It contains code examples for working with each concept.

Uploaded by

mukta.sairatna1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Variables
  • Data Types
  • Arrays
  • Objects
  • Array Functions
  • Functions
  • Destructuring
  • Arrow Functions
  • Template Literals
  • Promises
  • Conditional Statements
  • Async/Await
  • Loops
  • Fetch API
  • DOM Selection and Manipulation

Modern JavaScript Cheat Sheet

Table of Contents
▪ Variables
▪ Data Types
▪ Arrays
▪ Array Functions
▪ Objects
▪ Functions
▪ Arrow Functions
▪ Template Literals
▪ Destructuring
▪ Loops
▪ Conditional Statements
▪ Promises
▪ Async/Await
▪ Fetch API
▪ DOM Selection and Manipulation

1. Variables

let variableName = "Hello, JavaScript!";


const constantValue = 42;

2. Data Types

// String, Number, Boolean


const name = "Najem";
const age = 25;
const isStudent = true;

// Array, Object
const colors = ['red', 'green', 'blue'];
const person = { name: 'John', age: 30 };

// null, undefined
let value1 = null;
let value2;

Modern JavaScript Cheat Sheet 1


3. Arrays

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

// Access element
const firstColor = colors[0]; // 'red'

// Add an element
[Link]('yellow'); // ['red', 'green', 'blue', 'yellow']

// Loop through elements


for (const color of colors) {
[Link](color);
}

4. Array Functions

// Map
const numbers = [1, 2, 3, 4, 5];
const doubled = [Link]((num) => num * 2); // [2, 4, 6, 8, 10]

// Filter
const evenNumbers = [Link]((num) => num % 2 === 0); // [2, 4]

// Reduce
const sum = [Link]((acc, num) => acc + num, 0); // 15

// forEach
[Link]((color) => [Link](color));
// Output:
// 'red'
// 'green'
// 'blue'

// find and findIndex


const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' },
];
const user = [Link]((user) => [Link] === 2); // { id: 2, name: 'Bob' }
const userIndex = [Link]((user) => [Link] === 2); // 1

5. Objects

const person = {
name: 'John',
age: 30,
};

2 Modern JavaScript Cheat Sheet


// Access property
const name = [Link]; // 'John'

// Add a new property


[Link] = 'New York';

// Loop through properties


for (const key in person) {
[Link](key, person[key]);
}
// 'name' 'John'
// 'age' 30
// 'city' 'New York'

6. Functions

function greet(name) {
return `Hello, ${name}!`;
}

// Function expression
const add = function (a, b) {
return a + b;
};

// Arrow function
const multiply = (a, b) => a * b;

7. Arrow Functions

const square = (x) => x * x;


const double = (x) => {
return x * 2;
};

8. Template Literals

const name = 'Alice';


const greeting = `Hello, ${name}!`; // 'Hello, Alice!'

9. Destructuring

const person = { name: 'Bob', age: 25 };


const { name, age } = person; // name = 'Bob', age = 25

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


const [first, second] = colors; // first = 'red', second = 'green'

Modern JavaScript Cheat Sheet 3


10. Loops

// For Loop
for (let i = 0; i < 5; i++) {
[Link](i);
}
// For...of Loop
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
[Link](color);
}

11. Conditional Statements

const age = 18;

if (age >= 18) {


[Link]('You are an adult.'); // 'You are an adult.'
} else {
[Link]('You are a minor.');
}

12. Promises

const fetchData = () => {


return new Promise((resolve, reject) => {
// Async operation
if (success) {
resolve(data);
} else {
reject(error);
}
});
};

13. Async/Await

async function getData() {


try {
const response = await fetchData();
[Link](response);
} catch (error) {
[Link](error);
}
}

4 Modern JavaScript Cheat Sheet


14. Fetch API

fetch('[Link]
.then((response) => [Link]())
.then((data) => [Link](data))
.catch((error) => [Link](error));

15. DOM Selection and Manipulation

Selecting Elements

const elementById = [Link]('elementId');


const elementsByClass = [Link]('className');
const elementsByTag = [Link]('tagName');
const elementBySelector = [Link]('CSSSelector');
const elementsBySelectorAll = [Link]('CSSSelector');

Manipulating Elements

// Changing text content


[Link] = 'New Text';

// Changing HTML content


[Link] = '<strong>New HTML</strong>';

// Adding/removing CSS classes


[Link]('newClass');
[Link]('oldClass');

// Creating new elements


const newElement = [Link]('tagName');

// Appending elements
[Link](newElement);

// Removing elements
[Link](childElement);

// Event handling
[Link]('click', (event) => {
// Handle click event
});

Modern JavaScript Cheat Sheet 5

Common questions

Powered by AI

Arrow functions in JavaScript offer a more concise syntax compared to traditional function expressions. Unlike function expressions, they do not require the 'function' keyword and curly braces for simple return statements, allowing single-line expressions to produce a result implicitly without the 'return' keyword. For example, 'const multiply = (a, b) => a * b;' has the same outcome as 'const multiply = function(a, b) { return a * b; };' . This makes arrow functions particularly suitable for inline and simple operations, enhancing code readability and efficiency.

JavaScript's DOM manipulation techniques enable dynamic updates to webpage content by providing methods to select and modify HTML elements. Selection can be done using methods like 'document.getElementById()', 'getElementsByClassName()', 'querySelector()', and others, which allow targeting specific elements. Once selected, elements can be manipulated using properties like 'textContent' for changing text, 'innerHTML' for altering HTML content, and classList methods for adding or removing CSS classes. Additionally, new elements can be created and inserted into the DOM tree with 'createElement()' and 'appendChild()', while event handlers like 'addEventListener()' can react to user actions . These capabilities help build interactive and responsive web applications.

Conditional statements in JavaScript, such as 'if...else' and 'switch', allow developers to control the program flow based on specific criteria. The 'if...else' statement executes code blocks conditionally based on Boolean expressions, where 'if' specifies the condition, and 'else' provides code execution for when the condition is false. For example, 'if (age >= 18) { console.log('You are an adult.'); } else { console.log('You are a minor.'); }' checks if a person is an adult. 'Switch' statements provide an alternative for multiple conditionals by evaluating an expression against a series of cases, offering a clearer structure where a single variable's value determines the executed path. These structures allow for flexible and powerful decision-making processes in JavaScript code .

The 'for...of' loop in JavaScript provides a simpler and more readable syntax for iterating over iterable objects, such as arrays, by directly accessing each element sequentially without needing to manage an index counter. This contrasts with the traditional 'for' loop, where indexes, conditions, and increment expressions must be explicitly defined. For example, iterating over an array 'colors' with 'for (const color of colors) { console.log(color); }' avoids common errors associated with index management and renders the intent clearer compared to 'for (let i = 0; i < colors.length; i++) { console.log(colors[i]); }' .

Promises in JavaScript provide a structured way to handle asynchronous operations without getting into callback hell, which occurs with deeply nested callbacks. They allow sequential execution of tasks after the successful completion of a previous task using '.then()' and handling errors with '.catch()', resulting in cleaner and more manageable code . However, promises can introduce complexity in terms of understanding their chain flow, especially when dealing with multiple asynchronous operations. Additionally, incorrect handling of promise rejections may lead to unhandled promise errors, requiring careful coding practices to ensure reliability and correctness of error handling.

The Fetch API in JavaScript offers a modern mechanism for making HTTP requests to servers, replacing the older XMLHttpRequest. It returns promises, simplifying the handling of request success and failure states. A basic fetch operation involves using the fetch() method, which returns a promise that resolves to the Response object. Developers can chain '.then()' methods to process the response, usually converting it to JSON with 'response.json()', and handle errors using '.catch()', allowing them to separate success processing from error processing more clearly. Despite its powerful features, the Fetch API requires manual inspection of response.ok to check for HTTP errors since it only rejects the promise on network failure, not server-level errors . Its ability to handle a wide range of HTTP methods and customize headers and body content makes it an integral part of modern web development.

The 'reduce' method in JavaScript arrays facilitates complex aggregation problems by iterating over each element of an array and accumulating a single resultant value based on the provided callback function. This method can be adapted to various contexts such as summing values, flattening arrays, counting occurrences, and more. For instance, calculating the sum of an array of numbers could be performed as 'const sum = numbers.reduce((acc, num) => acc + num, 0);'. This framework is extensible to more complex scenarios like mapping and filtering operations simultaneously or even implementing stateful operations when combination logic is required beyond simple summation . The customization offered by the initial accumulator signature and the flexibility of the function logic applied make 'reduce' a powerful utility in data transformation.

Destructuring in JavaScript enhances the handling of objects and arrays by allowing developers to extract multiple properties or elements efficiently in a single statement, improving code readability and reducing the need for repetitive code. For example, given an object 'const person = { name: 'Bob', age: 25 };', destructuring lets us extract both properties succinctly: 'const { name, age } = person;' instead of accessing 'person.name' and 'person.age' separately. This approach is mirrored in arrays, where elements can be extracted in order with a syntax like 'const [first, second] = colors;' for array 'colors = ['red', 'green'];' . Destructuring reduces syntax verbosity and prevents errors associated with manual property access.

JavaScript's 'async/await' syntax significantly improves asynchronous code readability by allowing asynchronous code to be written in a synchronous style, thus avoiding deeply nested promise chains. The 'async' keyword before a function automatically returns a promise, and 'await' pauses the execution inside an 'async' function until the promise is resolved, enabling linear and manageable code flow. For example, using 'await' allows fetching data like 'const response = await fetchData();' instead of attaching multiple '.then()' calls to handle intermediary states of async operations . This results in code that is easier to read, understand, and debug.

JavaScript's template literals simplify dynamic string creation by allowing expressions to be embedded directly using `${expression}` syntax within backticks. This contrasts with traditional string concatenation, which requires explicit joining of strings and variables using the '+' operator. Template literals support multi-line strings without needing escape characters for new lines, thus reducing syntax overhead and improving readability. For instance, 'const greeting = `Hello, ${name}!`;' is easier to read and maintain than 'const greeting = 'Hello, ' + name + '!';' .

Modern JavaScript Cheat Sheet
Table of Contents
▪Variables
▪Data Types
▪Arrays
▪Array Functions
▪Objects
▪Functions
▪Arrow Fu
3. Arrays
4. Array Functions
5. Objects
const colors = ['red', 'green', 'blue'];
// Access element
const firstColor = colors[
6. Functions
7. Arrow Functions
8. Template Literals
9. Destructuring
// Access property
const name = person.name; // 'John'
10. Loops
11. Conditional Statements
12. Promises
13. Async/Await
// For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
14. Fetch API
15. DOM Selection and Manipulation
Selecting Elements
Manipulating Elements
fetch('https://api.example.com/data

You might also like