Python vs JavaScript: Complete Comparison of Essential Concepts

Python vs JavaScript: Complete Comparison of Essential Concepts

Purpose of This Guide

This guide is for learners who know programming and want a quick comparison of the key syntax and functional differences between Python and JavaScript. It focuses on the main differences to help build a solid foundation for using both languages.

Variables

In both Python and JavaScript, a variable serves as a named storage location in memory, where values—such as numbers, strings, or more complex data structures—are stored. Think of a variable as a container that holds data, which you can then access, manipulate, and use throughout your code.

Variable Declaration and Assignment

Declaring and assigning values to variables is a basic part of coding. Once you assign a value to a variable, you can use or access it throughout your code.

This table shows the different requirements and behaviours between these two languages:

PythonJavaScript
Assignment Operator==
Declaration KeywordNot requiredvar, let, const
ScopeFunction-level, or globalvar (function-scoped), let and const (block-scoped)
HoistingNot supportedSupported for var-declared variables
ReassignmentAllowedAllowed with var and let; const is immutable
TypingDynamicDynamic
RedeclarationNot allowed within the same scopeAllowed with var; disallowed with let and const
MutabilityMutability depends on data type (lists mutable, tuples immutable)Mutable with var and let; immutable with const
Calling VariablesUse variable name directlyUse variable name directly

Variable Naming Conventions

Variable naming conventions improve readability and maintain consistency across projects. Python and JavaScript each have preferred naming styles.

PythonJavaScript
Case SensitivityCase-sensitiveCase-sensitive
Naming Conventionsnake_casecamelCase
Allowed CharactersLetters, digits, underscoresLetters, digits, underscores
Private VariablePrefix with underscore (_)Prefix with underscore (_)
Reserved KeywordsReserved words must be avoided; refer to Python documentationAvoid reserved words; refer to JavaScript documentation

General Rules:

  • Variable names must not begin with a number.

  • They can contain letters, numbers, and underscores but must avoid symbols like @, #, and $, etc.

  • Variable names are case-sensitive—myVariable and myvariable are different.

  • Reserved words or built-in function names should not be used as variable names.

Resources:

Python 3.x Reserved Words

Python 3.x Built-in Functions

JavaScript Reserved Words on MDN

Hoisting

Python does not support hoisting. Variables must be declared before they are used.

print(a)  # NameError: name 'a' is not defined
a = 5

JavaScript has hoisting behaviour for variables declared with var. This means var declarations are moved to the top of their scope before code execution, though their assignments are not hoisted.

console.log(a);  // undefined (because of hoisting)
var a = 5;

console.log(b);  // ReferenceError: Cannot access 'b' before initialization
let b = 10;

Variable Assignment and Object Creation

Variables in Python and JavaScript handle assignments differently at the memory level:

  • JavaScript: Directly stores primitive data types (like numbers or strings) by value.

  • Python: Often creates an object in memory for the value and assigns a reference to that object to the variable.

In JavaScript, primitive types (such as number, string, boolean, null, undefined, and Symbol) are stored by value. When you assign a primitive type to a variable, JavaScript directly stores the value in the memory allocated for that variable. This means that if you assign a primitive variable to another variable, each variable operates independently with its own copy of the value.

let a = 5;
let b = a; // b now has its own copy of the value
a = 10;
console.log(b); // Outputs: 5, because `b` has its own independent copy of 5

For non-primitive types (such as objects and arrays), JavaScript uses reference-based storage. When you assign an object or array to a variable, JavaScript stores only a reference (or “pointer”) to the memory location where the actual data is stored. This means if you assign one object to another, they will both reference the same memory location, and changing one will affect the other.

let obj1 = {name: "Alice"};
let obj2 = obj1; // obj2 references the same object in memory as obj1
obj1.name = "Bob";
console.log(obj2.name); // Outputs: "Bob", because both variables point to the same object

Python manages data using references as well. However, everything in Python is an object, including numbers and other primitive types. When a variable is assigned a value in Python, it doesn’t hold the actual value but rather a reference to an object that contains the value. Python’s handling of assignment for immutable and mutable types differs:

  • Immutable Types (e.g., int, float, str, tuple): When you assign an immutable type to a variable, Python creates a new object in memory if you change the value. Each assignment creates a new reference to an object.
a = 5
b = a  # b now references the same integer object as a
a = 10  # a now references a new integer object with value 10
print(b)  # Outputs: 5, as b still references the original integer 5
  • Mutable Types (e.g., list, dict, set): When you assign a mutable object to another variable, both variables reference the same memory location, so changes to one variable’s data affect the other.
list1 = [1, 2, 3]
list2 = list1  # list2 references the same list object as list1
list1.append(4)
print(list2)  # Outputs: [1, 2, 3, 4], as both variables reference the same list

