JavaScript is a scripting language that enables dynamic interactivity on websites.
// Single-line comment
/* Multi-line
comment */
var x = 5;
let y = "Hello";
const z = true;
console.log(x + y);
| Keyword | Description | Scope | Reassignment | Redeclaration |
|---|---|---|---|---|
| var | Declares a variable. | Function or global scope. | Yes | Yes (in the same scope) |
| let | Declares a block-scoped, local variable. | Block scope. | Yes | No |
| const | Declares a block-scoped, read-only constant. | Block scope. | No | No |
| Type | Description | Example |
|---|---|---|
| String | Represents textual data. | "Hello", 'World', `Template literal` |
| Number | Represents numeric data (integers and floating-point numbers). | 10, 3.14, -5 |
| Boolean | Represents logical values (true or false). | true, false |
| Null | Represents the intentional absence of a value. | null |
| Undefined | Represents a variable that has not been assigned a value. | undefined |
| Symbol | A unique and immutable primitive value (introduced in ES6). | Symbol('description') |
| BigInt | Represents integers of arbitrary length (introduced in ES2020). | 9007199254740991n |
| Object | Represents a collection of key-value pairs. | { name: 'John', age: 30 }, [1, 2, 3], function() {} |
| Operator Type | Operators | Description | Example |
|---|---|---|---|
| Arithmetic | +, -, *, /, %, ++, -- | Perform arithmetic calculations. | 5 + 2, x++ |
| Assignment | =, +=, -=, *=, /=, %= | Assign values to variables. | x = 10, y += 5 |
| Comparison | ==, ===, !=, !==, >, <, >=, <= | Compare values. | x == 5, y === "Hello" |
| Logical | &&, ||, ! | Perform logical operations. | true && false, !true |
| Ternary | condition ? exprIfTrue : exprIfFalse | A shorthand for an if-else statement. | age > 18 ? "Adult" : "Minor" |
| Type | typeof, instanceof | Determine the type of a variable or object. | typeof x, arr instanceof Array |
| Statement | Description | Syntax |
|---|---|---|
| if | Executes a block of code if a condition is true. |
|
| else if | Executes a block of code if the previous if condition is false and the current condition is true. |
|
| else | Executes a block of code if all preceding if and else if conditions are false. |
|
| switch | Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case. |
|
| for | Loops through a block of code a number of times. |
|
| while | Loops through a block of code as long as a condition is true. |
|
| do...while | Loops through a block of code once, and then repeats as long as a condition is true. |
|
| break | Exits a loop or a switch statement. |
|
| continue | Skips the rest of the code in a loop for the current iteration. |
|
| Type | Description | Syntax | Example |
|---|---|---|---|
| Function Declaration | Defines a named function. |
|
|
| Function Expression | Defines a function as part of an expression. |
|
|
| Arrow Function (ES6+) | A concise way to write function expressions. |
|
|
| Concept | Description | Example |
|---|---|---|
| Object Literal | A way to define an object with properties and methods. |
|
| Accessing Properties | Using dot notation or bracket notation. |
|
| Accessing Methods | Calling a function that is a property of an object. |
|
| this Keyword | Refers to the object it belongs to. | (See example above) |
| Concept | Description | Example |
|---|---|---|
| Array Literal | A way to define an array. | const numbers = [1, 2, 3, 4, 5]; |
| Accessing Elements | Using index (starting from 0). | numbers[0]; // 1 |
| Common Methods | Functions to manipulate arrays. |
|
| Method | Description | Example |
|---|---|---|
| document.getElementById(id) | Returns the element with the specified ID. | const element = document.getElementById("myId"); |
| document.getElementsByClassName(className) | Returns a collection of elements with the specified class name. | const elements = document.getElementsByClassName("myClass"); |
| document.getElementsByTagName(tagName) | Returns a collection of elements with the specified tag name. | const elements = document.getElementsByTagName("p"); |
| document.querySelector(selector) | Returns the first element that matches a CSS selector. | const element = document.querySelector("#myId .myClass"); |
| document.querySelectorAll(selector) | Returns a collection of all elements that match a CSS selector. | const elements = document.querySelectorAll("div p"); |
| element.innerHTML | Gets or sets the HTML content of an element. | element.innerHTML = "<strong>Hello</strong>"; |
| element.textContent | Gets or sets the text content of an element. | element.textContent = "World"; |
| element.getAttribute(attributeName) | Gets the value of an attribute. | const href = element.getAttribute("href"); |
| element.setAttribute(attributeName, value) | Sets the value of an attribute. | element.setAttribute("href", "https://example.com"); |
| element.style.propertyName | Gets or sets inline CSS styles. | element.style.color = "red"; |
| document.createElement(tagName) | Creates a new HTML element. | const newElement = document.createElement("p"); |
| parentElement.appendChild(childElement) | Appends a child element to a parent element. | parentElement.appendChild(newElement); |
| parentElement.insertBefore(newElement, referenceElement) | Inserts a new element before a reference element. | parentElement.insertBefore(newElement, referenceElement); |
| parentElement.removeChild(childElement) | Removes a child element from a parent element. | parentElement.removeChild(childElement); |
| Concept | Description | Example |
|---|---|---|
| addEventListener(type, listener) | Attaches an event listener to an element. |
|
| removeEventListener(type, listener) | Removes an event listener from an element. |
|
| Common Events | Examples include click, mouseover, mouseout, mousemove, keydown, keyup, submit, change. | (See example above) |
| Event Object | Provides information about the event. |
|
| Concept | Description | Example |
|---|---|---|
| Callbacks | A function passed as an argument to another function, to be executed later. |
|
| Promises (ES6+) | An object representing the eventual completion (or failure) of an asynchronous operation. |
|
| Async/Await (ES2017+) | Syntactic sugar for working with promises, making asynchronous code look and behave a bit more like synchronous code. |
|
| Statement | Description | Syntax |
|---|---|---|
| try | Defines a block of code to test for errors. |
|
| catch | Defines a block of code to handle any errors that occur in the try block. |
|
| finally | Defines a block of code to be executed regardless of the try-catch result. |
|
| throw | Throws a custom error. |
|
| Method | Description | Example |
|---|---|---|
| length | Returns the length of a string. | "Hello".length; // 5 |
| charAt(index) | Returns the character at a specified index. | "Hello".charAt(0); // "H" |
| charCodeAt(index) | Returns the Unicode value of the character at a specified index. | "Hello".charCodeAt(0); // 72 |
| concat(string) | Joins two or more strings. | "Hello".concat(" ", "World"); // "Hello World" |
| indexOf(searchValue, fromIndex) | Returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. | "Hello World".indexOf("o"); // 4 |
| lastIndexOf(searchValue, fromIndex) | Returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found. | "Hello World".lastIndexOf("o"); // 7 |
| slice(beginIndex, endIndex) | Extracts a section of a string and returns it as a new string. | "Hello World".slice(0, 5); // "Hello" |
| substring(indexStart, indexEnd) | Returns the part of the string between the start and end indexes, or to the end of the string. | "Hello World".substring(6); // "World" |
| substr(start, length) | Returns a portion of the string, starting at the specified index and extending for a given number of characters. | "Hello World".substr(6, 5); // "World" |
| replace(searchValue, newValue) | Returns a new string with some or all matches of a pattern replaced by a replacement. | "Hello World".replace("Hello", "Hi"); // "Hi World" |
| replaceAll(searchValue, newValue) | Returns a new string with all matches of a pattern replaced by a replacement. | "Hello Hello".replaceAll("Hello", "Hi"); // "Hi Hi" |
| toUpperCase() | Returns the calling string value converted to uppercase. | "hello".toUpperCase(); // "HELLO" |
| toLowerCase() | Returns the calling string value converted to lowercase. | "WORLD".toLowerCase(); // "world" |
| trim() | Removes whitespace from both ends of a string. | " Hello ".trim(); // "Hello" |
| split(separator) | Splits a String object into an array of strings by separating the string into substrings. | "Hello,World".split(","); // ["Hello", "World"] |
| Method | Description | Example |
|---|---|---|
| toFixed(digits) | Formats a number using fixed-point notation. | (3.14159).toFixed(2); // "3.14" |
| toPrecision(precision) | Returns a string representing the Number object to the specified precision. | (3.14159).toPrecision(3); // "3.14" |
| parseInt(string) | Parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems). | parseInt("10"); // 10, parseInt("10.5"); // 10 |
| parseFloat(string) | Parses a string argument and returns a floating point number. | parseFloat("10.5"); // 10.5 |
| isNaN(value) | Determines whether a value is NaN (Not-a-Number). | isNaN(NaN); // true, isNaN("Hello"); // true, isNaN(10); // false |
| isFinite(value) | Determines whether a value is a finite number. | isFinite(10); // true, isFinite(Infinity); // false |
| Property/Method | Description | Example |
|---|---|---|
| Math.PI | Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159. | Math.PI; // 3.141592653589793 |
| Math.round(x) | Returns the value of a number rounded to the nearest integer. | Math.round(4.7); // 5, Math.round(4.4); // 4 |
| Math.ceil(x) | Returns the smallest integer greater than or equal to a given number. | Math.ceil(4.4); // 5 |
| Math.floor(x) | Returns the largest integer less than or equal to a given number. | Math.floor(4.7); // 4 |
| Math.random() | Returns a floating-point, pseudo-random number in the range 0 (inclusive) up to but not including 1 (exclusive). | Math.random(); // e.g., 0.876... |
| Math.max(x, y, ...) | Returns the largest of zero or more numbers. | Math.max(10, 5, 20); // 20 |
| Math.min(x, y, ...) | Returns the smallest of zero or more numbers. | Math.min(10, 5, 20); // 5 |
| Math.pow(base, exponent) | Returns base to the power of exponent. | Math.pow(2, 3); // 8 |
| Math.sqrt(x) | Returns the square root of x. | Math.sqrt(9); // 3 |
| Method | Description | Example |
|---|---|---|
| new Date() | Creates a new Date object with the current date and time. | const now = new Date(); |
| new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds) | Creates a new Date object with specified date and time. Note: monthIndex starts from 0 (January). | const specificDate = new Date(2023, 10, 20, 10, 30, 0); // Nov 20, 2023 10:30:00 |
| getFullYear() | Returns the year of a date. | now.getFullYear(); |
| getMonth() | Returns the month of a date (0-11). | now.getMonth(); |
| getDate() | Returns the day of the month of a date (1-31). | now.getDate(); |
| getHours() | Returns the hour of a date (0-23). | now.getHours(); |
| getMinutes() | Returns the minutes of a date (0-59). | now.getMinutes(); |
| getSeconds() | Returns the seconds of a date (0-59). | now.getSeconds(); |
| getMilliseconds() | Returns the milliseconds of a date (0-999). | now.getMilliseconds(); |
| getTime() | Returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. | now.getTime(); |
| Method | Description | Example |
|---|---|---|
| JSON.stringify(value) | Converts a JavaScript value to a JSON string. | const obj = {
name: "John", age: 30
}; const jsonString = JSON.stringify(obj); // '{"name":"John","age":30}' |
| JSON.parse(text) | Parses a JSON string, constructing the JavaScript value or object described by the string. | const json =
'{"name":"John","age":30}'; const parsedObj = JSON.parse(json); // { name: 'John', age: 30 } |
Scope determines the accessibility (visibility) of variables.
A closure is a function that has access to the outer (enclosing) function's variables—scope chain—even after the outer function has returned.
function outerFunction(outerVar) {
return function innerFunction(innerVar) {
console.log(outerVar, innerVar);
};
}
const myClosure = outerFunction("Hello");
myClosure("World"); // Output: Hello World
This cheat sheet provides a comprehensive overview of common JavaScript concepts and features. For more detailed information, refer to official JavaScript documentation and resources like MDN Web Docs.