Python and JavaScript are both extremely popular programming languages used in a wide variety of applications. In this guide, we will compare both of them to help intermediate and experienced JavaScript developers quickly get up and running with Python.
Variables
In Javascript, we define variables using the var
, let
and const
keywords followed by the variable name.
var customerName = "Harry";
let item = "pizza";
const price = 20;
console.log(`${customerName} bought a ${item} for $${price}.`); // Output: Harry bought a pizza for $20.
Whereas in Python we just use the variable name to assign the value.
customerName = "Harry"
item = "pizza"
price = 20
print(f"{customerName} bought a {item} for ${price}.") # Output: Harry bought a pizza for $20.
Camel case is the recommended variable naming convention in Javascript.
let numberOfPizzas = 2;
While Python recommends the snake case.
number_of_pizzas = 2
We can define global variables in JavaScript and Python by declaring variables outside any function or block.
JavaScript:
// Declare a global variable
let globalVar = "I'm a global variable";
function exampleFunction() {
// Access the global variable inside a function
console.log(globalVar);
}
exampleFunction(); // Output: I'm a global variable
console.log(globalVar); // Output: I'm a global variable
Python:
# Declare a global variable
global_var = "I'm a global variable"
def example_function():
# Access the global variable inside a function
print(global_var)
example_function() # Output: I'm a global variable
print(global_var) # Output: I'm a global variable
For variables defined inside a function or a block :
In Javascript, var
is function scoped whereas let
and const
are block level scoped:
function example() {
var x = 1;
let y = 2;
if (true) {
var x = 3; // This reassigns the outer 'x'.
let y = 4; // This creates a new 'y' within the block scope.
}
console.log(x); // Outputs 3 because 'var' is function-scoped.
console.log(y); // Outputs 2 because 'let' is block-scoped.
}
example();
Similarly var
and let
allows variables to reassign another value where const
creates constant variables, variables whose value cannot change.
const postalCode = 33304;
postalCode = 2;// Uncaught TypeError: Assignment to constant variable
In Python, all the variables are block-level scoped and we do not have the concept of constant. We usually use upper case to indicate to other programmers that the variable is constant
POSTAL_CODE = 33304
Data Types
In Javascript, we have seven primitive data types:
number
bigint
string
boolean
null
undefined
symbol
Other non-primitive data types include:
object
for more complex data structures likeArray
andSet
In Python, we have four primitive data types:
float
int
string
boolean
Other non-primitive data types include:
list
dictionary
set
tuple
For defining an empty value we use None
in Python. There is no undefined
type as seen in Javascript.
Python data types: list and tuples
In Python, we use tuples
and lists
for storing the collection of data.
They both allow the storage of any kind of data type, the main difference between them being Mutability. Lists are mutable, you may alter their elements or size after creation. Tuples, on the other hand, are immutable, once a tuple has been defined, its components or size cannot be changed.
# Example of a Python list:
fruits_list = ["apple", "banana", "cherry"]
# Example of a Python tuple:
fruits_tuple = ("apple", "banana", "cherry")
# Modifying a List (Mutable):
fruits_list.append("date")
fruits_list[0] = "orange"
# Attempting to modify a Tuple (Immutable) will raise an error:
# fruits_tuple.append("date") # This line will raise an AttributeError
# fruits_tuple[0] = "orange" # This line will raise a TypeError
# Accessing elements in both List and Tuple:
first_fruit_list = fruits_list[0] # Access the first item in the list
first_fruit_tuple = fruits_tuple[0] # Access the first item in the tuple
Similarly for storing a list of unique values in both JavaScript and Python, we can use sets
.
Javascript:
// Creating a set using curly braces
const studentIds = new Set([1, 2, 3, 4, 4]);
// Displaying the sets
console.log(mySet); // Output: Set { 1, 2, 3, 4 } (Duplicates are removed)
Python:
# Creating a set using curly braces
student_ids = {1, 2, 3, 4, 4}
# Displaying the sets
print(student_ids) # Output: {1, 2, 3, 4} (Note that duplicates are removed)
Objects
In JavaScript object is a collection of properties also known as key-value pairs.
var dog = {
name: "Fido",
breed: "Golden Retriever",
age: 3,
color: "Golden",
isFriendly: true
};
Objects serve as one of the key pillars in JavaScript with non-primitive data types like arrays
, functions
and sets
being all objects.
Python provides us with something similar called a dictionary
for holding key-value pairs. However, it is just another data type and not a foundational building block-like object.
dog = {
"name": "Fido",
"breed": "Golden Retriever",
"age": 3,
"color": "Golden",
"isFriendly": True
}
Python is a class-based object-oriented language. In Python, to create an object we first define a class and create objects(instances) from that class.
# Define a class named "Car"
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start_engine(self):
print(f"{self.make} {self.model}'s engine is started.")
# Create objects from the Car class
toyota = Car("Toyota", "Camry", 2022)
Here the object toyota
is the instance of a Car:
>>> isinstance(tom, Person)
# Output: True
Javascript is a Prototype-based language, prototypes are a mechanism by which Objects can inherit features from one another, remember in JavaScript everything apart from primitive data type is an object even functions.
We can create objects by:
// Define a class named "Car"
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
startEngine() {
console.log(`${this.make} ${this.model}'s engine is started.`);
}
}
// Create objects from the Car class
let toyota = new Car("Toyota", "Camry", 2022);
let audi = new Car("Audi","",2021);
However, it is just an ES6 synthetic sugar and The actual implementation under the hood is:
// Define a constructor function named "Car"
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// Add a method to the Car prototype
Car.prototype.startEngine = function() {
console.log(this.make + ' ' + this.model + "'s engine is started.");
};
// Create objects from the Car constructor function
let toyota = new Car("Toyota", "Camry", 2022);
In this context, the new keyword creates a blank JavaScript Object sets the prototype of the object to the Car functions prototype property and points the newly created object to this context of the function.
So we can say that instead of being an instance of a Car, toyota
is connected to Car.prototype
via the prototype chain. We can verify this by:
console.log(Object.getPrototypeOf(toyota) === Car.prototype) // true
Conditional Statements
Conditional statements in Python and JavaScript, including the if-else
construct, serves similar purposes, but there are some differences in syntax between the two languages.
JavaScript:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if neither condition1 nor condition2 is true
}
Python:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if neither condition1 nor condition2 is True
Comparison Operators
Javascript uses ===
for strict comparison (both value and data type should be equal) whereas in Python the default ==
compares value strictly out of the box.
Other comparison operators in Python include:
Greater than
>
Less than
<
Greater than or equal to
>=
Less than or equal to
<=
Logical Operators
In Javascript, we use &&
, ||
,!
for AND, OR and NOT logical operations.
let temperature = 28;
let isSummer = true;
let isSunny = false;
// Logical AND Operator
if (temperature > 25 && isSummer) {
console.log("It's a hot summer day!");
}
// Logical OR Operator
if (temperature > 30 || isSummer) {
console.log("It's either very hot or it's summer.");
}
// Logical NOT Operator
if (!isSunny) {
console.log("It's not a sunny day.");
}
In Python, we use and
, or
, not
as logical operators.
temperature = 28
is_summer = True
is_sunny = False
# Logical AND Operator
if temperature > 25 and is_summer:
print("It's a hot summer day!")
# Logical OR Operator
if temperature > 30 or is_summer:
print("It's either very hot or it's summer.")
# Logical NOT Operator
if not is_sunny:
print("It's not a sunny day.")
Loops
Loops offer a quick and easy way to do something repeatedly.
In JavaScript, we can use for statement to loop over something.
const pets = ['cat', 'dog', 'fish'];
for (const pet of pets) {
console.log(pet);
}
Its equivalent in Python will be:
pets = ['cat', 'dog', 'fish']
for pet in pets :
print(pet)
Note: There is no for (i=0; i<n; i++)
syntax in Python. Its equivalent is for i in range(n):
Anonymous/Lambda Function :
In Javascript, we have an anonymous function as functions that do not have any name.
const add = function(x, y) {
return x + y;
};
const result = add(5, 3);
In Python, we have the lambda function as an anonymous function
add = lambda x, y: x + y
result = add(5, 3)
print(result) # Output: 8
One great use case for anonymous functions is for map
, filter
and reduce
.
Map
JavaScript:
const celsiusTemperatures = [0, 10, 20, 30, 40];
const fahrenheitTemperatures = celsiusTemperatures.map((celsius) => (celsius * 9/5) + 32);
console.log(fahrenheitTemperatures);
// Output: [32, 50, 68, 86, 104]
Python:
celsius_temperatures = [0, 10, 20, 30, 40]
fahrenheit_temperatures = list(map(lambda celsius: (celsius * 9/5) + 32, celsius_temperatures))
print(fahrenheit_temperatures)
# Output: [32.0, 50.0, 68.0, 86.0, 104.0]
Filter
JavaScript:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
console.log(evenNumbers);
// Output: [2, 4, 6, 8, 10]
Python:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda number: number % 2 == 0, numbers))
print(even_numbers)
# Output: [2, 4, 6, 8, 10]
Reduce
JavaScript:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);
// Output: 15
Python:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers, 0)
print(sum_result)
# Output: 15
Exception Handling
No program is perfect as we always have to account for exceptions. Let's compare exception handling in Python and JavaScript:
In JavaScript, we handle errors with a try-catch
clause.
try {
// Code that may throw an exception
var result = 10 / 0;
} catch (error) {
// Handle the exception
console.error("Error: " + error);
}
In Python, we can catch errors by using try-except
.
try:
print(x)
except:
print("An exception has occurred!")
In JavaScript, we can access the error message through error.message
:
try {
// Code that may throw an exception
var result = 10 / 0;
} catch (error) {
// Handle the exception
console.error("Error: " + error.message);
}
In Python, we use Exceptions as e
for accessing the error message:
try:
print(x)
except Exception as e:
# Handle a more general exception
print(f"Error: {e}")
Python also provides different exception types to catch errors.
try:
# Code that may raise exceptions
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ZeroDivisionError as e:
# Handle division by zero exception
print(f"Error: Division by zero ({e})")
except ValueError as e:
# Handle invalid input (non-integer) exception
print(f"Error: Invalid input ({e})")
except Exception as e:
# Handle other general exceptions
print(f"Error: {e}")
Similar to Javascript we can also use a finally
block to write code that executes regardless of whether an exception occurred or not.
try:
# Code that may raise exceptions
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
except ZeroDivisionError as e:
# Handle division by zero exception
print(f"Error: Division by zero ({e})")
except ValueError as e:
# Handle invalid input (non-integer) exception
print(f"Error: Invalid input ({e})")
except Exception as e:
# Handle other general exceptions
print(f"Error: {e}")
finally:
# This block is always executed, whether an exception occurred or not
print("Cleanup")
Extra stuff
Spread/Merge
As we might know in JavaScript we can spread an object or array through ...
notation.
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
};
const contactInfo = {
email: "john.doe@example.com",
phone: "555-555-5555",
};
// Spread the properties of 'person' and 'contactInfo' into a new object 'combinedInfo'
const combinedInfo = {
...person,
...contactInfo,
};
console.log(combinedInfo);
// Output {
// firstName: "John",
// lastName: "Doe",
// age: 30,
// email: "john.doe@example.com",
// phone: "555-555-5555",
// }
const numbers = [1, 2, 3];
const newNumbers = [0, ...numbers, 4]
console.log(newNumbers);
// Output: [ 0, 1, 2, 3, 4 ]
Similarly, we can unpack the Dictionary and List in Python using **
and *
notations.
person = {
'firstName': 'John',
'lastName': 'Doe',
'age': 30
}
contactInfo = {
'email': 'john.doe@example.com',
'phone': '555-555-5555'
}
# Merge the properties of 'person' and 'contactInfo' into a new dictionary 'combinedInfo'
combinedInfo = {**person, **contactInfo}
print(combinedInfo)
# Output: {
# 'firstName': 'John',
# 'lastName': 'Doe',
# 'age': 30,
# 'email': 'john.doe@example.com',
# 'phone': '555-555-5555'
# }
numbers = [1, 2, 3]
new_numbers = [0, *numbers, 4]
print(new_numbers)
# Output: [0, 1, 2, 3, 4]
Optional Chaining
One popular way to safeguard against non-existing property in JavaScript is through the use of optional chaining. We can use the ?
notation on an object property and use ||
operator to provide a default value.
// Sample object with optional properties
const person = {
name: "John",
city: "Exampleville",
};
// Using optional chaining to access properties with a default value
const postalCode = person?.postalCode || "N/A";
We can achieve the same in Python through the get
attribute.
# Sample dictionary with optional properties
person = {
"name": "John",
"city": "Exampleville",
}
# Using get() to access properties with default values
postal_code = person.get("postalCode", "N/A")
Going Further
We have now gotten a brief overview of the Python programming language for the busy JavaScript developer. You should now be able to start building your projects with it. GoodLuck ;)