Data Types

Both languages support several standard data types.

Below is a detailed table of common data types in each language, followed by brief descriptions of each.

Data TypePythonJavaScriptDescription
IntegerintnumberWhole numbers without decimals, e.g., 42, -7, 0. Python distinguishes int as a separate type, while JavaScript combines all numbers.
Floating-pointfloatnumberNumbers with decimal points, e.g., 3.14, -0.001. Represented as float in Python and as number in JavaScript.
StringstrstringSequence of characters, such as "Hello" or '1234'. Both languages support single and double quotes for strings.
BooleanboolbooleanLogical values representing truth: True and False in Python; true and false in JavaScript.
List/ArraylistarrayOrdered collections of elements. Python lists and JavaScript arrays can store different data types in one container.
Dictionary/ObjectdictobjectKey-value pairs; in Python, it's a dict (e.g., {"key": "value"}), and in JavaScript, it's an object (e.g., {key: "value"}).
TupletupleNo direct equivalentImmutable ordered collection in Python, meaning elements cannot be changed once set. No direct equivalent in JavaScript.
SetsetNo direct equivalentUnordered collection of unique elements in Python. JavaScript has no direct equivalent but supports Set objects.
Null/UndefinedNonenull, undefinedRepresents the absence of a value. Python uses None, while JavaScript distinguishes between null (assigned absence) and undefined (uninitialized variable).
SymbolNo direct equivalentSymbol (ES6)Unique and immutable data type introduced in ES6 for property keys in JavaScript objects. No equivalent in Python.

Type Checking

PythonJavaScript
Type Checktype(value)typeof value
Display Outputprint()console.log()

Strings

In programming, a string is a sequence of characters enclosed in either single (' ') or double (" ") quotes. Each language has its own methods for handling immutability, string concatenation, indexing, slicing, and conversions.

Strings are immutable, meaning that once a string is created, its contents cannot be changed. Python will raise an error if you try to modify a string directly, while JavaScript will fail silently.

Examples for Python:

my_string = "Hello"
my_string[0] = "h"  # This will raise a TypeError

Examples for JavaScript:

let myString = "Hello";
myString[0] = "h";  // This will not change the string
console.log(myString);  // Output: "Hello"

String Concatenation

String concatenation combines two or more strings.

Both Python and JavaScript use the + operator to concatenate strings.

# python 
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # Output: "Hello World"

For a cleaner and more readable approach, JavaScript offers template literals (using backticks and ${...} syntax), while Python (Python 3.6+) provides f-strings (using f"" and {...} syntax) to embed variables directly into strings.

# Python
name = "John"

greeting = f"Hello, {name}"  
print(greeting)  # 'Hello, John'
// JavaScript
let str1 = "Hello";
let str2 = "World";

let result = `${str1} ${str2}`;
console.log(result);  // Output: "Hello World"

Python also provides the .format() method for formatting strings.

name = "John"

greeting = "Hello, {}".format(name)
print(greeting)  # 'Hello, John'

String Indexing

Both Python and JavaScript allow you to access individual characters within a string by their index.

Both languages use 0-based indexing. The key difference between the two is that Python supports negative indexing, but JavaScript does not. When accessing out-of-range elements, Python raises an IndexError, while JavaScript returns undefined.

Examples for Python:

my_string = "Hello"
first_char = my_string[0]  # Output: 'H'

# Python supports negative indexing
last_char = my_string[-1]   # Output: 'o'

Examples for JavaScript:

let myString = "Hello";
let first_char = my_string[0];  // Output: 'H'

// JavaScript does not support negative indexing. However, you can use 
// the length property to access the last character in a string 
// by subtracting one from the string’s length. For example:
let lastChar = myString[myString.length - 1];  // Output: 'o'

String Slicing

String slicing extracts a part of a string between two specified indices.

Key Differences:

PythonJavaScript
Basic Syntaxmy_string[start:end:step]myString.slice(start, end) , myString.substring(start, end)
Step ParameterSupportedNot supported

String Slicing in Python

The syntax explanation:

  • start: The starting index (inclusive), defaults to 0.

  • end: The ending index (exclusive), defaults to the length of the string.

  • step: The increment between indices (optional), defaults to 1.

Examples:

my_string = "Hello World"

# Slicing from index 0 to 5 (end is exclusive)
substring = my_string[0:5]  # 'Hello'

# Omitting the start (start from the beginning)
substring = my_string[:5]  # 'Hello'

# Omitting the end (slice till the end)
substring = my_string[6:]  # 'World'

# Negative indexing with slicing
substring = my_string[-5:]  # 'World'

