Parallels Between Python and JavaScript

2990 VIEWS

· ·

When you have amassed voluminous experience in using a programming language and later switched to a new one, you unconsciously tend to think of the new language in terms of the previous. “How do I achieve X feature from Y language in Z language?” For example, “How do I use the concept of list comprehension from Python in JavaScript?” Drawing such parallels and patterns is an effective method of learning new things.

For me, this inadvertently happened when I dabbled my curiosity in Python after a long ride on the JavaScript terrain. One memorable moment was when I discovered that JavaScript’s Object Destructuring had an identical semantic effect as Unpacking in Python.

In this article, I share with you 7 of the semantic parallels between Python and JavaScript I found, and how they slightly differ from each other in syntax and usage. Let’s get started!

Prerequisites

To understand the concepts being juxtaposed in this article, you should have experience coding in both JavaScript and Python.

Table of Contents
  1. Spread Operator and List Comprehension?
  2. Object Destructuring and Unpacking
  3. Object.entries and .items()
  4. Swapping Variables
  5. Ternary Operator
  6. Using Higher-Order Functions
    • Map
    • Filter
    • Reduce
  7. Module Imports
    • Namespace imports
    • Importing one item
    • Importing multiple items
    • Importing with aliases

1. Spread Operator and List Comprehensions

In programming, we handle assignments with respect to Reference Types (such as arrays, lists, and objects) differently. Consider the scenario below.

 const A = [1,2,3,4,5]
 const B = A

In the above code, the content of A is not copied into B but rather both A and B point to [1,2,3,4,5] in memory. In effect, they are sharing the same array, not having their individual copies. Hence, any modification made via A affects B and vice versa, as demonstrated below.

  A.push(12);
  console.log(B); // [1,2,3,4,5,12]
  console.log(A); // [1,2,3,4,5,12]

Although 12 was added to A, printing B showed the updated array content because B points to the same array as A in memory. To circumvent this unexpected behavior, the contents of A should be copied individually into B using a loop.

 const A = [1, 2, 3, 4, 5];
 const B = [];
 
 for (let i = 0; i < A.length; i++) {
   B.push(A[i]);
 }

However, there are more succinct ways to copy elements from one variable to another other than a traditional loop. In JavaScript, the spread operator ( … ) can be used.

  const A = [1, 2, 3, 4, 5];
  const B = [...A];
 
  console.log(A); // [1,2,3,4,5]
  console.log(B); // [1,2,3,4,5]
 
  A.push(21);
  console.log(A); // [1,2,3,4,5,21]
 
  console.log(B); // [1,2,3,4,5]

In Python, this can be achieved with list comprehension.

  A = [1,2,3,4,5]
  B = [num for num in A]
 
  print(A) # [1,2,3,4,5]
  print(B) # [1,2,3,4,5]
 
  A.append(21)
  print(A) # [1,2,3,4,5,21]
  print(B) # [1,2,3,4,5]

2. Object Destructuring and Unpacking 

Both destructuring (in JavaScript) and unpacking (in Python) are used to extract values from a list/array into variables.

Destructuring in Javascript:

  const student = ["Dolores Abernathy", 21]
 
  const [name,age] = student
 
  console.log(name) // Dolores Abernathy
  console.log(age) // 21

In the above example, the contents of the student array were extracted into name and age respectively.

Python’s Unpacking:

  student = ["Dolores Abernathy", 21]
  name,age = student
 
  print(name) # Dolores Abernathy
  print(age)  # 21

The major difference is that in Python, no square brackets are involved during the extraction.

3. Object.entries and .items() 

Objects in javascript are similar to dictionaries in python. They both store data values in key,value pairs and do not allow duplicate keys. Duplicate keys will override existing keys.

Object.entries returns an array of the key,value pairs in the object.

.items() method returns a list of tuples of the key,value pairs in the dictionary.

Javascript’s Object.entries:

const student = {
    name: "Dolores Abernaty",
    age: 21
}
 
const result = Object.entries(student)
console.log(result) // [ ["name","Dolores Abernathy"], ["age",21] ]

Python’s .items() method:

student = {
    'name': 'Dolores Abernathy',
    'age': 21
}
 
print(list(student.items())) # [('name', 'Dolores Abernathy'), ('age', 21)]

Assuming we want to display on the screen the content of the student object/dictionary in this fashion.

name -> Dolores Abernathy
Age -> 21
for (let [key, value] of Object.entries(student)) {
  console.log(key + " -> " + value);
}

Notice how we used object destructuring to extract the key and value.

for key,value in student.items():
      print(key + " -> " + value)

Here, too, we unpacked the key and value from the returned tuple.

