Variables and Data Types
- var: Declares a variable
- let: Declares a block-scoped local variable
- const: Declares a read-only constant
Data Types:
- Number: 42 or 3.14
- String: ‘Hello’, “World”
- Boolean: true, false
- Null: null
- Undefined: undefined
- Object: { key: ‘value’ }
- Array: [1, 2, 3]
Operators
- Arithmetic: +, -, *, /, %, ++, —
- Comparison: ==, ===, !=, !==, <, >, <=, >=
- Logical: &&, ||, !
- Ternary: condition ? expression1 : expression2
- Assignment: =, +=, -=, *=, /=, %=
Control Structures
- if: if (condition) { … }
- else: if (condition) { … } else { … }
- else if: if (condition1) { … } else if (condition2) { … } else { … }
- switch: switch (expression) { case value1: … break; case value2: … break; default: … }
- for: for (initialization; condition; increment) { … }
- while: while (condition) { … }
- do while: do { … } while (condition);
- break: break;
- continue: continue;
Functions
- Function declaration: function functionName(parameters) { … }
- Function expression: var functionName = function(parameters) { … };
- Arrow function: (parameters) => { … }
- Calling a function: functionName(arguments);
- Return value: return expression;
Objects
- Object literal: { key1: value1, key2: value2 }
- Accessing properties: object.key or object[‘key’]
- Adding properties: object.newKey = value;
- Deleting properties: delete object.key;
- Iterating over properties: for (var key in object) { … }
Arrays
- Array literal: [element1, element2, element3]
- Accessing elements: array[index]
- Length: array.length
- Adding elements: array.push(value); or array[index] = value;
- Removing elements: array.pop(); or delete array[index];
- Iterating over elements: for (var i = 0; i < array.length; i++) { … }
Common Array Methods
- forEach: array.forEach(function(element, index) { … });
- map: var newArray = array.map(function(element, index) { … });
- filter: var newArray = array.filter(function(element, index) { … });
- reduce: var result = array.reduce(function(accumulator, element, index) { … }, initialValue);
- indexOf: var index = array.indexOf(value);
- includes: var isIncluded = array.includes(value);
String Methods
- Length: string.length
- indexOf: string.indexOf(substring)
- lastIndexOf: string.lastIndexOf(substring)
- slice: string.slice(start, end)
- toUpperCase: string.toUpperCase()
- toLowerCase: string.toLowerCase()
- trim: string.trim()
- split: string.split(separator)
- replace: string.replace(searchValue, newValue)
Error Handling
- try catch: try { … } catch (error) { … }
- throw: throw new Error(‘Error message’);
Regular Expressions
- RegExp literal: /pattern/flags
- RegExp constructor: new RegExp(‘pattern’, ‘flags’)
Flags
- g: global
- i: case-insensitive
- m: multiline
Methods
- test: regex.test(string)
- exec: regex.exec(string)
- match: string.match(regex)
- replace: string.replace(regex, replacement)
JSON
- JSON.parse: var obj = JSON.parse(jsonString);
- JSON.stringify: var jsonString = JSON.stringify(obj);
DOM Manipulation
- getElementById: document.getElementById(‘id’);
- getElementsByClassName: document.getElementsByClassName(‘className’);
- getElementsByTagName: document.getElementsByTagName(‘tagName’);
- querySelector: document.querySelector(‘selector’);
- querySelectorAll: document.querySelectorAll(‘selector’);
- createElement: document.createElement(‘tagName’);
- createTextNode: document.createTextNode(‘text’);
- appendChild: parent.appendChild(child);
- removeChild: parent.removeChild(child);
- insertBefore: parent.insertBefore(newChild, referenceChild);
- replaceChild: parent.replaceChild(newChild, oldChild);
- setAttribute: element.setAttribute(‘attribute’, ‘value’);
- getAttribute: element.getAttribute(‘attribute’);
- removeAttribute: element.removeAttribute(‘attribute’);
- addEventListener: element.addEventListener(‘event’, function);
- removeEventListener: element.removeEventListener(‘event’, function);
Timing Functions
- setTimeout: var timeoutId = setTimeout(function, delay);
- clearTimeout: clearTimeout(timeoutId);
- setInterval: var intervalId = setInterval(function, delay);
- clearInterval: clearInterval(intervalId);
Promises
- Creating a Promise: var promise = new Promise(function(resolve, reject) { … });
- then: promise.then(function(result) { … });
- catch: promise.catch(function(error) { … });
- finally: promise.finally(function() { … });
- Promise.all: Promise.all([promise1, promise2]).then(function(results) { … });
- Promise.race: Promise.race([promise1, promise2]).then(function(result) { … });
Async/Await
- async: async function functionName() { … }
- await: var result = await promise; (inside an async function)
Modules
- Exporting: export { variable, function };
- Default Export: export default expression;
- Importing: import { variable, function } from ‘module’;
- Importing Default: import defaultExport from ‘module’;
- Importing with Alias: import { variable as alias } from ‘module’;
- Importing Everything: import * as name from ‘module’;
Classes
- Class Declaration: class ClassName { … }
- Constructor: constructor(parameters) { … }
- Properties: property = value;
- Methods: methodName(parameters) { … }
- Inheritance: class DerivedClass extends BaseClass { … }
- super: super(parameters); (inside a derived class constructor)
- Static Methods: static methodName(parameters) { … }
Destructuring
- Array Destructuring: const [a, b] = array;
- Object Destructuring: const { prop1, prop2 } = object;
- Destructuring with Default Values: const { prop1, prop2 = defaultValue } = object;
- Destructuring with Renaming: const { prop1: newName1, prop2: newName2 } = object;
Template Literals
- Template Literal: `string with ${expression} inside`
Rest and Spread Operators
- Rest Operator: function functionName(…parameters) { … }
- Spread Operator (arrays): const newArray = […array1, …array2];
- Spread Operator (objects): const newObject = { …object1, …object2 };
Short-circuit Evaluation
- OR: const result = value1 || defaultValue;
- AND: const result = value1 && value2;
Optional Chaining
- Optional Chaining: const result = object?.property?.nestedProperty;
Nullish Coalescing Operator
- Nullish Coalescing: const result = value1 ?? defaultValue;
Sets
- Creating a Set: const set = new Set([value1, value2]);
- Adding values: set.add(value);
- Removing values: set.delete(value);
- Checking if a value exists: set.has(value);
- Size: set.size;
- Clearing a Set: set.clear();
- Iterating over a Set: set.forEach((value, _, set) => { … });
Maps
- Creating a Map: const map = new Map([[‘key1’, value1], [‘key2’, value2]]);
- Getting values: map.get(‘key’);
- Setting values: map.set(‘key’, value);
- Checking if a key exists: map.has(‘key’);
- Deleting keys: map.delete(‘key’);
- Size: map.size;
- Clearing a Map: map.clear();
- Iterating over a Map: map.forEach((value, key, map) => { … });
Symbols
- Creating a Symbol: const symbol = Symbol(‘description’);
- Using a Symbol as a Key: const object = { [symbol]: value };
Iterators
- Creating an Iterator: { [Symbol.iterator]: function() { … } }
- Using an Iterator: for (const value of iterable) { … }
Generators
- Generator Function: function* generatorName() { … }
- Yield: yield value;
- Iterator: const iterator = generator();
- Next: iterator.next();
Proxies
- Creating a Proxy: const proxy = new Proxy(target, handler);
- Handler: { get: function(target, property, receiver), set: function(target, property, value, receiver) }
Error Types
- Error
- ReferenceError
- TypeError
- SyntaxError
- RangeError
- EvalError
- URIError
JavaScript Events
- click: element.addEventListener(‘click’, function);
- dblclick: element.addEventListener(‘dblclick’, function);
- mousedown: element.addEventListener(‘mousedown’, function);
- mouseup: element.addEventListener(‘mouseup’, function);
- mousemove: element.addEventListener(‘mousemove’, function);
- mouseover: element.addEventListener(‘mouseover’, function);
- mouseout: element.addEventListener(‘mouseout’, function);
- keydown: element.addEventListener(‘keydown’, function);
- keyup: element.addEventListener(‘keyup’, function);
- keypress: element.addEventListener(‘keypress’, function);
- focus: element.addEventListener(‘focus’, function);
- blur: element.addEventListener(‘blur’, function);
- change: element.addEventListener(‘change’, function);
- submit: element.addEventListener(‘submit’, function);
- load: element.addEventListener(‘load’, function);
- unload: element.addEventListener(‘unload’, function);
- error: element.addEventListener(‘error’, function);
- resize: element.addEventListener(‘resize’, function);
- scroll: element.addEventListener(‘scroll’, function);
Web APIs
- Fetch API: fetch(url, options).then(response => response.json()).then(data => { … });
- XMLHttpRequest: var xhr = new XMLHttpRequest(); xhr.open(‘GET’, url, true); xhr.onreadystatechange = function() { … }; xhr.send();
- Web Storage (localStorage and sessionStorage): localStorage.setItem(‘key’, value); var value = localStorage.getItem(‘key’); localStorage.removeItem(‘key’);
- Geolocation API: navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
- File Reader API: var reader = new FileReader(); reader.onload = function() { … }; reader.readAsText(file);
- Web Workers: var worker = new Worker(‘worker.js’); worker.postMessage(data); worker.onmessage = function(event) { … }; worker.terminate();
- WebSockets: var socket = new WebSocket(‘ws://example.com’); socket.onopen = function() { … }; socket.onmessage = function(event) { … }; socket.send(data); socket.close();
Date and Time
- Creating a Date object: const date = new Date();
- Getters: getFullYear(), getMonth(), getDate(), getDay(), getHours(), getMinutes(), getSeconds(), getMilliseconds(), getTime(), getTimezoneOffset()
- Setters: setFullYear(), setMonth(), setDate(), setHours(), setMinutes(), setSeconds(), setMilliseconds(), setTime()
- Parsing: Date.parse(‘YYYY-MM-DDTHH:mm:ss.sssZ’)
- Formatting: date.toLocaleString(), date.toLocaleDateString(), date.toLocaleTimeString()
Math Object
- Constants: Math.PI, Math.E, Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E, Math.SQRT1_2, Math.SQRT2
- Functions: Math.abs(), Math.ceil(), Math.floor(), Math.round(), Math.trunc(), Math.sign(), Math.sqrt(), Math.cbrt(), Math.pow(), Math.exp(), Math.log(), Math.log10(), Math.log2(), Math.max(), Math.min(), Math.random(), Math.sin(), Math.cos(), Math.tan(), Math.asin(), Math.acos(), Math.atan(), Math.atan2()
Number Object
- Constants: Number.MAX_VALUE, Number.MIN_VALUE, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NaN
- Functions: Number.isFinite(), Number.isInteger(), Number.isNaN(), Number.parseFloat(), Number.parseInt()
- Methods: toFixed(), toExponential(), toPrecision()
String Object
- Escape characters: \\, \’, \”, \n, \r, \t, \b, \f, \v, \uXXXX
- Methods: charAt(), charCodeAt(), codePointAt(), concat(), endsWith(), startsWith(), includes(), indexOf(), lastIndexOf(), localeCompare(), match(), padEnd(), padStart(), repeat(), search(), slice(), split(), substr(), substring(), toLowerCase(), toUpperCase(), toLocaleLowerCase(), toLocaleUpperCase(), trim(), trimStart(), trimEnd(), valueOf()
Array Object
- Methods: concat(), copyWithin(), entries(), every(), fill(), filter(), find(), findIndex(), flat(), flatMap(), forEach(), includes(), indexOf(), isArray(), join(), keys(), lastIndexOf(), map(), pop(), push(), reduce(), reduceRight(), reverse(), shift(), slice(), some(), sort(), splice(), toLocaleString(), toString(), unshift(), values()
Function Object
- Properties: name, length, prototype
- Methods: apply(), bind(), call(), toString()
Leave a Reply