# Using step (start from the beginning, every second character slice till the end)
substring = my_string[::2]  # 'HloWrd'

# Reversing the string with negative step
substring = my_string[::-1]  # 'dlroW olleH'

String Slicing in JavaScript

The syntax explanation:

  • start: The starting index (inclusive).

  • end: The ending index (exclusive), defaults to the length of the string.

  • do not support the step parameter.

Examples using .slice(start, end):

let myString = "Hello World";

// Slicing from index 0 to 5 (end is exclusive)
let substring = myString.slice(0, 5);  // 'Hello'

// Omitting the start (start from the beginning)
substring = myString.slice(0, 5);  // 'Hello'

// Omitting the end (start from index 6, slice till the end)
substring = myString.slice(6);  // 'World'

// Negative indexing with slicing
substring = myString.slice(-5);  // 'World'

Examples using .substring(start, end), note that negative indices are not supported with this method.

let substring = myString.substring(0, 5);  // 'Hello'
substring = myString.substring(6);  // 'World'

Changing Case

Each language provides a set of methods to convert strings to lowercase, uppercase, and other case formats.

PythonJavaScript
Convert to Lowercasemy_string.lower()myString.toLowerCase()
Convert to Uppercasemy_string.upper()myString.toUpperCase()
Capitalize Stringmy_string.capitalize()myString[0].toUpperCase() + myString.slice(1).toLowerCase()
Title Casemy_string.title()No direct method

Examples for Python:

my_string = "hEllo woRld"
print(my_string.upper())  # 'HELLO WORLD'
print(my_string.lower())  # 'hello world'
print(my_string.capitalize())  # 'Hello world'
print(my_string.title())  # 'Hello World'

Examples for JavaScript:

let myString = "hEllo woRld"
console.log(myString.toUpperCase());  // 'HELLO WORLD'
console.log(myString.toLowerCase());  // 'hello world'
console.log(myString[0].toUpperCase() + myString.slice(1).toLowerCase());  
// 'Hello world'

Finding and Checking Substrings

PythonJavaScript
Locate substring indexmy_string.find('sub')myString.indexOf('sub')
Find the Last Occurrencemy_string.rfind('sub')myString.lastIndexOf('sub')
Check if Substring Exists'sub' in my_stringmyString.includes('sub')
Checks for prefixmy_string.startswith('prefix')myString.startsWith('prefix')
Checks for suffixmy_string.endswith('suffix')myString.endsWith('suffix')
Count Occurrences of Substringmy_string.count('sub',start, end)No direct method

Examples for Python:

my_string = "hello world"

# Searches for the substring 'world' in my_string and returns the starting index where it is found. 
#If not found, it would return -1. 
print(my_string.find('world'))  # 6

# Check if the substring 'world' exists and return a boolean
print('world' in my_string)  # True

# çhecks if my_string begins with the substring 'hello'.
print(my_string.startswith('hello'))  # True

# çhecks if my_string ends with the substring 'hello'.
print(my_string.endswith('world'))  # True

# Counts the occurrences of the substring 'o' within my_string
# The start and end parameters are optional.
print(my_string.count('o')) # 2

Examples for JavaScript:

let myString = "hello world";

console.log(myString.indexOf('world'));  // 6
console.log(myString.includes('world'));  // true
console.log(myString.startsWith('hello'));  // true
console.log(myString.endsWith('world'));  // true

Modifying and Replacing Strings

PythonJavaScript
Replace a Substringmy_string.replace('old', 'new')myString.replace('old', 'new')
Remove Whitespacemy_string.strip()myString.trim()
Left Trim (Whitespace)my_string.lstrip()myString.trimStart()
Right Trim (Whitespace)my_string.rstrip()myString.trimEnd()

Examples for Python:

my_string = "  hello world  "

print(my_string.strip())  # 'hello world'
print(my_string.replace('world', 'Python'))  # 'hello Python'

Splitting and Joining Strings

PythonJavaScript
Split a String into a Listmy_string.split('delimiter')myString.split('delimiter')
Join a List of Strings'delimiter'.join(list_of_strings)arrayOfStrings.join('delimiter')

Examples for Python:

my_string = "hello,world"

# Splits the string my_string at each comma , 
# and returns a list of the resulting substrings.
split_list = my_string.split(",") 
print(split_list) # output: ['hello', 'world']

# The join method takes the list split_list and joins its elements 
# into a single string, inserting a space " " between each element. 
joined_string = " ".join(split_list)  
print(joined_string) # output: 'hello world'

Examples for JavaScript:

let myString = "hello,world";

let splitArray = myString.split(",");  // ['hello', 'world']
let joinedString = splitArray.join(" ");  // 'hello world'

Check String Length

The len() function is used to check the length of a string in Python.