4. Swapping Variables

Traditionally, here is how we would swap 2 variables (using a third helper variable).

first = "i am first"
second = "i am second"
 
# swapping
helper = first
first = second
second = helper
 
print(first)# i am second
print(second) # i am first

But there are interesting ways to do it in Python and JavaScript.

Python (using simultaneous assignments):

first = "i am first";
second = "i am second";
 
# swapping the variables
first, second = second, first
 
print(first) # i am second
print(second) # i am first

Javascript (using destructuring):

let first = "i am first";
let second = "i am second";
 
 // swapping the variables
let [second, first] = [first, second]
 
console.log(first)  // i am second
console.log(second) // i am first

5. Ternary

The ternary conditional operator is not available in Python, however, there is a way to mimic its behavior. Let’s look at an example.

Javascript (with ternary):

const age = 21
 
const status = age > 18 ? "you are qualified" : "you are not qualified"
 
console.log(status) // you are qualified

In Python, we would use if-else

age = 21
 
status = "you are qualified" if age > 18 else "you are not qualified"
 
print(status) # you are qualified

6. Using Higher-Order Functions (Map, Reduce, Filter)

Python makes higher-order functions available globally and can be called like any other function. In JavaScript, higher-order functions are called as methods on the specific array we want to perform the action on.

In short:

  • Python: higherOrder(callback,list) : map(square,nums)
  • Javascript: array.higherOrder(callback) :  nums.map(square)

The above distinction is demonstrated below.

Map

In this example, we square every number in the nums.

def square(n):
    return n*n

nums = [1, 2, 3, 4, 5]
result = map(square,nums)
 
print(list(result)) #[1,4,9,16,25]
function square(n) {
    return n * n
}
 
let nums = [1,2,3,4,5]
let result = nums.map(square)
 
print(result) // [1,4,9,16,25]
Filter

In this example, we filter and return only the numbers in nums that are greater than 2.

def isGreaterThan2(num):
    return num > 2

nums = [1,2,3,4,5]
result = filter(isGreaterThan2,nums)
 
print(list(result)) # [3,4,5]
const nums = [1, 2, 3, 4, 5]
 
function isGreaterThan2(num){
  return num > 2
}
 
let result = nums.filter(isGreaterThan2);
 
console.log(result) // [3, 4, 5]
Reduce

This example sums up and returns the numbers in nums. Moreover, in Python, reduce must be imported from functools.

Python:

from functools import reduce
 
nums = [1, 2, 3, 4, 5]
 
def sum_(total, num):
    return total + num

result = reduce(sum_,nums)
 
print(result) # 15

Javascript:

const nums = [1, 2, 3, 4, 5];
 
function sum(total, num) {
  return total + num;
}
 
let result = nums.reduce(sum, 0);
 
console.log(result); // 15

To learn more about higher-order functions, check out this article.

7. Module Imports

Modules allow us to break down large projects into manageable chunks and organized files. The dominant keywords used with module imports are import and from. There is a slight dichotomy in how they are used in Python and JavaScript. Check them out below.

Namespace Imports

With namespace imports, all the variables and functions of the imported module are accessed via the dot operator on the namespace. In the example below, greetings is the namespace that contains all the variables and functions of the greetings module, and hello is a variable within that module.

Python:

import greetings
 
print(greetings.hello)

Javascript:

import * as greetings from "./greetings.js"
 
console.log(greetings.hello)
Importing One Item

Instead of accessing the variables and functions in a module via the dot operator on the namespace, they can be extracted directly at the time of import and made available globally in the current code.

Python:

from greetings import hello
 
print(hello)

Javascript:

import hello from "./greetings.js" // for default exports
import { hello } from "./greetings.js"  // for named exports
Importing Multiple Items

Python:

from greetings import hello, hi

Javascript:

import { hello, hi } from "./greetings.js"
Importing with Aliases

Sometimes, we might want to use the variables and functions from a module under a different name. We can do so with the as keyword.

Python:

from greetings import hello as hell, hi as hy

Javascript:

import { hello as hell, hi as hy } from "./greetings.js"

There is a lot more to import in Python and JavaScript. The following links provide exhaustive use cases: Python imports and JavaScript imports.

Conclusion

Python and Javascript are amazing programming languages that present a lot of versatility, allowing us to explore different solutions to code problems. Although different in syntax, there are parallels between Python and JavaScript that can help you learn both languages. Keep exploring.


Faddal Ibrahim is a Computer Science major at Ashesi University with 4 years of coding experience. His forte lies in web technologies and is currently exploring DevOps engineering and cybersecurity. When he isn’t immersed in building projects, he spends his time watching Anime.


Discussion

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar