Understanding Array Swapping in JavaScript Step-by-Step Guide

 

1. Basic Swap (Using Temporary Variable)

Concept: Use a temporary variable to hold one value during the swap.

javascript
// Step 1: Initialize array
let fruits = ["🍎", "🍌", "🍊"];

// Step 2: Define swap positions
const indexA = 0; // Apple
const indexB = 2; // Orange

// Step 3: Swap using a temporary variable
const temp = fruits[indexA];
fruits[indexA] = fruits[indexB];
fruits[indexB] = temp;

console.log(fruits); // Output: ["🍊", "🍌", "🍎"]

2. Destructuring Assignment (ES6)

Concept: Swap elements in one line using array destructuring.

javascript
let colors = ["red", "green", "blue"];

// Swap index 1 (green) and 2 (blue)
[colors[1], colors[2]] = [colors[2], colors[1]];

console.log(colors); // Output: ["red", "blue", "green"]

3. Using splice() for Complex Swaps

Concept: Remove and insert elements at specific positions.

javascript
let numbers = [1, 2, 3, 4];

// Swap index 0 (1) and index 3 (4)
const removed = numbers.splice(0, 1); // Remove 1 element at index 0 → [1]
numbers.splice(3, 0, removed[0]); // Insert removed element at index 3

console.log(numbers); // Output: [2, 3, 4, 1]

4. Advanced: Swap Function with Validation

Create a reusable function that validates indices before swapping:

javascript
function swapArrayElements(arr, index1, index2) {
  if (
    index1 < 0 || index2 < 0 || // Negative indices
    index1 >= arr.length ||     // Indices out of bounds
    index2 >= arr.length
  ) {
    console.error("Invalid indices!");
    return arr; // Return original array
  }
  [arr[index1], arr[index2]] = [arr[index2], arr[index1]]; // Destructure swap
  return arr;
}

// Test
const animals = ["🐶", "🐱", "🐭", "🐹"];
swapArrayElements(animals, 1, 3); // Swap cat and hamster
console.log(animals); // Output: ["🐶", "🐹", "🐭", "🐱"]

5. Real-World Example: Sorting Adjacent Elements

Swap adjacent elements to "bubble" a value up/down (e.g., simple sorting):

javascript
let scores = [50, 30, 40, 20];

// Bubble up: Swap lower value to the right
for (let i = 0; i < scores.length - 1; i++) {
  if (scores[i] < scores[i + 1]) {
    // Swap if current element < next element
    [scores[i], scores[i + 1]] = [scores[i + 1], scores[i]];
  }
}

console.log(scores); // Output: [50, 40, 30, 20] (50>40, others adjusted)

Key Notes:

  1. Destructuring is concise but avoid using it on sparse arrays (holes).

  2. Always validate indices to prevent runtime errors.

  3. For large arrays, temporary variables are performance-optimal.

  4. Non-mutating approach: Create a new array if you need immutability:

    javascript
    const newArr = [...arr]; // Copy array
    [newArr[i], newArr[j]] = [newArr[j], newArr[i]]; // Swap in copy

Practice Exercise:

Swap the first and last elements of any array without knowing its length:

javascript
// Solution:
let arr = [10, 20, 30, 40];
[arr[0], arr[arr.length - 1]] = [arr[arr.length - 1], arr[0]];
console.log(arr); // [40, 20, 30, 10]

JavaScript Cheat Sheet that covers all the important concepts, syntax











Overview of Common Roles in .NET Projects

 

Role Responsibilities Tech Stack Relevance
  • Backend Developer
  • Write APIs, business logic, integrate with databases
  • All: .NET Framework, Core, and .NET 5/6/7/8
  • Frontend Developer
  • Build UI (e.g., Razor pages, Blazor, Angular/React)
  • .NET Core+, with Blazor or JS SPA frameworks
  • Full Stack Developer
  • Handles both backend and frontend
  • More common in .NET Core and .NET 5+
  • DevOps Engineer
  • CI/CD, deployment, cloud (Azure, Docker, Kubernetes)
  • Mostly .NET Core and .NET 5/6/7/8
  • Solution Architect
  • Designs system architecture
  • All versions
  • QA/Test Engineer
  • Writes unit/integration tests, automation scripts
  • All (Test tools differ slightly)
  • Database Developer
  • DB schema design, stored procedures, EF Core configuration
  • All, but EF Core used from .NET Core onward
  • Legacy Support Engineer
  • Maintain/upgrade older apps (e.g., ASP.NET Web Forms)
  • Mostly .NET Framework
  • Cloud Engineer
  • Cloud-first design (Azure Functions, App Services)
  • .NET Core and .NET 5/6/7+

What is Agile? Explain.

 Ans. 

Agile is a project management methodology that emphasizes flexibility, collaboration, and iterative development.

  • Agile focuses on delivering working software in short, iterative cycles called sprints.

  • It values customer collaboration, responding to change, and continuous improvement.

  • Scrum and Kanban are popular Agile frameworks used in software development.

  • Agile promotes self-organizing teams and regular feedback to adapt to changing requirements.

What are the methods to transfer data between components in Angular?

 Ans. 