my_string = "Hello"

print(len(my_string))  # 5

In JavaScript, you can determine the length of a string using the .length property, not a function like in Python.

let myString = "Hello";

let length = myString.length;
console.log(length) // 5

Checking String Properties

Python has more built-in methods for string manipulation (like isalpha(), isdigit(), capitalize(), etc.)

my_string = "hello123"

# to check if String is Alphabetic
print(my_string.isalpha())  # False (contains digits)

# to check if String is Numeric
print(my_string.isdigit())  # False

# to check if String is Alphanumeric
print(my_string.isalnum())  # True (contains only alphanumeric characters)

# to check if all the alphabetic characters in my_string are lowercase
print(my_string.islower()) # True

# to check if all the alphabetic characters in my_string are uppercase
print(my_string.isupper()) # False

Converting Other Data Types to Strings

Both Python and JavaScript provide ways to convert various data types (numbers, booleans, arrays, objects) into strings.to strings.

In Python, str() converts data types into strings.

# Converting a number to a string
num = 123
str_num = str(num)  # '123'

# Converting a list to a string
my_list = [1, 2, 3]
str_list = str(my_list)  # '[1, 2, 3]'

# Converting a dictionary to a string
my_dict = {"name": "John", "age": 30}
str_dict = str(my_dict)  # "{'name': 'John', 'age': 30}"

In JavaScript, the String() function behaves similarly but returns [object Object] for objects and converts arrays to a comma-separated string.

// Converting a boolean to a string
let boolVal = true;
let strBool = String(boolVal);  // 'true'

// Converting an array to a string
let myArray = [1, 2, 3];
let strArray = String(myArray);  // '1,2,3'

// Converting an object to a string (returns [object Object])
let myObject = {name: "John", age: 30};
let strObject = String(myObject);  // '[object Object]'

Most JavaScript types (numbers, booleans, arrays, etc.) also have a .toString() method that converts them to a string. However, null and undefined do not have this method.

// Boolean to string
let boolVal = true;
let strBool = boolVal.toString();  // 'true'

