Comparative Programming: JavaScript and Python (Part 2)
This is second part of the comparative programming article. If you have not read the first article, you check it here.
Data Structures
In computing, data structures means a container that can hold a collection of items, that can be looped through. They can vary in different programming languages.
Arrays & Lists
sometimes called a vector, is a data structure that holds a collection of items, most often used as an iterable sequence.
JavaScript: let myArray = [1,2,3,4,5];
Python: my_list = [1,2,3,4,5]
Lists/arrays can have any type of data in them as long as you follow the syntax rules. They can be populated with strings, numbers, booleans, and even other lists and data types. The types can be mixed as well. Here is an example of how to create an array that contains many different types of data
let myMixedArray = [1,"Apple", true, [1,2,3], undefined];
You can loop through an array/list and perform some operations on its items in sequence, like this Python code which prints out a series of fruits. The variable fruit
takes on the value of the next item in the fruits
collection.
fruits = ['apple', 'orange', 'banana', 'pear', 'plum']
for fruit in fruits:
print(fruit)
And here’s the equivalent code in JavaScript (note that there are other ways to do this in JavaScript as well). The fruits.length
attribute represents the total number of items in the array, so this code essentially says, "beginning with the first item (item [0]
), and as long as i
is less than the length of the array, print the array item and then increment i
let fruits = ['apple', 'orange', 'banana', 'pear', 'plum'];
for (let i = 0; i < fruits.length; i++){
console.log(fruits[i]);
}
Array indexes start from 0, not 1. So the index of the first item in an array is 0, the second item has an index of 1, the third has an index of 2 etc.
There are a number of methods and attributes to these arrays, lists or vectors as however languages refer to them

Runnable Example JavaScript
let fruits = ['apple', 'orange', 'banana', 'pear', 'plum'];
// Print all fruits
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Reverse the list
fruits.reverse();
console.log(fruits);
// Sort the list alphabetically:
fruits.sort();
console.log(fruits);
Python
fruits = ['apple', 'orange', 'banana', 'pear', 'plum']
# Print all fruits
for fruit in fruits:
print(fruit)
print()
# Get an item located in a list
second_item = fruits[1]
print(second_item)
print()
# Add an item to the list
fruits.append('cherries')
print(fruits)
print()
# Reverse the list
fruits.reverse()
print(fruits)
# Sort the list alphabetically:
fruits.sort()
print(fruits)
Objects & Dictionaries
An object or dictionary is another type of data structure that holds a collection of items. Like lists and arrays, dictionaries (which are called objects in JavaScript), are typically used to organize data. Also like lists, they are mutable (changeable), can grow or shrink as needed, and can be nested and contain any type of data. In contrast to lists and arrays though, which use indexes to access their items, dictionaries and objects are made up of named key/value pairs. In other programming languages outside JavaScript and Python, these data structures may be known by other names such as associative arrays or hashmaps.

JavaScript: properties should be immutable
let myObject = {
property1: 'value1',
property2: 'value2',
property3: 'value3',
};
Python: keys should be immutable
my_dict = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
}
To access a specific value from a dictionary, you use its key by placing it in square brackets ([]
).
my_dict = {
'some_number': 12,
'a_string': 'Hello world!',
'nested_list': [1, 2, 3],
'a_boolean': True,
}
print(my_dict['some_number']) # prints 12
print(my_dict['a_string']) # prints 'Hello world!'
print(my_dict['nested_list']) # prints [1, 2, 3]
print(my_dict['a_boolean']) # prints True
In JavaScript, a bracket or a dot notation is used:
let myObject = {
property1: 'value1',
property2: 'value2',
property3: 'value3',
};
console.log(myObject.property1); // logs 'value1'
console.log(myObject.property2); // logs 'value2'
console.log(myObject.property3); // logs 'value3'
// or ...
console.log(myObject['property1']); // logs 'value1'
console.log(myObject['property2']); // logs 'value2'
console.log(myObject['property3']); // logs 'value3'
Sets
Sets are similar to other data structures but unique in a few ways:
- Sets are mutable, but their members cannot be changed. Once an item is added to a set, it must be removed and replaced in order to be changed.
- Sets are unordered. There is no way to reference an item by index or name in a set.
- Sets cannot contain duplicate values. For this reason they can be useful in eliminating duplicates from other data structures.
JavaScript: let mySet = new Set([1,2,3,4,5])
Python: my_set = set([1,2,3,4,5])
Sets can have multiple data types at the same time, but should not contain other iterables like lists, dictionaries or other sets:
let myMixedSet = new Set(1, 'Apple', true); // ok
let myMixedSet = new Set(1, 'Apple', [1, 2, 3]); // not ok, set contains a list
Sets are iterable. In Python, its easy to iterate than in JavaScript
directions = {'north', 'south', 'east', 'west'}
for direction in directions:
print(direction)
Some common methods in sets:

Example in JavaScript:
// Create a set
let directions = new Set(['north', 'south', 'east', 'west']);
// Display the set
console.log(directions);
// Add an item to the set:
directions.add('northwest');
// Display it again
console.log(directions);
Example in Python:
# Create a set
directions = set(['north', 'south', 'east', 'west'])
# Print its members
for direction in directions:
print(direction)
# Add an item to the set:
directions.add('northwest')
print()
# Print the members again
# Notice the order cannot be relied upon!
for direction in directions:
print(direction)
Nested & Multi-dimensional Data Structures
Nested or multi-dimensional data structure is simply one data structure with another inside it as one of its elements.
- Nesting a list inside another list
- Nesting a list inside a dictionary
- Nesting a dictionary inside a list
- Nesting a dictionary inside another dictionary
- Nesting a set inside a list or dictionary
Important: because sets require their members to be immutable, you cannot nest iterable data structures like lists, dictionaries and other sets inside of a set.
JavaScript:
let contacts = [
{
name: 'Joe',
phoneNumber: '123456789'
},
{
name: 'Mary',
phoneNumber: '456789123'
},
{
name: 'Dad',
phoneNumber: '789132456'
},
];
console.log(contacts[0]) // will print below
{
name: 'Joe',
phoneNumber: '123456789'
}
Python:
foods = {
'dairy': ['milk', 'cheese', 'yogurt'],
'grains': ['oats', 'cereal', 'pasta'],
'fats_and_sweets': ['chocolate', 'sugar', 'butter'],
'fruits': ['apples', 'oranges', 'bananas'],
'vegetables': ['broccoli', 'beans', 'peas']
}
print(foods['dairy'])
['milk', 'cheese', 'yogurt']
The nested structures show up when working with APIs and in web frameworks such as Django and Flask.
Recap: Navigation and Iteration of Data Structures

- Arrays and lists, which contain simple sequences of values
- Objects and dictionaries, which contain key/value pairs
- Sets, which are like lists except for some restrictions on how they can be modified
The first two items above can be both iterated (looped through) and indexed (i.e. you can pull a specific item out of them). The last item, sets, only supports iteration, and in fact in JavaScript it requires a more complex method of iteration since sets don’t support indexing.
You can also access a nested list/array item by simply drilling down into the nested list or array’s indexes:
let controls = [
['up', 'down', 'left', 'right'],
['a', 'b', 'select', 'start']
];
// Each array item is another array
// logs ['up', 'down', 'left', 'right']
console.log(controls[0]);
// logs ['a', 'b', 'select', 'start']
console.log(controls[1]);
// In the first sub-array (index 0) each item is a direction
console.log(controls[0][0]); // logs 'up'
console.log(controls[0][1]); // logs 'down'
console.log(controls[0][2]); // logs 'left'
console.log(controls[0][3]); // logs 'right'
// In the second sub-array (index 1) each item is a button
console.log(controls[1][0]); // logs 'a'
console.log(controls[1][1]); // logs 'b'
console.log(controls[1][2]); // logs 'select'
console.log(controls[1][3]); // logs 'start'
Python:
foods = {
'dairy': ['milk', 'cheese', 'yogurt'],
'grains': ['oats', 'cereal', 'pasta'],
'fats_and_sweets': ['chocolate', 'sugar', 'butter'],
'fruits': ['apples', 'oranges', 'bananas'],
'vegetables': ['broccoli', 'beans', 'peas']
}
print(foods['dairy']) # prints ['milk', 'cheese', 'yogurt']
print(foods['dairy'][0]) # prints 'milk'
print(foods['dairy'][1]) # prints 'cheese'
print(foods['dairy'][2]) # prints 'yogurt'
The data can also be accessed using a combination of keys, indexes and loops:
let contacts = [
{
name: 'Joe',
phoneNumber: '123456789',
address: {
street: '123 45th Street',
city: 'Summerville',
country: 'USA'
}
},
{
name: 'Mary',
phoneNumber: '456789123',
address: {
street: '47 Grafton Street',
city: 'Dublin',
country: 'Ireland'
}
},
{
name: 'Dad',
phoneNumber: '789132456',
address: {
street: '18 Downings Road',
city: 'Warwick',
country: 'UK'
}
},
];
console.log(contacts[0]['name']); // 'Joe'
console.log(contacts[0]['address']['city']); // 'Summerville
console.log(contacts[2]['phoneNumber']); // '789132456'
// Don't forget you can use dot notation too:
console.log(contacts[1].address.street); // '47 Grafton Street'
// loops
for (let i = 0; i < contacts.length; i++) {
console.log(contacts[i].name); // Joe, Mary, Dad
}
Manipulation of Data Structures
Arrays, lists, objects, dictionaries and sets can be modified in two main ways:
- Manually, which means you use the native syntax of the language you’re working.
- Methodically, which means you use methods or functions that are part of the data structures themselves.
Arrays/Lists:
Modifying a list or array element is simple. All you need to do is use its index and provide the new value, such as in this Python example which updates the first element in the list (index 0):
directions = ['north', 'south', 'east', 'west']
print(directions[0]) # 'north'
directions[0] = 'northwest'
print(directions[0]) # 'northwest'
# The list now looks like this
# ['northwest', 'south', 'east', 'west']
Modifying all elements or larger lists:
directions = ['north', 'south', 'east', 'west']
i = 0
while i < len(directions):
directions[i] = directions[i].upper() # make them all uppercase!
i += 1
print(directions) # ['NORTH', 'SOUTH', 'EAST', 'WEST']
Modifying using built-in methods:
directions = ['north', 'south', 'east', 'west']
directions.append('northwest')
print(directions) # ['north', 'south', 'east', 'west', 'northwest']
directions.remove('northwest')
print(directions) # ['north', 'south', 'east', 'west']
directions.sort()
print(directions) # ['east', 'north', 'south', 'west']
directions.reverse()
print(directions) # ['west', 'south', 'north', 'east']
directions.insert(1, 'northwest') # insert 'northwest' at index 1
print(directions) # ['north', 'northwest', 'south', 'east', 'west']
This is where I finish today. In the next, I will write about Functions in both JavaScript and Python.