Methods to transfer data between components in Angular include Input and Output properties, ViewChild, Services, and Event Emitters.

  • Using Input and Output properties to pass data from parent to child components and emit events from child to parent components.

  • Using ViewChild to access child components and their properties directly from the parent component.

  • Using Services to create a shared service that can be injected into multiple components to share data.

  • Using Event Emitters to emit custom events from child components that can be subscribed to in parent components.

Reversing an array in JavaScript can be done in several ways depending on the specific use case. Below, I’ll show all major types of examples

 

. Using the Built-in .reverse() Method

This is the simplest and most direct way.

javascript

let arr = [1, 2, 3, 4, 5]; arr.reverse(); console.log(arr); // [5, 4, 3, 2, 1]

⚠️ This method mutates the original array.


🔁 2. Using the Spread Operator & .reverse() (Non-mutating)

To avoid changing the original array:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = [...arr].reverse(); console.log(reversed); // [5, 4, 3, 2, 1] console.log(arr); // [1, 2, 3, 4, 5] — unchanged

🔁 3. Using a for Loop

Manual reverse using a classic for loop:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = []; for (let i = arr.length - 1; i >= 0; i--) { reversed.push(arr[i]); } console.log(reversed); // [5, 4, 3, 2, 1]

🔁 4. Using a while Loop

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = []; let i = arr.length - 1; while (i >= 0) { reversed.push(arr[i]); i--; } console.log(reversed); // [5, 4, 3, 2, 1]

🔁 5. Using Recursion

A functional way to reverse an array:

javascript

function reverseArray(arr) { if (arr.length === 0) return []; return [arr.pop()].concat(reverseArray(arr)); } let arr = [1, 2, 3, 4, 5]; console.log(reverseArray([...arr])); // [5, 4, 3, 2, 1]

🔁 This also mutates the original if not cloned with [...arr].


🔁 6. Using reduceRight()

A more functional-style approach:

javascript

let arr = [1, 2, 3, 4, 5]; let reversed = arr.reduceRight((acc, curr) => { acc.push(curr); return acc; }, []); console.log(reversed); // [5, 4, 3, 2, 1]

🔁 7. Swapping Elements In-Place

This doesn't use extra space and is optimal for large arrays:

javascript

let arr = [1, 2, 3, 4, 5]; for (let i = 0; i < arr.length / 2; i++) { let temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } console.log(arr); // [5, 4, 3, 2, 1]

Summary Table:

MethodMutates?Extra SpaceNotes
.reverse()Simple, in-place
[...arr].reverse()Clones, safer
for/while loopGood for manual control
Recursion✅ or ❌Elegant but less efficient
reduceRight()Functional-style
In-place swapOptimal for performance


What is the difference between authorization and authentication?

 Ans. 

Authentication verifies the identity of a user, while authorization determines what a user can access.

  • Authentication confirms the user's identity through credentials like username and password.

  • Authorization controls the user's access to resources or features based on their authenticated identity.

  • Example: Logging into a website (authentication) and then being able to view/edit specific pages based on user roles (authorization).

To solve this problem, we need to reverse a singly linked list. The goal is to reverse the direction of the pointers in the list such that the last node becomes the first node, and the first node becomes the last node.

 

Approach

The approach involves iterating through the linked list while reversing the pointers of each node. Here’s a step-by-step breakdown:

  1. Initialization: Start with two pointers, prev and current. The prev pointer is initialized to null because the new tail (originally the first node) should point to null after reversal. The current pointer starts at the head of the list.

  2. Iteration: Traverse the list with the current pointer. For each node:

    • Store the next node: Temporarily store the next node of the current node to avoid losing the reference when we change the current node's pointer.

    • Reverse the pointer: Set the current node's next pointer to point to the prev node.

    • Move pointers forward: Update prev to be the current node and move current to the next node in the original list (which was stored earlier).

  3. Termination: Once current becomes null, the prev pointer will be at the new head of the reversed list. Return prev.

This approach efficiently reverses the list in a single pass through the nodes with constant space complexity, making it optimal.

Solution Code

javascript
class ListNode {
  constructor(val = 0, next = null) {
    this.val = val;
    this.next = next;
  }
}

function reverseList(head) {
  let prev = null;
  let current = head;
  
  while (current !== null) {
    const nextTemp = current.next;
    current.next = prev;
    prev = current;
    current = nextTemp;
  }
  
  return prev;
}

// Debug your code below
let head = new ListNode(1, new ListNode(2));
let reversedHead = reverseList(head);
console.log(reversedHead.val);
console.log(reversedHead.next.val);

Explanation

  • Initialization: The prev pointer starts as null because the first node of the original list will become the last node in the reversed list, pointing to null. The current pointer starts at the head of the list.

  • Loop Through List: For each node, we:

    1. Store the next node (nextTemp) to remember the rest of the list.

    2. Reverse the current node's pointer to point to prev.

    3. Move prev to the current node and current to the next node (nextTemp).

  • Termination: When current becomes nullprev will be pointing to the last node of the original list, which is now the head of the reversed list. We return prev as the new head.

Advanced Angular Methods & Real-World Scenarios

  1.  ViewChild  /  ViewChildren Purpose : Access DOM elements or child components programmatically. Scenario : Video player controls in a m...

Best for you