You can also convert data types to strings by embedding them within template literals (using ${} inside backticks ` ) in JavaScript, and f-strings (using {} inside f"") in Python.

Examples for Python:

num = 123
str_num = f"{num}"  # '123'

Examples for JavaScript:

let num = 123;
str_num = `${num}`  // '123'

Numbers

In Python, the main numeric types are Integer (int), Floating-Point (float), and Complex (complex). JavaScript, by contrast, has the Number type for most numerical values, which covers both integers and floating-point numbers. For handling integers outside JavaScript's standard Number range (safe up to 253−12^{53} - 1253−1), JavaScript provides the BigInt type.

Here’s a comparison of the primary numeric types in Python and JavaScript, along with examples.

Numeric TypePythonJavaScript
Integerint (arbitrary precision)Number (up to 253−12^{53} - 1253−1), BigInt for larger
Floating-PointfloatNumber
Complex NumberscomplexNot supported
NaN & Infinityfloat('nan'), float('inf')NaN, Infinity

Basic Arithmetic Operations

Python and JavaScript both support core arithmetic operations, including addition(+), subtraction(-), multiplication(*), division(/), modulus(%), exponentiation(**), and integer division(// or Math.floor(x / y) for JS). Here’s how these operations work in each language:

OperationPython SyntaxJavaScript SyntaxExample Result
Additionx + yx + y5 + 3 → 8
Subtractionx - yx - y5 - 3 → 2
Multiplicationx * yx * y5 * 3 → 15
Division (Float)x / yx / y5 / 2 → 2.5
Integer Divisionx // yMath.floor(x / y)5 // 2 → 2 , Math.floor(5 / 2) → 2
Modulusx % yx % y5 % 2 → 1
Exponentiationx ** yx ** y5 ** 2 → 25

Essential Number Methods and Functions

Both Python and JavaScript provide a variety of built-in methods and functions for efficient number handling, from rounding and truncation to random number generation and type conversion. Here are some of the most commonly used methods in each language, with examples to illustrate their usage.

Rounding Functions

PythonJavaScript
Rounds x to n decimal places(Python), Rounds x to the nearest integer (JavaScript)round(x, n)Math.round(x)
Rounds x down to the nearest integermath.floor(x)Math.floor(x)
Rounds x up to the nearest integermath.ceil(x)Math.ceil(x)
Removes the decimal part of xmath.trunc(x)Math.trunc(x)

Examples for Python:

import math

x = 5.678
print(round(x, 2))   # Rounds to 2 decimal places: 5.68
print(math.floor(x)) # Rounds down: 5
print(math.ceil(x))  # Rounds up: 6
print(math.trunc(x)) # Removes decimal part: 5

Examples for JavaScript:

let x = 5.678;
console.log(Math.round(x));    // Nearest integer: 6

Random Number Generation

Python (using the random module):

  • random.random(): Returns a random float between 0.0 and 1.0.

  • random.randint(a, b): Returns a random integer between a and b (inclusive).

import random
print(random.random())          # Random float: 0.0 to 1.0
print(random.randint(1, 10))    # Random integer between 1 and 10

JavaScript:

  • Math.random(): Returns a random float between 0 (inclusive) and 1 (exclusive).

  • To generate integers within a range, use Math.floor(Math.random() * (max - min + 1)) + min.

console.log(Math.random());  // Random float: 0 to 1
console.log(Math.floor(Math.random() * (10 - 1 + 1)) + 1); // Random integer 1 to 10

Parsing and Converting Numbers

Python:

  • int(x): Converts x to an integer.

  • float(x): Converts x to a floating-point number.

num_str = "42.7"
print(int(float(num_str)))    # Converts to integer: 42
print(float(num_str))         # Converts to float: 42.7

JavaScript:

  • parseInt(string): Parses a string and returns an integer.

  • parseFloat(string): Parses a string and returns a floating-point number.

  • Number(x): Converts x to a number.

let numStr = "42.7";
console.log(parseInt(numStr));   // Converts to integer: 42
console.log(parseFloat(numStr)); // Converts to float: 42.7
console.log(Number(numStr));     // Converts to number: 42.7

Booleans

Booleans represent truth values in programming and are essential for control flow, comparisons, and logical operations. In both Python and JavaScript, the Boolean type has only two possible values: True and False in Python, and true and false in JavaScript.

Boolean Operations

Boolean operations in both languages follow basic logical principles, involving operators like and, or, and not in Python, or their JavaScript equivalents, &&, ||, and !.

Examples for Python:

a = True
b = False
print(a and b)  # Output: False
print(a or b)   # Output: True
print(not a)    # Output: False

Examples for JavaScript:

let a = true;
let b = false;
console.log(a && b);  // Output: false
console.log(a || b);  // Output: true
console.log(!b);      // Output: true//

Comparison Operators

Comparison operators return Boolean values and are used to compare variables and values in both Python and JavaScript. Common operators include equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Additionally, strict equality (===) and strict inequality (!==) exist in JavaScript, which compares both value and type.

OperatorPython SyntaxJavaScript Syntax
Equal====
Not Equal!=!=
Strict EqualN/A===
Strict Not EqualN/A!==
Greater Than>>
Less Than<<
Greater or Equal>=>=
Less or Equal<=<=

Strict Equality in JavaScript: === checks both value and type, while == only compares values, performing type coercion.

// JavaScript comparison operations
let x = 5;
let y = "5";
console.log(x == y);     // Output: true (non-strict equality)
console.log(x === y);    // Output: false (strict equality)

Lists/Arrays

Lists in Python and arrays in JavaScript serve as flexible, ordered collections of elements that can hold data of any type, such as numbers, strings, or other objects.

List/Array Creation

Python lists and JavaScript arrays are both defined with square brackets ([])

Examples for Python:

fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]

# mixed data types list
mixed = ["text", 3.14, True]

Examples for JavaScript:

// empty array
const empty = [];

Accessing Lists/Arrays

Both Python lists and JavaScript arrays let you access specific elements using indexing. They are zero-indexed, which means the first element is accessed with index 0.

In Python, use square brackets [] with the index of the element. It also supports negative indexing.

# Python Indexing
fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # Output: apple

# access the last elememt
print(fruits[-1])  # Output: cherry

JavaScript also uses square brackets [] to access array elements. However, for negative indexing, you need to use the .at() method or calculate the position using the length property.

// JavaScript Indexing
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);   // Output: apple

// access the last elememt
console.log(fruits[fruits.length - 1]);  // Output: cherry
console.log(fruits.at(-1));  // Output: cherry

Modifying Elements

You can change the value of a specific element by accessing it with its index and assigning a new value.

let myArray = [10, 20, 30, 40];
myArray[1] = 25;  // Change the second element
console.log(myArray);  // Output: [10, 25, 30, 40]

Slicing

In Python, you can slice a list using list[start:end:step]. The start parameter defaults to 0, the end parameter defaults to the last index of the list and is exclusive, and the step is optional.

# Python Slicing
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])   # Output: [2, 3, 4]
print(numbers[::2])   # Output: [1, 3, 5]

JavaScript provides the .slice(start, end, step) method to slice an array.

// JavaScript Slicing
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.slice(1, 4));  // Output: [2, 3, 4]
console.log(numbers.slice(0, 5, 2)); // Output: [1, 3, 5]

Nested Lists/Arrays

Accessing and modifying elements in nested lists (Python) and nested arrays (JavaScript) follows similar principles as working with single-level lists/arrays. However, you need to access each level individually using multiple indices.

Examples for Python:

nested_list = [
    [1, 2, 3],  # First inner list
    [4, 5, 6],  # Second inner list
    [7, 8, 9]   # Third inner list
]

# Accessing an element
print(nested_list[0][1])  # Output: 2 (from the first inner list)
print(nested_list[2][2])  # Output: 9 (from the third inner list)

# Modifying an element
nested_list[1][1] = 50  # Change the second element of the second inner list
print(nested_list)  # Output: [[1, 2, 3], [4, 50, 6], [7, 8, 9]]

# Modify the entire second sublist
nested_list[1] = [40, 50, 60]
print(nested_list)  # Output: [[1, 2, 3], [40, 50, 60], [7, 8, 9]]

Examples for JavaScript:

let nestedArray = [
    [1, 2, 3],  // First inner array
    [4, 5, 6],  // Second inner array
    [7, 8, 9]   // Third inner array
];

// Accessing an element
console.log(nestedArray[0][1]);  // Output: 2 (from the first inner array)
console.log(nestedArray[2][2]);  // Output: 9 (from the third inner array)

List/Array Manipulations and Methods

Adding Elements

PythonJavaScript
Add an element to the end of the list/array.append().push()
Add an element to the beginning of the array.insert(0, element).unshift()
Add an element at a specific position.insert().splice()
Combine two lists/arrays or add multiple elements.extend().concat()

Examples for Python:

my_list = [1, 2, 3]

# Insert element to the beginning
my_list.insert(0, 1)
print(my_list)  # Output: [1, 1, 2, 3]

# Insert element at index 1
my_list.insert(1, 10)
print(my_list)  # Output: [1, 10, 1, 2, 3]

# Extend the list with another list
my_list.extend([5, 6, 7])
print(my_list)  # Output: [1, 10, 1, 2, 3, 5, 6, 7]

Examples for JavaScript:

let myArray = [1, 2, 3];

// At position 1, delete 0 element, add 10 and 11
myArray.splice(1, 0, 10, 11);
console.log(myArray); // Output:

// Concatenate arrays
myArray = myArray.concat([5, 6, 7]);
console.log(myArray);  // Output: [1, 10, 11, 2, 3, 5, 6, 7]

Removing Elements

PythonJavaScript
Remove and return the last element.pop().pop()
Remove the first elementN/A.shift()
Remove the first occurrence of a specific value.remove()N/A
Remove elements from a specific indexdel.splice()
Remove all elements.clear()N/A

Examples for Python:

my_list = [1, 2, 3, 4, 2]

# Remove the first occurrence of the value 2
my_list.remove(2)
print(my_list)  # Output: [1, 3, 4, 2]

# Delete element by index
del my_list[0]
print(my_list)  # Output: [3, 4, 2]

# Clear the entire list
my_list.clear()
print(my_list)  # Output: []

Examples for JavaScript:

let myArray = [1, 2, 3, 4];

// Splice elements from a specific index
myArray.splice(1, 1);  // Removes 1 element starting from index 1
console.log(myArray);  // Output: [1, 3, 4]

Finding Elements

PythonJavaScript
Return the index of the first occurrence of an element.index().indexOf()
Check if an element is presentin.includes()

Examples for Python:

my_list = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

# Find index
print(my_list.index("Lemon"))  # Output: 2

# Check for existence
print("Orange" in my_list)  # Output: True

Examples for JavaScript:

let myArray = ["Banana", "Orange", "Lemon", "Apple", "Mango"];

// Check for existence
console.log(myArray.includes("Orange"));  // Output: true

Dictionaries/Objects

In Python, a dictionary and an object in JavaScript have similar purposes: they both store data as key-value pairs.

Creation

In Python, dictionaries are created using curly braces {}, with each key-value pair separated by a comma. Keys are unique and can be of any immutable data type (such as strings, numbers, or tuples), while values can be of any data type.

# Python Dictionary
student = {
    "name": "Alice",
    "age": 20,
    "grades": [88, 92, 79]
}

In JavaScript, objects are created similarly using curly braces {}, but keys are often strings (or symbols), and values can be any data type.

// JavaScript Object
const student = {
    name: "Alice",
    age: 20,
    grades: [88, 92, 79]
};

JavaScript objects also support shorthand notation for creating properties if the key and variable name are the same, making the code cleaner and more readable.

// With Shorthand Notation
const name = "Alice";
const age = 20;

const student = {
    name,  // shorthand for name: name
    age    // shorthand for age: age
};

console.log(student);  // Output: { name: 'Alice', age: 20 }

Accessing Values

Values in both dictionaries and objects can be accessed by referencing their keys.

In Python, you can use square brackets [] or the get() method.

const student = {
    name: "Alice",
    age: 20,
    grades: [88, 92, 79]
};

# Python Accessing Values using square brackets
print(student["name"])   # Output: Alice

# Python Accessing Values using the get() method
print(student.get("age"))  # Output: 20

In JavaScript, you use dot notation . or square brackets [].

const student = {
    name: "Alice",
    age: 20,
    grades: [88, 92, 79]
};

// JavaScript Accessing Values using dot notation
console.log(student.name);    // Output: Alice

// JavaScript Accessing Values using square brackets
console.log(student["age"]);  // Output: 20

Adding and Updating Key-Value Pairs

In both Python and JavaScript, adding or updating a key-value pair is straightforward. If the key already exists, it is updated; if it doesn’t exist, it’s added.

Python:

  • Use the assignment syntax: dict[key] = value

  • Use the update() method to add multiple key-value pairs at once.

student = {"name": "Alice", "age": 20}

# Update existing key
student["age"] = 21
print(student) # {'name': 'Alice', 'age': 21}

# Add new key            
student["grade"] = "A"
print(student) # {'name': 'Alice', 'age': 21, 'grade': 'A'}

# Add multiple pairs        
student.update({"city": "New York", "course": "Math"})
print(student)  # {'name': 'Alice', 'age': 21, 'grade': 'A', 'city': 'New York', 'course': 'Math'}

JavaScript:

  • Use dot notation (obj.key = value) or square bracket notation (obj["key"] = value).

  • Use Object.assign() to add or update multiple properties at once.

const student = { name: "Alice", age: 20 };

// Update existing property
student.age = 21;
console.log(student); // {'name': 'Alice', 'age': 21}

// Add new property
student.grade = "A";  
console.log(student); // {'name': 'Alice', 'age': 21, 'grade': 'A'}

// Add multiple properties         
Object.assign(student, { city: "New York", course: "Math" }); 
console.log(student);  // {name: 'Alice', age: 21, grade: 'A', city: 'New York', course: 'Math'}

Removing Key-Value Pairs

PythonJavaScript
Delete a specific keydel operatordelete operator
Remove the specified key and returns its value.pop(key)N/A
Remove and return the last inserted key-value pair.popitem()N/A
Empty the entire dictionary.clear()N/A

Examples for Python:

student = {"name": "Alice", "age": 21, "grade": "A", "city": "New York"}

# Removes 'age' key and returns its value
age = student.pop("age")           
print(age)  # 21
print(student) # {'name': 'Alice', 'grade': 'A', 'city': 'New York'}

# Removes last inserted pair
print(student.popitem()) # ('city', 'New York')     
print(student) # {'name': 'Alice', 'grade': 'A'}

# Deletes 'grade' key
del student["grade"] 
print(student) # {'name': 'Alice'} 

# Clears all entries      
student.clear()                    
print(student)  # {}

Control Flow

Control flow in both Python and JavaScript refers to the order in which statements, instructions, or function calls are executed in a program. By default, code in both languages runs line by line, following the order it appears. Control flow allows programs to make decisions, repeat actions, and manage execution based on specific conditions.

Common Control Flow Structures:

PythonJavaScript
Conditionalif, elif, elseif, else if, else or switch statement
Ternary Operatorvalue_if_true if condition else value_if_falsecondition ? value_if_true : value_if_false
for Loopsfor…infor, for...of, for...in
while Loopswhile, while..elsewhile, do..while
Error Handlingtry, excepttry, catch

Logical Operators:

PythonJavaScript
True if both conditions are trueand&&
True if either one condition is trueor`
Reverses the conditionnot!

Truthy and Falsy Values

Python:

  • falsy: False, None, 0, 0.0, '' (empty strings), [] (empty lists), () (empty tuples), {} (empty dictionaries).

  • Everything else is truthy.

JavaScript:

  • falsy: false, 0, "" (empty string), null, undefined, NaN.

  • Everything else is truthy.

Conditional statements

Conditional statements allow the program to execute specific blocks of code based on certain condition.

The if statement checks whether a condition is true or false. If it is true, the code block runs. If it is not true, the code block is skipped. If the previous conditions are not true, the program checks the elif statement condition. The else statement handles anything not caught by the earlier conditions.

age = 20

if age < 18:
    print("Minor")
elif age >= 18 and age < 65:
    print("Adult")
else:
    print("Senior")

# In this example, the console output is "Adult".

JavaScript offers the switch statement, which simplifies multiple conditional checks, especially when comparing the same variable or expression against different values. It is a more readable alternative to chaining several if...else if statements.

  • The switch statement evaluates an expression and then matches it against case values.

  • Each case block represents a specific value to check. If a match is found, the corresponding code runs.

  • The break statement stops further checks, ensuring only the matched case runs.

  • The default case executes if no other case matches, acting as a fallback.

let day = 3;
let dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    case 4:
        dayName = "Thursday";
        break;
    case 5:
        dayName = "Friday";
        break;
    default:
        dayName = "Weekend";
        break;
}
// In this example, day is checked against each case. 
// When it matches 3, it assigns "Wednesday" to dayName and exits the switch.
console.log(dayName);  // Output: "Wednesday"

