🟨

JavaScript

Modern JavaScript development, jQuery och best practices

Vad du hittar här

Praktiska JavaScript-exempel, från grundläggande funktioner till moderna ES6+ patterns. Innehåller också jQuery-exempel och optimeringsstrategier för webbutveckling.

Innehåll

3
Core Examples
3
jQuery Examples
3
Modern JS Patterns
4
Best Practices

Core JavaScript Examples

🔄

Reload Current Page

Programmatically reload the current page using JavaScript.

window.location.assign(window.location.href);

💡 Förklaring: This assigns the current URL to itself, causing a page reload

🆔

Generate Random GUID

Generate a universally unique identifier (UUID/GUID) in JavaScript.

function NewGuid() {
  var d = new Date().getTime();
  var uuid = 'xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
  return uuid;
}

// Usage
const newId = NewGuid();
console.log(newId); // e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"

💡 Förklaring: Creates a Version 4 UUID using timestamp and random numbers

📅

Date Formatting Extension

Extend Date prototype to format dates as YYYY-MM format.

Date.prototype.yyyymm = function() {
  var yyyy = this.getFullYear().toString();
  var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based
  return yyyy + '-' + (mm[1] ? mm : "0" + mm[0]); // padding
};

// Usage
const date = new Date();
console.log(date.yyyymm()); // "2024-03"

💡 Förklaring: Adds a method to all Date objects for consistent date formatting

jQuery Examples

jQuery UI Datepicker Configuration

Configure jQuery UI datepicker with custom date format and controls.

$('.js-datepicker').datepicker({
  dateFormat: "yy-mm-dd",
  changeMonth: true,
  changeYear: true,
  showButtonPanel: true,
  closeText: "Close",
  currentText: "Today"
});

📝 Notera: Sets ISO date format and enables month/year dropdowns

AJAX Form Submission

Submit form data using jQuery AJAX with error handling.

$('#myForm').on('submit', function(e) {
  e.preventDefault();
  
  $.ajax({
    url: $(this).attr('action'),
    method: 'POST',
    data: $(this).serialize(),
    success: function(response) {
      console.log('Success:', response);
      // Handle success
    },
    error: function(xhr, status, error) {
      console.error('Error:', error);
      // Handle error
    }
  });
});

📝 Notera: Prevents default form submission and uses AJAX instead

Dynamic Content Loading

Load content dynamically and handle loading states.

function loadContent(url, targetElement) {
  $(targetElement).html('<div className="loading">Loading...</div>');
  
  $.get(url)
    .done(function(data) {
      $(targetElement).html(data);
    })
    .fail(function() {
      $(targetElement).html('<div className="error">Failed to load content</div>');
    });
}

// Usage
loadContent('/api/content', '#content-container');

📝 Notera: Shows loading indicator and handles both success and error states

Modern JavaScript (ES6+)

ES6+ Arrow Functions

Modern arrow function syntax and usage patterns.

// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;

// Array methods with arrow functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

Async/Await Pattern

Modern asynchronous JavaScript using async/await.

// Fetch data with async/await
async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const userData = await response.json();
    return userData;
  } catch (error) {
    console.error('Error fetching user data:', error);
    throw error;
  }
}

// Usage
const userData = await fetchUserData(123);

Destructuring and Spread

Modern JavaScript destructuring and spread operator patterns.

// Object destructuring
const user = { name: 'John', age: 30, email: 'john@example.com' };
const { name, age, ...rest } = user;

// Array destructuring
const [first, second, ...others] = [1, 2, 3, 4, 5];

// Spread operator
const newUser = { ...user, age: 31 };
const newArray = [...numbers, 6, 7, 8];

// Function parameter destructuring
function updateUser({ id, name, email }) {
  // Update user with provided fields
}

Best Practices

Use Strict Mode

Always use 'use strict' to catch common coding mistakes

💡 Exempel: Add 'use strict'; at the top of JavaScript files

Avoid Global Variables

Minimize global scope pollution by using modules or namespaces

💡 Exempel: Use IIFE patterns or modern ES6 modules

Handle Errors Gracefully

Always include error handling for asynchronous operations

💡 Exempel: Use try/catch with async/await or .catch() with Promises

Use Semantic Variable Names

Choose descriptive names that explain the variable's purpose

💡 Exempel: Use 'userEmail' instead of 'ue' or 'data'

Performance Optimization

🚀 DOM Manipulation

Minimize direct DOM access and batch DOM updates

🔧 Lösning: Use document fragments or virtual DOM libraries for complex updates

🚀 Event Delegation

Use event delegation instead of attaching listeners to many elements

🔧 Lösning: Attach one listener to parent element and use event.target

🚀 Debounce User Input

Prevent excessive function calls on user input events

🔧 Lösning: Use debouncing for search inputs, resize handlers, etc.

🚀 Lazy Loading

Load content only when needed to improve initial page load

🔧 Lösning: Use Intersection Observer API for images and content

💡JavaScript Development Tips

Använd utvecklarverktygen

Lär dig att använda webbläsarens utvecklarverktyg för debugging och performance-analys.

Testa kod regelbundet

Skriv och kör tester för dina JavaScript-funktioner med Jest eller liknande ramverk.

Håll dig uppdaterad

JavaScript utvecklas snabbt - följ MDN Web Docs och moderna best practices.