21. Closures
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
javascript
function outerFunction() {
let outerVariable = "I'm outside!";
function innerFunction() {
console.log(outerVariable); // Can access outerVariable
}
return innerFunction;
}
let closure = outerFunction();
closure(); // Outputs: I'm outside!
22. The this
Keyword
The this
keyword refers to the context in which a function is called.
javascript
let person = {
name: 'Alice',
greet: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
person.greet(); // Outputs: Hello, my name is Alice
let greet = person.greet;
greet(); // Outputs: Hello, my name is undefined (or could cause an error in strict mode)
To preserve the context of this
, you can use bind
, call
, or apply
.
bind
javascript
let boundGreet = person.greet.bind(person);
boundGreet(); // Outputs: Hello, my name is Alice
23. Immediately Invoked Function Expressions (IIFE)
IIFE is a function that runs as soon as it is defined.
javascript
(function() {
console.log("This is an IIFE");
})(); // Outputs: This is an IIFE
24. The Event Loop
JavaScript has a single-threaded event loop that manages the execution of asynchronous operations.
javascript
console.log('Start');
setTimeout(() => {
console.log('Timeout');
}, 0);
Promise.resolve().then(() => {
console.log('Promise');
});
console.log('End');
// Output order: Start, End, Promise, Timeout
25. JSON
JSON (JavaScript Object Notation) is a format for storing and transporting data.
Parsing JSON
javascript
let jsonString = '{"name": "John", "age": 30}';
let obj = JSON.parse(jsonString);
console.log(obj.name); // Outputs: John
Stringifying JSON
javascript
let obj = {name: "John", age: 30};
let jsonString = JSON.stringify(obj);
console.log(jsonString); // Outputs: {"name":"John","age":30}
26. Regular Expressions
Regular expressions are patterns used to match character combinations in strings.
javascript
let text = "The quick brown fox";
let pattern = /quick/;
let result = pattern.test(text);
console.log(result); // Outputs: true
27. Browser Storage
Local Storage
Local storage allows you to store data on the user's browser.
javascript
localStorage.setItem('name', 'Alice');
let name = localStorage.getItem('name');
console.log(name); // Outputs: Alice
localStorage.removeItem('name');
Session Storage
Session storage is similar to local storage, but data is cleared when the page session ends.
javascript
sessionStorage.setItem('name', 'Bob');
let name = sessionStorage.getItem('name');
console.log(name); // Outputs: Bob
sessionStorage.removeItem('name');
28. setTimeout
and setInterval
These functions are used to execute code after a delay or repeatedly at specified intervals.
setTimeout
javascript
setTimeout(() => {
console.log('This runs after 2 seconds');
}, 2000);
setInterval
javascript
let count = 0;
let intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) {
clearInterval(intervalId);
}
}, 1000);
29. Debouncing and Throttling
Debouncing and throttling are techniques to control how often a function is executed.
Debouncing
Debouncing ensures a function is executed only after a specified delay has passed since it was last invoked.
javascript
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
window.addEventListener('resize', debounce(() => {
console.log('Resized');
}, 500));
Throttling
Throttling ensures a function is executed at most once in a specified period.
javascript
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('resize', throttle(() => {
console.log('Resized');
}, 1000));
30. Web APIs
Web APIs are interfaces provided by browsers to interact with various browser functions and services.
Geolocation API
javascript
navigator.geolocation.getCurrentPosition((position) => {
console.log(position.coords.latitude, position.coords.longitude);
});
Fetch API
javascript
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
31. Working with Dates
JavaScript provides the Date
object for handling dates and times.
javascript
let now = new Date();
console.log(now); // Outputs current date and time
let specificDate = new Date('2023-05-25');
console.log(specificDate); // Outputs: Thu May 25 2023
32. Template Literals for HTML
Template literals can be used to create HTML strings.
javascript
let name = 'John';
let html = `
<div>
<h1>Hello, ${name}!</h1>
<p>This is a template literal</p>
</div>
`;
document.body.innerHTML = html;
33. Form Handling
JavaScript can handle form submissions and validate inputs.
html
<!DOCTYPE html>
<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form id="myForm">
<input type="text" id="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
let name = document.getElementById('name').value;
alert(`Hello, ${name}!`);
});
</script>
</body>
</html>
34. Responsive Design
JavaScript can be used to make web pages responsive.
javascript
window.addEventListener('resize', () => {
if (window.innerWidth < 600) {
document.body.style.backgroundColor = 'lightblue';
} else {
document.body.style.backgroundColor = 'white';
}
});
35. Using External Libraries
You can enhance your JavaScript projects using external libraries like jQuery, Lodash, and Axios.
jQuery Example
html
<!DOCTYPE html>
<html>
<head>
<title>jQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="btn">Click me</button>
<script>
$('#btn').click(function() {
alert('Button clicked!');
});
</script>
</body>
</html>
36. ES6 Modules
ES6 modules provide a way to organize and share code between files.
Creating a Module
javascript
// file: myModule.js
export const name = 'Alice';
export function greet() {
return 'Hello!';
}
Using a Module
javascript
// file: main.js
import { name, greet } from './myModule.js';
console.log(name); // Outputs: Alice
console.log(greet()); // Outputs: Hello!
37. Advanced Array Methods
Learn about more advanced array methods such as reduce
, find
, some
, and every
.
reduce
javascript
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // Outputs: 15
find
javascript
let users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'}
];
let user = users.find(user => user.id === 2);
console.log(user); // Outputs: {id: 2, name: 'Bob'}
some
javascript
let hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // Outputs: true
every
javascript
let allPositive = numbers.every(num => num > 0);
console.log(allPositive); // Outputs: true
38. Proxy and Reflect
Proxies allow you to intercept and redefine operations for objects.
javascript
let person = {
name: 'Alice',
age: 25
};
let handler = {
get: function(target, property) {
return property in target ? target[property] : 'Not found';
}
};
let proxy = new