Analogs in Python and JavaScript. Part one

Hi, Habr! I present to your attention the translation of the article "Equivalents in Python and JavaScript. Part 1" .


Although Python and Javascript are quite different, there are many similarities that any full-stack developer should be aware of. In this series of 4 articles, we will see what is common in both languages, and consider a number of known problems as well as ways to solve them.


This is not a reference book, there will not be basic information about the types of variables, if-ahs and cycles.
But we will look at more complex data structures and operations using them using Python and Javascript.


I will also illustrate this with examples from practice.


This series will be interesting for back-end vendors using Django, Flask or any other Python-framework who want to learn more about modern Javascript. On the other hand, these articles will be useful for front-endenders who want to better understand how the backend works, or even write a website on Django.


The remaining articles in this series are:


  1. Part Two : JSON, regulars, errors, exceptions
  2. Part three : modern Python and JS: string patterns (f-strings), list unpacking, lambda functions, list iterations, generators, sets.
  3. The fourth part is the function arguments, creating and working with classes, inheritance, setter getters, and class properties.

Cast to type


Let's start by casting the string to a whole. In Python, everything is simple and straightforward:


number = int(text) 

But in JS you have to explain to which system you are going to convert to - decimal, octal, hexadecimal or binary:


 number = parseInt(text, 10); 

To use the usual decimal system, we pass 10 as the second argument to the parseInt () function. 8 for octal, 16 for hexadecimal, or 2 for binary. If the second parameter is omitted, the number starts from zero and you are using an outdated browser, the string with the text will be interpreted as an octal system:


 parseInt('012') == 10 //     parseInt('012', 10) == 12 

Conditional assignment


Although Python and JS use different syntaxes for this, this operation is popular in both languages. It is popular because in one expression you can assign different values ​​for both the True- and False-cases.
Starting in Python 2.7, conditional assignment looks like this:


 value = 'YES' if positive == True else 'NO' 

In JavaScript, conditional assignment is done using a ternary operator ? , as well as in C, C ++, C #, Java, Ruby, PHP, Perl, Swift, and ActionScript:


 value = positive === true? 'YES': 'NO'; 

Accessing an object property by property name


The usual way to access an object property in both Python and JS is the same:


 obj.color = 'YELLOW' 

And what if the property name is enclosed in a string variable? For example, the property name can be obtained from the property list or the property name is composed of two string variables: "title" + land_code .
In Python, the functions getattr() and setattr() exist for this:


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

In JS, you can treat an object as a dictionary and pass the name of the property in square brackets:


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

To get the default value in case a property with that name does not exist, in Python the getattr() function has a third parameter for this. In JS, if the requested property is missing, the function will return undefined . It can be compared with the OR operator with the default value - this is standard practice in JS - this method can be found in many frameworks and libraries.


Access to the dictionary by key


Similar to the above. The key is standardly indicated in square brackets in both languages:


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

For access by key in Python, standard syntax with square brackets is used; however, if such a key is missing, it will cause an exception with a KeyError error.
More flexible is the get() method which returns None if there is no key. You can also pass the value that will be returned if there is no key:


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

In JS, you can do the same trick as with the object property - OR with a default value:


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

Slices: Lists and Strings


Python has a [:] operator for retrieving parts of a list, tuple, or similar structures. An example with an object of type Django QuerySets :


 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] 

JS has a slice() method with the same effect:


 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 do not confuse with the splice() method which changes the original array!


In Python, the [:] operator also applies to strings:


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

In JS, strings also have a slice() method:


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

List operations


In programming, it is often necessary to collect and analyze a sequence of elements. In Python, lists are usually used for this, and in Javascript, arrays are used. They have similar syntax and operations, but methods for adding and deleting elements are different.


We combine two lists, add one element to the end, add one element to the beginning, obtain and delete an element at the beginning, obtain and delete an element from the end, and delete a specific element by index.
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'] 

Same in 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'] 

Connecting rowsets


Connect a set of string elements into a single line using a space, comma or a newline in the form of a connecting character.


In Python, this is the join() string method that takes a list or a tuple as an argument. For the uninitiated (in Python syntax) it may seem strange to start an expression with a separator, but after regular use you will get used to this form of writing:


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

In JS, arrays have a join() method with a separator as an argument:


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

Summarize



In the next series, we will look at creating and parsing JSON, regular expressions, and working with errors and exceptions!

Source: https://habr.com/ru/post/416617/


All Articles