Ternary Operator

The ternary operator is a shorthand way to write simple if-else statements in one line. It evaluates a condition and returns one of two values, depending on whether the condition is true or false.

Example for Python:

age = 18
# prints "Adult" if the condition age >= 18 is true; 
# otherwise, it prints "Minor".
print("Adult") if age >= 18 else print("Minor") # Output: "Adult"

Example for JavaScript:

let age = 18;

// Store the value "Adult" in the variable status if the condition age >= 18 is true; 
// otherwise, store the value "Minor" in it.
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);  // Output: "Adult"

For Loop

For loops in both Python and JavaScript allow iteration over sequences, such as lists or arrays.

Python's for loop iterates directly over the elements of a sequence (like a list, tuple, or string) or ranges, without needing a counter variable.

# The for loop iterates over a sequence of numbers generated by the range(5) function. 
# The range(5) produces a sequence of integers from 0 to 4 (excluding 5), 
# and the loop executes once for each number in that range. 
for i in range(5): 
    print(i)

# output: 
# 0
# 1
# 2
# 3
# 4

To iterate over a dictionary in Python, you can use the .items(), .keys(), or .values() methods to get the keys and values.

person = {"name": "John", "age": 30, "city": "New York"}

# The .items() method returns each key and value pair from the dictionary as a tuple, 
# allowing you to unpack them directly into key and value variables within the loop
for key, value in person.items():
    print(f"{key}: {value}")

