Equivalents in Python and JavaScript. Part 1
Tags: basics, cheatsheet, javascript, python
Published: 2018-06-30 04:56:08

---
title: Equivalents in Python and JavaScript. Part 1
published: true
tags: Basics,Cheatsheet,JavaScript,Python
canonical_url: http://djangotricks.blogspot.com/2018/06/equivalents-in-python-and-javascript-part-1.html
series: Equivalents in Python and JavaScript
---

 ![](https://2.bp.blogspot.com/-vPKYTFzcQIE/WzrCDyN3S_I/AAAAAAAAB5k/7bCSikeIKrgP27OEDrcJp4NsjDZnSt2YACLcBGAs/s1600/equivalents-in-python-and-javascript-part-1.png) 

Although __Python__ and __JavaScript__ are quite different languages, there are some analogies which full stack __Python__ developers should know when developing web projects. In this series of 4 parts, I will explore what is similar in each of those languages and what are the common ways to solve common problems. This is not meant to be a reference and I will skip the basics like primitive variable types, conditions, and loops. But I will dig into more complex structures and data operations using both, __Python__ and __JavaScript__. Also, I will try to focus on the practical use cases. This series should be interesting for the developers of Django, Flask, or another __Python__ framework who want to get a grasp of traditional and modern vanilla __JavaScript__. On the other hand, it will be useful for the front-enders who want to better understand how the backend is working and maybe even start their own Django website.

## Parsing integer

We'll begin with integer parsing.

In __Python__ that's straightforward:

```python
number = int(text)
```

But in __JavaScript__ you have to explain what number system you expect: decimal, octal, hexadecimal, or binary:

```javascript
number = parseInt(text, 10);
```

To use the "normal" decimal number system we are passing number 10 as the second parameter of the `parseInt()` function. 8 goes for octal, 16 for hexadecimal, or 2 - for binary. If the __second parameter is missing__, the number in text starts with zero, and you are using a slightly older browser, the number in the text will be interpreted as octal. For example,

```javascript
parseInt('012') == 10  // in some older browsers
parseInt('012', 10) == 12
```

And that can really mess up your calculations.

## Conditional assignment

For conditional assignment, __Python__ and __JavaScript__ have different syntaxes, but conditional assignments are quite popular in both languages. That's popular, because it's just a single statement to have a condition checking, the true-case value, and the false-case value.

Since __Python__ 2.7 you can write conditional assignments like this:

```python
value = 'ADULT' if age >= 18 else 'CHILD'
```

In __JavaScript__ conditional assignments are done using ternary operator `?:`, similar to the ones in C, C++, C#, Java, Ruby, PHP, Perl, Swift, and ActionScript:

```javascript
value = age >= 18? 'ADULT': 'CHILD';
```

## Object attribute value by attribute name

The normal way to access an object's attribute is by the dot notation in both, __Python__ and __JavaScript__:

```python
obj.color = 'YELLOW'
```

But what if you want to refer to an attribute by its name saved as a string? For example, the attribute name could be coming from a list of attributes or the attribute name is combined from two strings like `'title_' + lang_code`.

For that reason, in __Python__, there are functions `getattr()` and `setattr()`. I use them a lot.

```python
attribute = 'color'
value = getattr(obj, attribute, 'GREEN')
setattr(obj, attribute, value)
```

In __JavaScript__ you can treat an object like a dictionary and pass the attribute name in square brackets:

```javascript
attribute = 'color';
value = obj[attribute] || 'GREEN';
obj[attribute] = value;
```

To retrieve a default value when an object has no such attribute, in __Python__, `getattr()` has the third parameter. In __JavaScript__, if `obj` attribute doesn't exist, it will return the `undefined` value. Then it can be OR-ed with the default value that you want to assign. That's a common practice in __JavaScript__ that you can find in many __JavaScript__ libraries and frameworks.

## Dictionary value by key

This is similar to the previous one. The normal way to assign a dictionary's value by key in both languages is using the square brackets:

```python
dictionary = {}
dictionary['color'] = 'YELLOW'
```

To read a value in __Python__ you can use the square-bracket notation, but it will fail on non-existing keys with `KeyError`. The more flexible way is to use the `get()` method which returns `None` for non-existing keys. Also you can pass an optional default value as the second parameter:

```python
key = 'color'
value = dictionary.get(key, 'GREEN')
```

In __JavaScript__ you would use the same trick as with object attributes, because dictionaries and objects are the same there:

```javascript
key = 'color';
value = dictionary[key] || 'GREEN';
```

## Slicing lists and strings

__Python__ has the slice `[:]` operator to get parts of lists, tuples, and similar more complex structures, for example Django QuerySets:

```python
items = [1, 2, 3, 4, 5]
first_two = items[:2]      # [1, 2]
last_two = items[-2:]      # [4, 5]
middle_three = items[1:4]  # [2, 3, 4]
```

In __JavaScript__ arrays have the `slice()` method with the same effect and similar usage:

```javascript
items = [1, 2, 3, 4, 5];
first_two = items.slice(0, 2);     // [1, 2] 
last_two = items.slice(-2);        // [4, 5]
middle_three = items.slice(1, 4);  // [2, 3, 4]
```

But don't mix it up with the `splice()` method which modifies the original array!

---

The `[:]` slice operator in __Python__ also works for strings:

```python
text = 'ABCDE'
first_two = text[:2]      # 'AB'
last_two = text[-2:]      # 'DE'
middle_three = text[1:4]  # 'BCD'
```

In __JavaScript__ strings just like arrays have the `slice()` method:

```javascript
text = 'ABCDE';
first_two = text.slice(0, 2);    // 'AB'
last_two = text.slice(-2);       // 'DE'
middle_three = text.slice(1, 4); // 'BCD'
```

## Operations with list items

In programming it is very common to collect and analyze sequences of elements. In __Python__ that is usually done with lists and in __JavaScript__ with arrays. They have similar syntax and operations, but different method names to add and remove values.
 
This is how to concatenate two lists, add one value to the end, add one value to the beginning, get and remove a value from the beginning, get and remove a value from the end, and delete a certain value by index in __Python__:

```python
items1 = ['A']
items2 = ['B']
items = items1 + items2  # items == ['A', 'B']
items.append('C')        # ['A', 'B', 'C']
items.insert(0, 'D')     # ['D', 'A', 'B', 'C']
first = items.pop(0)     # ['A', 'B', 'C']
last = items.pop()       # ['A', 'B']
items.delete(0)          # ['B']
```

This is how to do exactly the same with arrays in __JavaScript__:

```javascript
items1 = ['A'];
items2 = ['B'];
items = items1.concat(items2);  // items === ['A', 'B']
items.push('C');                // ['A', 'B', 'C']
items.unshift('D');             // ['D', 'A', 'B', 'C']
first = items.shift();          // ['A', 'B', 'C']
last = items.pop();             // ['A', 'B']
items.splice(0, 1);             // ['B']
```

## Joining lists of strings

It is very common after having a list or array of strings, to combine them into one string by a separator like comma or new line.

In __Python__ that is done by the `join()` method of a string where you pass the list or tuple. Although it might feel unnatural, you start with the separator there. But I can assure that you get used to it after several times of usage.

```python
items = ['A', 'B', 'C']
text = ', '.join(items)  # 'A, B, C'
```

In __JavaScript__ the array has the `join()` method where you pass the separator:

```javascript
items = ['A', 'B', 'C'];
text = items.join(', ');  // 'A, B, C'
```

## The Takeaways

- List and tuples in __Python__ are similar to arrays in __JavaScript__.
- Dictionaries in __Python__ are similar to objects in __JavaScript__.
- Strings in __Python__ are similar to strings in __JavaScript__.
- Numbers in __JavaScript__ should be parsed with care.
- Single-line conditional assignments exist in both languages.
- Joining sequences of strings in __Python__ is confusing, but you can quickly get used to it.

I compiled the whole list of equivalents of __Python__ and __JavaScript__ to a cheat sheet that you can print out and use for good. Side by side it compares traditional __Python__ 2.7 and __JavaScript__ based on ECMAScript 5 standard, as well as newer __Python__ 3.6 and __JavaScript__ based on ECMAScript 6 standard with such goodies as string interpolation, lambdas, generators, classes, etc.

<center><a href="https://www.djangotricks.com/goodies/YbnpiLKBmAZi/" target="_blank">✨✨✨<br />Get the Ultimate Cheat Sheet of <br />Equivalents in Python and JavaScript<br />✨✨✨</a></center>

In [the next part](https://dev.to/djangotricks/equivalents-in-python-and-javascript-part-2-3fej) of the series, we will have a look at JSON creation and parsing, operations with regular expressions, and error handling. Stay tuned! 

* * *

Cover photo by [Benjamin Hung](https://unsplash.com/photos/GAFZcKrWnO8).

 ![](http://feeds.feedburner.com/~r/djangotricks/~4/GeUgbRasTww)