What Can JavaScript Do: 10 Practical Code Examples
Ready-to-use JavaScript code snippets demonstrating what JavaScript can do in real-world applications and projects.
What Can JavaScript Do: 10 Practical Code Examples
Discover what JavaScript can do through practical, ready-to-use code snippets that demonstrate its versatility in web development, data handling, and user interaction.
1. Dynamic Content Creation #
JavaScript can create and modify HTML elements on the fly:
2. Form Validation and Input Handling #
JavaScript can validate user input and provide instant feedback:
// Real-time form validation
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
function handleFormInput() {
const emailInput = document.getElementById('email');
const feedback = document.getElementById('feedback');
emailInput.addEventListener('input', function() {
const isValid = validateEmail(this.value);
feedback.textContent = isValid ?
'Valid email!' : 'Please enter a valid email';
feedback.style.color = isValid ? 'green' : 'red';
});
}
3. Data Fetching and API Integration #
JavaScript can communicate with external services and APIs:
// Fetch data from APIs
async function fetchUserData(userId) {
try {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const userData = await response.json();
// JavaScript can process and display the data
displayUserInfo(userData);
} catch (error) {
console.error('What JavaScript can do includes error handling:', error);
}
}
function displayUserInfo(user) {
console.log(`Name: ${user.name}`);
console.log(`Email: ${user.email}`);
console.log(`Company: ${user.company.name}`);
}
4. Interactive User Interface Elements #
JavaScript can create responsive and interactive UI components:
5. Data Processing and Transformation #
JavaScript can manipulate and transform complex data structures:
6. Local Storage Management #
JavaScript can store and retrieve data in the browser:
// Local storage utilities
const StorageManager = {
// Save data to local storage
save: function(key, data) {
try {
localStorage.setItem(key, JSON.stringify(data));
console.log(`Data saved to ${key}`);
} catch (error) {
console.error('Storage error:', error);
}
},
// Retrieve data from local storage
load: function(key) {
try {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
} catch (error) {
console.error('Storage retrieval error:', error);
return null;
}
},
// Remove data from local storage
remove: function(key) {
localStorage.removeItem(key);
console.log(`${key} removed from storage`);
}
};
// Usage example
StorageManager.save('userPreferences', { theme: 'dark', language: 'en' });
const preferences = StorageManager.load('userPreferences');
7. Date and Time Manipulation #
JavaScript can handle complex date and time operations:
8. Event Handling and User Interaction #
JavaScript can respond to user actions and browser events:
// Comprehensive event handling
function setupEventHandlers() {
// Mouse events
document.addEventListener('click', function(event) {
console.log(`Clicked at: ${event.clientX}, ${event.clientY}`);
});
// Keyboard events
document.addEventListener('keydown', function(event) {
if (event.ctrlKey && event.key === 's') {
event.preventDefault();
console.log('Save shortcut triggered!');
}
});
// Window events
window.addEventListener('resize', function() {
console.log(`Window resized to: ${window.innerWidth}x${window.innerHeight}`);
});
// Scroll events
window.addEventListener('scroll', function() {
const scrollPercent = (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100;
console.log(`Scroll progress: ${scrollPercent.toFixed(1)}%`);
});
}
9. Animation and Visual Effects #
JavaScript can create smooth animations and visual effects:
// Animation utilities
function createSmoothAnimation() {
const element = document.getElementById('animated-element');
let position = 0;
let direction = 1;
function animate() {
position += direction * 2;
if (position >= 200 || position <= 0) {
direction *= -1;
}
element.style.transform = `translateX(${position}px)`;
requestAnimationFrame(animate);
}
animate();
}
// CSS-like transitions in JavaScript
function fadeElement(element, fadeIn = true) {
const duration = 500;
const startTime = performance.now();
function updateOpacity(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
element.style.opacity = fadeIn ? progress : 1 - progress;
if (progress < 1) {
requestAnimationFrame(updateOpacity);
}
}
requestAnimationFrame(updateOpacity);
}
10. Mathematical Calculations and Algorithms #
JavaScript can perform complex calculations and implement algorithms:
Summary #
These practical examples demonstrate what JavaScript can do across different domains:
- UI Manipulation: Create dynamic content and interactive elements
- Data Processing: Handle complex data transformation and analysis
- User Interaction: Respond to events and provide real-time feedback
- API Communication: Fetch and process external data
- Storage Management: Persist data in the browser
- Visual Effects: Create animations and smooth transitions
- Mathematical Operations: Perform calculations and implement algorithms
JavaScript's versatility makes it an essential tool for modern web development, capable of handling everything from simple interactions to complex applications.