# output:
# name: John
# age: 30
# city: New York

JavaScript has traditional for loops, for...of for iterating over iterable objects (like arrays), and for...in for object properties.

// Traditional for loop uses an index i to iterate over the numbers array, 
// incrementing i after each iteration.
let numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

// output: 
// 1
// 2
// 3
// 4
// 5

The for-in loop in JavaScript is used to iterate over the keys of an object or each index of an array (although for...of is generally preferred for arrays).

let person = { name: "Alice", age: 25, city: "New York" };

// for...in accesses each property name in the person object 
// and retrieves its corresponding value.
for (let key in person) {
    console.log(key);
}

// Output:
// name
// age
// city

JavaScript introduced the for-of loop in ES6 to directly iterate over the values of iterable objects (arrays, strings, etc.).

let numbers = [1, 2, 3, 4];
for (let num of numbers) {
    console.log(num);
}
// Output: 1, 2, 3, 4

While Loop

In both languages, the loop will keep running as long as the condition evaluates to True (in Python) or true (in JavaScript). Once the condition becomes False or false, the loop exits.

Use a while loop when you don’t know in advance how many iterations are needed, but you have a condition that will be checked before each iteration.

Basic Syntax of a While Loop

Example for Python:

x = 0
while x < 3:
    print(x)
    x += 1

# output:
# 0
# 1
# 2

Example for JavaScript:

let x = 0;
while (x < 3) {
    console.log(x);
    x++;
}

// output:
// 0
// 1
// 2

while...else Loop (Python Only)

Python has an optional else clause that can be used with while loops. The else block will execute if the loop completes without encountering a break statement.

x = 0
while x < 3:
    print(x)
    x += 1
else:
    print("Loop ended normally")

# output:
# 0
# 1
# 2
# Loop ended normally

do...while Loop (JavaScript Only)

The condition in a do-while loop is evaluated after the code block executes, ensuring that the code runs at least once regardless of whether the condition is initially true.

let count = 1;
do {
    console.log(count);
    count++;
} while (count <= 5);
// Output: 1, 2, 3, 4, 5

break and continue in Loops

Both Python and JavaScript support the use of break and continue statements in loops.

  • break: Terminates the loop immediately.

  • continue: Skips the current iteration and moves to the next one.

Conclusion

Understanding the differences and similarities between Python and JavaScript is crucial for developers working with these versatile languages. This article explored key concepts such as data types, control flow, loops, string manipulation, lists/arrays, dictionaries/objects, and more. Each section highlighted the distinct features of Python and JavaScript while showcasing their shared functionalities and unique quirks.