Embracing Context Switching Part One

Enable dual language proficiency by studying the differences and similarities between two of the hottest languages: Python and JavaScript.

Developing for the web sometimes requires a number of different skills and languages. The two worlds of JavaScript and Python have found a home in web development but they have their own idiosyncrasies.

Here are some of the more useful features and how they are approached with each language.

Logging and Debugging

JavaScriptPython
console.log("hello");
console.info("This is some info");

console.warn("This is a warning");
console.dir(Object); // Show methods
print("This will log to console")
dir(object) // Show Methods

Unit Testing

JavaScriptPython
Mocha
Chai
Many More…
unittest
Pytest

JavaScript doesn’t come with a native way to test code, but there are a plethora of 3rd party libraries to choose from when you want to make certain your code continues to function. Mocha and Jest are some of the most popular to choose from.

The Python Standard Library on the other hand includes a number of development tools including automatic documentation generation and unit testing to help with developing and maintaining your application.

While unittest is included in the Python, there are 3rd party suites and tools that can help provide better performance and error reporting. Tools like pytest and selenium seek to improve on the experience provided by the built-in testing tools.

Data Types

JavaScriptPython
Boolean, Number, String, Null, UndefinedBoolean, Integer, Float, String, Complex

In JavaScript both null and undefined are primitive data types.

Running the following code:

typeof(null);
typeof(undefined);

JavaScript will respond:

"object"
"undefined"

In Python, complex numbers can be represented using their own data type. A complex number (also known as an imaginary number) is a number whose root is -1.

Using complex numbers is pretty straight forward. Python uses j to represent the imaginary part of the complex number.

my_complex_number = 4+3j
print(type(my_complex_number))

You should see the output:

<class 'complex'>

Exception Handling

JavaScriptPython
try…catchtry … except

The syntax between JavaScript and Python is just different enough to be confusing.

JavaScript will pass in an object with several methods. This can help you to debug the error that has occurred.

try {
   // Try some fancy thing here
} catch (error) {
  // This block is run if an error occurs
  console.warn(error.message)
}

Python’s syntax on the other hand:

try:
  # Try some fancy Python code here
except ValueError:
  # This block runs if a specific ValueError has been encountered
except:
  # This block will run if a different error is thrown

Python allows for many more ways to handle errors. For a more in depth look at error handling in Python check out the docs.

Variables

JavaScriptPython
Declared using let, const, or varAssignment Only

Python and JavaScript handle variable assignment in strikingly different ways though it may not be immediately obvious.

Newer versions of JavaScript allow you to be more selective about where your variables are accessible via the let keyword. let confines the scope of your variable assignments to the block in which it is created.

for(let i=0;i<2;i++){
  let myVar = "Block Scope Variable ";
  console.log(myVar+i);
}
console.log(myVar);
Block Scope Variable 0
Block Scope Variable 1
 /home/justin/Projects/testing/jtest.js:5
   console.log(myVar);
               ^
ReferenceError: myVar is not defined

Using let protects the variables myVar and i from being accessed from outside of the block they were declared. Python on the other hand has no such feature. Python will not prevent you from accessing any values if you really have the desire. Because of this, it’s customary to prefix functions, methods, and variables that are meant to be private using an underscore.

There’s another key difference related to JavaScript’s implicit functionality as well.

Hoisting in JavaScript

JavaScript

console.log(myMessage);
var myMessage = "Hello World!";

Due to hoisting, the code above will work fine and outputs undefined to the console. JavaScript will only hoist variable declarations. As you can see, any assignments that happen will occur where you would expect in your code.

Hoisting also only occurs when using the var keyword. Variables declared using let or const are not hoisted at all and will throw an error myVar is not defined instead of just logging undefined to the console.

Spread and Splat

JavaScriptPython
... (spread)* (splat)

JavaScript and Python have similar tools for unpacking lists or iterables into 0 or more values.

JavaScript Example:

let myList = [1,2];

function myFunc(param1, param2){
  console.log(param1 + param2);
}

myFunc(...myList);

Python Example:

paramList = [1,2]
def addTwo(param1, param2):
  print(param1 + param2)

addTwo(*paramList)

Both of these functions will output the value 3.

Loops

JavaScriptPython
for
for/in
for/of 
while
do/while
while/else

for in
using: range(), enum() and an iterator object.
Array.map()
Array.prototype.forEach()
List Comprehensions
Instead of:
mylist = [1,2,3,4,5]
for x in mylist:
print(x)
Use:
[ print(x) for x in mylist]

There are many ways to create loops in both languages. In addition to C style loops, JavaScript adds additional ways to iterate over arrays, maps, and sets with built in methods which use callbacks.

Functions

JavaScriptPython
function keyworddef keyword
(param1, param2) => expression lambda param1, param2 : expression

JavaScript and Python both allow for multiple ways to declare functions.

The typical way in JavaScript:

function foo(bar1, bar1){
  console.log(bar1 + bar2);
}

and Python:

def foo(bar1, bar2):
  print(bar1 + bar2)

Each can be represented using an anonymous function.

JavaScript: (bar1, bar2)=>console.log(bar1 + bar2);

Python: lambda bar1, bar2 : print(bar1, bar2)

Only JavaScript uses hoisting to allow the invoking of functions before they are declared. Python requires functions to be declared before they’re used.

The implicit behavior particular to JavaScript is that it binds this to different things. this could refer to the local execution context, or it could refer to the invoking functions namespace. Check out this great article describing the different ways JavaScript handles binding this for each of the functions you choose.

Generator Functions

Both JavaScript and Python allow the use of generator functions. These save time and memory when working with large amounts of data by allowing the return of a single value at a time instead of storing copies in memory before returning to the invoking function.

The following is an example of how to use generators in both JavaScript and Python.

JavaScript iterators and generators are explained in detail on MDN.

Hackaday has a great article explaining the difference between iterators and generators in Python.

Conclusion

This is far from an exhaustive list of all the features included in Python and JavaScript but it gives a taste of the subtle differences between the languages. Part Two will cover tools to solve common problems using appropriate language features and data structures.

Leave a Reply