Javascript map demo

In this simple Javascript map demo example we are going to create a map object and then populate it with the key and value pair. This map object is just like the dictionary object in python, it takes in a key and a value pair where the key can then be used to access the value. The value can be anything, a variable, a function or an object. Below javascript program will create two objects, the person and his salary, then keeps both of them within a map object where those two objects can then be accessed through their related key later on.

let salary = {
		getSalary : function() {
						return this.salary;
			
		},
		setSalary : function(salary) {
						this.salary = salary;
					}
}

let person = {
		getName : function() {
						return this.name;
			
		},
		setName : function(name) {
				this.name = name;
		}
}

let map = new Map();

map.set("person", person);
map.set("salary", salary);

map.get("person").setName("John");
map.get("salary").setSalary(3000);

console.log(map.get("person").getName() + " monthly salary is " + map.get("salary").getSalary());

map.get("person").setName("Jimmy");
map.get("salary").setSalary(4000);

console.log(map.get("person").getName() + " monthly salary is " + map.get("salary").getSalary());

The program above returns the below outcome…

John monthly salary is 3000
Jimmy monthly salary is 4000

The variable such as name will be created for us when we set it’s value for the first time!

Leave a Reply

Be the First to Comment!

avatar
  Subscribe  
Notify of