JavaScript has 7 data types:
undefined
: A variable that has been declared but not assigned a value is undefined
.null
: A special value representing the intentional absence of any object value.A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
function outer() {
let count = 0;
return function inner() {
count++;
console.log(count);
};
}
const counter = outer();
counter(); // 1
counter(); // 2
Hoisting is JavaScript's behavior of moving all declarations (var, function, class) to the top of their containing scope during compilation.
console.log(x); // undefined
var x = 5;
this
refers to the context in which a function is called:
this
from the surrounding context.Arrow functions are a more concise way to write functions and do not have their own this
context. They inherit this
from the parent scope.
const add = (a, b) => a + b;
The event loop is a mechanism that allows JavaScript to perform non-blocking I/O operations by putting callbacks and promises in a message queue, executing them asynchronously.
==
(Equality): Compares values after type conversion.===
(Strict Equality): Compares both value and type.
'5' == 5; // true
'5' === 5; // false
A promise is an object representing the eventual completion or failure of an asynchronous operation. It has three states: Pending, Fulfilled, and Rejected.
let p = new Promise((resolve, reject) => {
let success = true;
if (success) resolve('Success!');
else reject('Failed!');
});
async
functions return a promise, and await
is used inside async functions to pause the execution until the promise resolves.
async function fetchData() {
let data = await fetch('url');
console.log(await data.json());
}
var
: Function-scoped and can be redeclared.let
: Block-scoped and cannot be redeclared within the same scope.const
: Block-scoped and cannot be reassigned.Modules in JavaScript are a way to break code into smaller, reusable pieces. Modules can be exported and imported.
// file1.js
export const name = 'John';
// file2.js
import { name } from './file1';
The spread operator (...
) is used to expand elements of an iterable (like arrays) into individual elements.
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5];
The rest parameter (...
) allows a function to accept an indefinite number of arguments as an array.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
A higher-order function is a function that takes another function as an argument or returns a function as a result.
function multiply(a, b) {
return a * b;
}
function operate(fn, a, b) {
return fn(a, b);
}
operate(multiply, 2, 3); // 6
bind()
creates a new function that, when invoked, has its this
set to the provided value and prepends any arguments to the function.
const obj = { x: 5 };
const getX = function () {
return this.x;
};
const boundGetX = getX.bind(obj);
console.log(boundGetX()); // 5
call()
: Calls a function with a given this
value and arguments passed individually.apply()
: Calls a function with a given this
value and arguments passed as an array.Destructuring allows extracting values from arrays or objects and assigning them to variables.
const { name, age } = { name: 'John', age: 25 };
const [first, second] = [1, 2];
Promise chaining allows you to chain multiple .then()
calls, where each .then()
is executed after the promise resolves.
fetch('/api')
.then(response => response.json())
.then(data => console.log(data));
Event delegation is a technique where you attach a single event listener to a parent element instead of multiple listeners to child elements. It takes advantage of event bubbling.
document.querySelector('#parent').addEventListener('click', (event) => {
if (event.target && event.target.matches('button')) {
console.log('Button clicked');
}
});
setTimeout()
is used to execute a function after a specified delay.
setTimeout(() => {
console.log('Hello after 2 seconds');
}, 2000);
setInterval()
repeatedly calls a function with a specified time delay between each call.
setInterval(() => {
console.log('Repeated message every second');
}, 1000);
for
loop: A general-purpose loop that can be used with arrays, objects, etc.forEach
loop: An array-specific method that iterates through the array elements.
arr.forEach((item) => console.log(item));
JSON (JavaScript Object Notation) is a lightweight data interchange format used to represent structured data. It is often used in APIs for data exchange.
const data = '{"name":"John", "age":30}';
const obj = JSON.parse(data); // Converts JSON string to JavaScript object
Both are web storage APIs for storing data:
localStorage
: Persists data across sessions.sessionStorage
: Persists data only for the duration of the page session.The module pattern is used to encapsulate functionality in a self-contained unit to avoid polluting the global namespace.
const myModule = (function () {
let privateVar = 'Private';
return {
publicMethod: function () {
console.log(privateVar);
},
};
})();
slice()
: Returns a shallow copy of a portion of the array without modifying the original.splice()
: Changes the content of an array by removing or replacing elements.Template literals allow embedding expressions inside string literals using ${}
syntax.
const name = 'John';
const greeting = `Hello, ${name}!`;
The debugger
keyword is used to pause the execution of JavaScript code, allowing you to inspect the state of the program at that point.
debugger;