0% found this document useful (0 votes)
208 views30 pages

JavaScript Cheatsheet Guide

This document is a comprehensive JavaScript cheatsheet and theory guide covering essential topics such as JavaScript basics, variables, functions, control structures, objects, arrays, DOM manipulation, events, asynchronous JavaScript, ES6+ features, and common methods. It provides code examples and explanations for each topic, making it a valuable resource for both beginners and experienced developers. The guide also includes best practices and a quick reference cheatsheet for easy access to key concepts.

Uploaded by

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

JavaScript Cheatsheet Guide

This document is a comprehensive JavaScript cheatsheet and theory guide covering essential topics such as JavaScript basics, variables, functions, control structures, objects, arrays, DOM manipulation, events, asynchronous JavaScript, ES6+ features, and common methods. It provides code examples and explanations for each topic, making it a valuable resource for both beginners and experienced developers. The guide also includes best practices and a quick reference cheatsheet for easy access to key concepts.

Uploaded by

Kushal gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVASCRIPT CHEATSHEET AND THEORY GUIDE

===============================================

TABLE OF CONTENTS

=================

1. JavaScript Basics

2. Variables and Data Types

3. Functions

4. Control Structures

5. Objects and Arrays

6. DOM Manipulation

7. Events

8. Asynchronous JavaScript

9. ES6+ Features

10. Common Methods and Properties

11. Best Practices

12. Quick Reference Cheatsheet

===============================================

1. JAVASCRIPT BASICS

====================

What is JavaScript?

-------------------

JavaScript is a high-level, interpreted programming language that enables interactive web


pages. It's an essential part of web applications alongside HTML and CSS.
Key Features:

- Dynamic typing

- Prototype-based object orientation

- First-class functions

- Event-driven programming

- Client-side and server-side execution

How to Include JavaScript:

--------------------------

<!-- Inline JavaScript -->

<script>

[Link]("Hello, World!");

</script>

<!-- External JavaScript file -->

<script src="[Link]"></script>

<!-- Modern way with defer -->

<script src="[Link]" defer></script>

===============================================

2. VARIABLES AND DATA TYPES

============================

Variable Declarations:

----------------------

// ES5 way
var name = "John";

// ES6+ way (preferred)

let age = 25;

const PI = 3.14159;

Differences:

- var: Function-scoped, can be redeclared, hoisted

- let: Block-scoped, cannot be redeclared, hoisted but not initialized

- const: Block-scoped, cannot be reassigned or redeclared

Data Types:

-----------

Primitive Types:

1. String: "Hello", 'World', `Template literal`

2. Number: 42, 3.14, Infinity, NaN

3. Boolean: true, false

4. Undefined: undefined

5. Null: null

6. Symbol (ES6): Symbol('id')

7. BigInt (ES2020): 123n

Non-Primitive Types:

1. Object: {}, {name: "John", age: 30}

2. Array: [], [1, 2, 3]

3. Function: function() {}, () => {}

Type Checking:
--------------

typeof "Hello" // "string"

typeof 42 // "number"

typeof true // "boolean"

typeof undefined // "undefined"

typeof null // "object" (known quirk)

typeof {} // "object"

typeof [] // "object"

typeof function() {} // "function"

[Link]([]) // true

[Link]({}) // false

===============================================

3. FUNCTIONS

============

Function Declaration:

---------------------

