⚡ JavaScript

जावास्क्रिप्ट (Node.js) में शब्दकोश और हैश तालिकाएँ: विस्तृत मार्गदर्शिका

Dictionaries and Hash Tables in JavaScript

Introduction: What is it and why?

Imagine you have a backpack with items, but each item has its own name tag. For example, the tag "favorite toy" points to a ball, and the tag "treat" points to a chocolate bar. To quickly find the chocolate bar, you don't rummage through the entire backpack, but simply look at the "treat" tag.

A dictionary (or object) in JavaScript works exactly the same way! It is a special data structure where each value (chocolate bar) has its own key (the "treat" tag).

Dictionaries help you:

  • Quickly find information by name (key)
  • Store related data together (e.g., a person's name and their phone number)
  • Easily add, modify, and delete entries

Basic syntax with examples

A dictionary is created using curly braces {}. Inside, we write "key: value" pairs, separating them with commas.

// Creating a dictionary with greetings
const greetings = {
  "Russia": "Hello!",
  "France": "Bonjour!",
  "Italy": "Ciao!"
};

// Output the greeting for Russia
console.log(greetings["Russia"]); // Hello!

You can work with keys like variables. Let's look at the basic operations:

// Creating an empty phone book
const phoneBook = {};

// Adding entries
phoneBook["Anna"] = "8-999-123-45-67";
phoneBook["Boris"] = "8-999-765-43-21";

// Getting a value by key
console.log(phoneBook["Anna"]); // 8-999-123-45-67

// Changing an existing entry
phoneBook["Anna"] = "8-999-000-00-00";

// Deleting an entry
delete phoneBook["Boris"];

console.log(phoneBook); // { Anna: '8-999-000-00-00' }

Another convenient way is to use dot notation, if the key consists of a single word without spaces:

const book = {};
book.title = "War and Peace";
book.author = "Leo Tolstoy";
console.log(book.author); // Leo Tolstoy

Analysis of typical tasks

Task 1: Greeting for a traveler

You need to create a dictionary where the key is a country and the value is a greeting. The user enters a country, the program outputs the greeting.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

const dictionary = {
  "Russia": "Hello!",
  "France": "Bonjour!",
  "Italy": "Ciao!",
  "Spain": "¡Hola!"
};

readline.question('Enter country: ', (country) => {
  if (dictionary[country]) {
    console.log(`Greeting: ${dictionary[country]}`);
  } else {
    console.log('Country not found in dictionary');
  }
  readline.close();
});

Task 2: Phone book

We have a directory with names and numbers. We need to find a number by name.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

const phoneBook = {
  "Ivan": "8-111-222-33-44",
  "Maria": "8-555-666-77-88",
  "Peter": "8-999-888-77-66"
};

readline.question('Enter name: ', (name) => {
  if (phoneBook[name]) {
    console.log(`Phone ${name}: ${phoneBook[name]}`);
  } else {
    console.log('Subscriber not found');
  }
  readline.close();
});

Task 3: Weekly planner (weekly plan)

Creating a dictionary where the keys are days of the week, and the values are to-do lists.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

const weekPlan = {};
const days = ["Monday", "Tuesday", "Wednesday"];

function addTask() {
  if (days.length === 0) {
    console.log("Ready plan:");
    console.log(weekPlan);
    readline.close();
    return;
  }
  
  const day = days.shift();
  readline.question(`What are we doing on ${day}? `, (task) => {
    weekPlan[day] = task;
    addTask();
  });
}

addTask();

Task 4: Digital notepad (deleting a contact)

Deleting a contact from the dictionary using the delete operator.

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

const contacts = {
  "Anna": "8-111-111-11-11",
  "Boris": "8-222-222-22-22",
  "Vika": "8-333-333-33-33"
};

console.log("Current contacts:", Object.keys(contacts));

readline.question('Who to delete? ', (name) => {
  if (contacts[name]) {
    delete contacts[name];
    console.log(`${name} deleted. Remaining:`, Object.keys(contacts));
  } else {
    console.log("No such contact");
  }
  readline.close();
});

Task 5: Dictionary keys (product list)

Output all product names from the dictionary using Object.keys().

const products = {
  "Bread": 50,
  "Milk": 80,
  "Apples": 120,
  "Cheese": 200
};

console.log("Product list:");
const names = Object.keys(products);
for (let i = 0; i < names.length; i++) {
  console.log(`${i + 1}. ${names[i]} — ${products[names[i]]} rub.`);
}

Common beginner mistakes

  1. Forgetting to put commas between pairs
    // Incorrect
    const obj = {a: 1 b: 2} // Error!
    
    // Correct
    const obj = {a: 1, b: 2}
  2. Confusing keys with variables
    // Incorrect
    const key = "name";
    const obj = {key: "Anna"}; // Creates key "key", not "name"
    
    // Correct
    const key = "name";
    const obj = {[key]: "Anna"}; // Creates key "name"
  3. Trying to access a non-existent key
    const obj = {a: 1};
    console.log(obj.b); // undefined (not an error, but can be surprising)
  4. Using dot notation for keys with spaces
    // Incorrect
    const obj = {};
    obj.my key = 5; // Error!
    
    // Correct
    obj["my key"] = 5;

Final example: "Book Library"

Let's create a program that