function greet(name) {

return "Hello, " + name + "!";

Function Expression:

--------------------

const greet = function(name) {

return "Hello, " + name + "!";


};

Arrow Functions (ES6):

----------------------

const greet = (name) => {

return "Hello, " + name + "!";

};

// Shorthand for single expression

const greet = name => "Hello, " + name + "!";

// Multiple parameters

const add = (a, b) => a + b;

// No parameters

const sayHello = () => "Hello!";

Function Parameters:

--------------------

// Default parameters

function greet(name = "World") {

return "Hello, " + name + "!";

// Rest parameters

function sum(...numbers) {

return [Link]((total, num) => total + num, 0);

}
// Destructuring parameters

function greet({name, age}) {

return `Hello, ${name}! You are ${age} years old.`;

Higher-Order Functions:

-----------------------

// Function that takes another function as parameter

function execute(fn, value) {

return fn(value);

// Function that returns another function

function createMultiplier(factor) {

return function(number) {

return number * factor;

};

const double = createMultiplier(2);

[Link](double(5)); // 10

===============================================

4. CONTROL STRUCTURES

======================
Conditional Statements:

-----------------------

// if-else

if (condition) {

// code

} else if (anotherCondition) {

// code

} else {

// code

// Ternary operator

const result = condition ? valueIfTrue : valueIfFalse;

// Switch statement

switch (value) {

case 'option1':

// code

break;

case 'option2':

// code

break;

default:

// code

Loops:

------
// for loop

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

[Link](i);

// for...in (for object properties)

for (let key in object) {

[Link](key, object[key]);

// for...of (for iterable values)

for (let value of array) {

[Link](value);

// while loop

while (condition) {

// code

// do...while loop

do {

// code

} while (condition);

// forEach (array method)

[Link]((item, index) => {

[Link](index, item);
});

Loop Control:

-------------

break; // Exit loop

continue; // Skip to next iteration

===============================================

5. OBJECTS AND ARRAYS

======================

Objects:

--------

// Object literal

const person = {

name: "John",

age: 30,

greet: function() {

return "Hello, I'm " + [Link];

};

// Accessing properties

[Link]([Link]); // Dot notation

[Link](person['name']); // Bracket notation

// Adding properties
[Link] = "john@[Link]";

person['phone'] = "123-456-7890";

// Deleting properties

delete [Link];

// Object methods

[Link](person); // Returns array of keys

[Link](person); // Returns array of values

[Link](person); // Returns array of [key, value] pairs

// Object destructuring

const {name, age} = person;

// Object spread operator

const newPerson = {...person, city: "New York"};

Arrays:

-------

// Array literal

const fruits = ["apple", "banana", "orange"];

// Array constructor

const numbers = new Array(1, 2, 3, 4, 5);

// Accessing elements

[Link](fruits[0]); // "apple"

[Link]([Link]); // 3
// Common array methods

[Link]("grape"); // Add to end

[Link](); // Remove from end

[Link]("mango"); // Add to beginning

[Link](); // Remove from beginning

[Link](1, 1, "kiwi"); // Remove/replace elements

// Array iteration methods

[Link](fruit => [Link](fruit));

const upperFruits = [Link](fruit => [Link]());

const longFruits = [Link](fruit => [Link] > 5);

const totalLength = [Link]((sum, fruit) => sum + [Link], 0);

// Array destructuring

const [first, second, ...rest] = fruits;

// Array spread operator

const moreFruits = [...fruits, "pineapple", "watermelon"];

===============================================

6. DOM MANIPULATION

====================

Selecting Elements:

-------------------

// By ID
const element = [Link]('myId');

// By class name

const elements = [Link]('myClass');

// By tag name

const elements = [Link]('div');

// Query selector (CSS selectors)

const element = [Link]('.myClass');

const elements = [Link]('.myClass');

Modifying Elements:

-------------------

// Content

[Link] = "New text";

[Link] = "<strong>Bold text</strong>";

// Attributes

[Link]('class', 'newClass');

[Link]('class');

[Link]('class');

// Properties

[Link] = "newId";

[Link] = "newClass";

[Link] = "newValue"; // for form elements


// Style

[Link] = "red";

[Link] = "blue";

[Link] = "none";

// Classes

[Link]('newClass');

[Link]('oldClass');

[Link]('activeClass');

[Link]('someClass');

Creating and Removing Elements:

-------------------------------

// Create element

const newDiv = [Link]('div');

[Link] = "Hello World";

// Append to parent

[Link](newDiv);

// Insert before element

[Link](newDiv, existingElement);

// Remove element

[Link]();

// or

[Link](element);
===============================================

7. EVENTS

==========

Event Listeners:

----------------

// Add event listener

[Link]('click', function(event) {

[Link]('Element clicked!');

});

// Arrow function

[Link]('click', (event) => {

[Link]('Element clicked!');

});

// Remove event listener

[Link]('click', handlerFunction);

Common Events:

--------------

- click: Mouse click

- mouseover/mouseout: Mouse hover

- mouseenter/mouseleave: Mouse enter/leave

- keydown/keyup: Keyboard events

- submit: Form submission

- load: Page/image loading


- resize: Window resize

- scroll: Page scrolling

Event Object:

-------------

[Link]('click', (event) => {

[Link](); // Prevent default behavior

[Link](); // Stop event bubbling

[Link]([Link]); // Element that triggered event

[Link]([Link]); // Event type

});

Event Delegation:

-----------------

// Handle events for dynamically created elements

[Link]('click', (event) => {

if ([Link]('button')) {

[Link]('Button clicked!');

});

===============================================

8. ASYNCHRONOUS JAVASCRIPT

===========================

Callbacks:

----------
function fetchData(callback) {

setTimeout(() => {

const data = "Some data";

callback(data);

}, 1000);

fetchData((data) => {

[Link](data);

});

Promises:

---------

// Creating a promise

const myPromise = new Promise((resolve, reject) => {

const success = true;

if (success) {

resolve("Operation successful!");

} else {

reject("Operation failed!");

});

// Using promises

myPromise

.then(result => [Link](result))

.catch(error => [Link](error))

.finally(() => [Link]("Promise completed"));


// Promise methods

[Link]([promise1, promise2]) // Wait for all

[Link]([promise1, promise2]) // First to complete

[Link](value) // Resolved promise

[Link](error) // Rejected promise

Async/Await:

------------

async function fetchData() {

try {

const response = await fetch('[Link]

const data = await [Link]();

return data;

} catch (error) {

[Link]('Error:', error);

// Using async function

fetchData().then(data => [Link](data));

Fetch API:

----------

// GET request

fetch('[Link]

.then(response => [Link]())

.then(data => [Link](data));


// POST request

fetch('[Link] {

method: 'POST',

headers: {

'Content-Type': 'application/json',

},

body: [Link]({name: 'John', age: 30})

})

.then(response => [Link]())

.then(data => [Link](data));

===============================================

9. ES6+ FEATURES

=================

Template Literals:

------------------

const name = "John";

const age = 30;

const message = `Hello, my name is ${name} and I'm ${age} years old.`;

Destructuring:

--------------

// Array destructuring

const [a, b, c] = [1, 2, 3];

const [first, , third] = [1, 2, 3]; // Skip second element


// Object destructuring

const {name, age} = person;

const {name: userName, age: userAge} = person; // Rename

Spread Operator:

----------------

// Arrays

const arr1 = [1, 2, 3];

const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Objects

const obj1 = {a: 1, b: 2};

const obj2 = {...obj1, c: 3}; // {a: 1, b: 2, c: 3}

// Function arguments

function sum(a, b, c) {

return a + b + c;

const numbers = [1, 2, 3];

sum(...numbers); // same as sum(1, 2, 3)

Rest Parameters:

----------------

function sum(...numbers) {

return [Link]((total, num) => total + num, 0);

}
Classes:

--------

class Person {

constructor(name, age) {

[Link] = name;

[Link] = age;

greet() {

return `Hello, I'm ${[Link]}`;

static species() {

return "Homo sapiens";

class Student extends Person {

constructor(name, age, grade) {

super(name, age);

[Link] = grade;

study() {

return `${[Link]} is studying`;

}
Modules:

--------

// [Link]

export const PI = 3.14159;

export function add(a, b) {

return a + b;

export default class Calculator {

// class definition

// [Link]

import Calculator, { PI, add } from './[Link]';

import * as math from './[Link]';

Map and Set:

------------

// Map

const map = new Map();

[Link]('key1', 'value1');

[Link]('key2', 'value2');

[Link]([Link]('key1')); // 'value1'

[Link]('key1'); // true

[Link]('key1');

// Set

const set = new Set([1, 2, 3, 3, 4]);

[Link](set); // Set {1, 2, 3, 4}


[Link](5);

[Link](3); // true

[Link](2);

===============================================

10. COMMON METHODS AND PROPERTIES

==================================

String Methods:

---------------

const str = "Hello World";

[Link] // 11

[Link](0) // "H"

[Link]("o") // 4

[Link]("o") // 7

[Link](0, 5) // "Hello"

[Link](0, 5) // "Hello"

[Link](0, 5) // "Hello"

[Link]() // "hello world"

[Link]() // "HELLO WORLD"

[Link]() // Remove whitespace

[Link](" ") // ["Hello", "World"]

[Link]("World", "JS") // "Hello JS"

[Link]("World") // true

[Link]("Hello") // true

[Link]("World") // true
Number Methods:

---------------

const num = 123.456;

[Link]() // "123.456"

[Link](2) // "123.46"

[Link](4) // "123.5"

parseInt("123") // 123

parseFloat("123.45") // 123.45

[Link](123) // true

[Link](NaN) // true

[Link](123.456) // 123

[Link](123.456) // 123

[Link](123.456) // 124

[Link](1, 2, 3) // 3

[Link](1, 2, 3) // 1

[Link]() // Random number 0-1

Array Methods:

--------------

const arr = [1, 2, 3, 4, 5];

[Link](6) // Add to end

[Link]() // Remove from end

[Link](0) // Add to beginning

[Link]() // Remove from beginning

[Link](1, 2, 'a', 'b') // Remove/insert elements


[Link](1, 3) // Extract portion

[Link]([6, 7]) // Combine arrays

[Link](", ") // Convert to string

[Link]() // Reverse array

[Link]() // Sort array

[Link](3) // Find index

[Link](3) // Check if exists

[Link](x => x > 3) // Find first match

[Link](x => x > 3) // Filter elements

[Link](x => x * 2) // Transform elements

[Link]((sum, x) => sum + x, 0) // Reduce to single value

Date Methods:

-------------

const now = new Date();

[Link]() // Year

[Link]() // Month (0-11)

[Link]() // Day of month

[Link]() // Day of week (0-6)

[Link]() // Hours

[Link]() // Minutes

[Link]() // Seconds

[Link]() // Milliseconds since epoch

[Link]() // String representation

[Link]() // Date string

[Link]() // Time string

[Link]() // ISO format


===============================================

11. BEST PRACTICES

==================

Code Style:

-----------

1. Use meaningful variable names

2. Use camelCase for variables and functions

3. Use PascalCase for classes

4. Use UPPER_CASE for constants

5. Keep functions small and focused

6. Use consistent indentation (2 or 4 spaces)

Performance:

------------

1. Minimize DOM manipulation

2. Use event delegation for dynamic content

3. Avoid global variables

4. Use const and let instead of var

5. Use strict mode: 'use strict';

6. Cache DOM queries

7. Use document fragments for multiple DOM additions

Error Handling:

---------------

try {
// Code that might throw an error

riskyOperation();

} catch (error) {

[Link]('An error occurred:', [Link]);

} finally {

// Code that always runs

cleanup();

// Custom errors

throw new Error('Something went wrong');

Security:

---------

1. Validate user input

2. Escape HTML content

3. Use HTTPS

4. Don't expose sensitive data in client-side code

5. Use Content Security Policy (CSP)

===============================================

12. QUICK REFERENCE CHEATSHEET

===============================

Variable Declaration:

let name = "John";

const age = 30;


Functions:

function name() {}

const name = () => {};

Conditionals:

if (condition) {} else {}

condition ? true : false;

Loops:

for (let i = 0; i < 10; i++) {}

for (let item of array) {}

[Link](item => {});

Objects:

const obj = {key: value};

[Link] or obj['key']

Arrays:

const arr = [1, 2, 3];

[Link](), [Link](), [Link](), [Link]()

DOM:

[Link]()

[Link]()

[Link]

[Link]
Async:

async function() {}

await promise

fetch(url).then().catch()

Events:

[Link]('click', () => {});

Console:

[Link]()

[Link]()

[Link]()

Common Operators:

=== (strict equality)

!== (strict inequality)

&& (logical AND)

|| (logical OR)

! (logical NOT)

++ (increment)

-- (decrement)

Type Checking:

typeof variable

[Link]()

instanceof

JSON:
[Link](object)

[Link](string)

===============================================

ADDITIONAL RESOURCES

====================

Official Documentation:

- MDN Web Docs: [Link]

- ECMAScript Specification: [Link]

Practice Platforms:

- freeCodeCamp

- Codecademy

- [Link]

- LeetCode (for algorithms)

Useful Libraries:

- Lodash (utility functions)

- [Link] (date manipulation)

- Axios (HTTP requests)

- jQuery (DOM manipulation - though less common now)

Frameworks:

- React

- [Link]

- Angular
- [Link] (server-side)

===============================================

This cheatsheet covers the fundamental concepts and practical aspects of JavaScript
programming. Keep it handy for quick reference while coding!

Common questions

Powered by AI

The 'for...of' loop iterates over iterable objects such as arrays, yielding the values of each object's element. This loop is most useful when you need to access the values directly and is more readable compared to manual indexing in a traditional 'for' loop. The 'for...in' loop iterates over all enumerable properties of an object, including those inherited, and is primarily used with objects to access property names. However, it should be avoided with arrays due to possible unexpected behavior with inherited properties. The traditional 'for' loop provides full control over index manipulation which is preferable when needing precise control over the iteration, such as accessing element indices or skipping iterations based on certain calculations. Each type has distinct purposes, and choice depends on the need for value-orientation, key/properties iteration, or flexible index manipulation .

Higher-order functions are functions that either take other functions as arguments or return them as results. This facilitates a functional programming approach, improving code modularity and reuse by allowing abstraction of actions not just data. For example, the function 'execute(fn, value)' takes a function as a parameter and applies it to a value, allowing different operations to be passed in without changing the wrapper structure. Similarly, 'createMultiplier(factor)' returns a function tailored to multiply any given number by the specified factor, enabling the creation of utility functions like 'double' seamlessly. These patterns encourage DRY (Don't Repeat Yourself) principle, as you can create more generic functions that can be tailored by passing specific outcomes or logic as arguments .

JavaScript closures occur when a function retains access to its lexical scope, even after that scope has exited. A closure is created by defining a function inside another function, while maintaining a reference to its parent scope variables. They are commonly used for data encapsulation and creating private variables. For instance, in a factory function pattern, closures are used to maintain state across invocations without exposing the variables directly. Another common use is in asynchronous programming for callbacks, where closures ensure that the correct data is preserved when the callback executes. Additionally, closures allow for the implementation of once-functions which execute once, caching results for subsequent calls, ideal in optimization scenarios .

The 'var' keyword is function-scoped, which means it is accessible throughout the function where it is declared, and it supports hoisting, allowing variable use before declaration. However, var can lead to issues such as re-declaration and scope leakage. 'let' is block-scoped, meaning it is only accessible within the set of curly braces where it is declared. It is not initialized until execution reaches the line of code that declares it, reducing hoisting issues. 'const' is similar to 'let' in terms of block-scoping but is used to declare variables that should not be reassigned, ensuring immutability for the value binding, though not the value itself. 'let' and 'const' should be preferred in modern JavaScript for improved scoping and clarity .

Event delegation in JavaScript is a technique where a single event listener is set on a parent element to manage events on child elements. This is accomplished by taking advantage of event bubbling, where events propagate through the DOM from child to parent. Developers can then filter the event using properties like 'event.target' to react to specific elements. This approach reduces the number of event listeners, which enhances performance, particularly for elements created dynamically. It simplifies code maintenance and memory usage, as fewer handlers mean less memory consumption and simplified updates when modifying the DOM dynamically .

Modern JavaScript features introduced in ES6+ enhance the language by providing more powerful syntax and functionalities which improve code simplicity, readability, and maintainability. Examples include: 1. Arrow Functions: Concise way to define functions, especially in callbacks, enhancing the readability. 2. Template Literals: Simplify string concatenation by allowing embedded expressions within backticks. 3. Destructuring: Allows unpacking values from arrays or properties from objects into distinct variables. 4. Spread & Rest Operators: Spread operator makes it easy to expand iterables into multiple elements/objects, while rest parameters allow representation of indefinite number of arguments as an array. 5. Classes: Provides a clearer, more concise syntax for establishing prototypes and creating objects. These features collectively make the code more expressive and straightforward, facilitating better coding practices .

Using 'async/await' offers a syntax that makes asynchronous code look synchronous, significantly enhancing code readability and maintainability. Unlike promise chaining, which requires multiple '.then()' calls, 'async/await' sequentially executes asynchronous functions, allowing developers to use standard 'try/catch' statements for error handling, which is more intuitive and resembles synchronous error handling. This reduces the complexity of managing asynchronous flows, especially in complex logic involving multiple awaits. Moreover, it avoids nested '.then()' chains, making the code easier to read and debug while maintaining the asynchronous behavior advantages .

JavaScript supports both client-side and server-side programming due to its versatile execution environment. On the client side, it is used to create interactive web pages, managing DOM manipulations, event handling, and asynchronous operations using features like AJAX and Fetch API. On the server side, using environments like Node.js, JavaScript can handle backend logic, manage databases, and perform network communications. This capability allows for a cohesive language across the entire stack, potentially reducing context switching for developers and facilitating full-stack development .

Promises are usually preferred over callbacks when you need to handle asynchronous operations because they offer a more organized, readable, and manageable structure, notably in scenarios involving multiple asynchronous tasks or when task sequencing is important. Promises allow chaining with '.then()' methods, making it easier to write sequential logic and manage error handling with the '.catch()' method. Additionally, promises help avoid the so-called 'callback hell', which occurs with nested callbacks, making the code complex and error-prone. Promises are especially beneficial in modern applications that utilize ES6+, providing more efficient ways to manage asynchronous code than traditional callbacks .

The 'eval' function in JavaScript executes a string as code, which comes with significant advantages and potential risks. It allows for dynamic code execution, thereby adding flexibility and enabling meta-programming by executing strings of code generated programmatically. However, 'eval' poses severe security concerns. It can execute arbitrary code from strings, leading to code injection vulnerabilities if user inputs are not properly sanitized and validated, making it a common attack vector for cross-site scripting (XSS). Furthermore, its use can affect performance, as it disables some JavaScript engine optimizations. Therefore, while it provides powerful dynamic execution capabilities, 'eval' should be avoided in favor of safer alternatives such as 'Function' constructor or external script files for dynamic code loading .

You might also like