Python vs. JavaScript: A Guide to Basic Data Types
This guide aims to help developers familiar with JavaScript quickly understand Python's basic data types, and vice versa. Through comparison, we will gain a deeper understanding of the similarities and differences in how the two languages handle core data.
References: Python VS JavaScript – What are the Key Differences
Core Differences at a Glance
Feature | Python | JavaScript |
---|---|---|
Numeric Types | int (integer) and float are separate | Number (handles both integers and floats), BigInt |
Boolean Values | True , False (Capitalized) | true , false (lowercase) |
Nullish Values | None (a single null object) | null (intended absence) and undefined (not defined) |
Variable Declaration | Direct assignment, no keyword needed | Requires let , const , var keywords |
Method/Function Naming | snake_case (underscore naming) | camelCase (camel case naming) |
Type Checking | type() (returns type), isinstance() | typeof (returns string), instanceof |
1. Numeric Types
Python
Python clearly distinguishes between integers and floating-point numbers.
int
: Integers. Python'sint
can handle integers of arbitrary size, with no risk of overflow.float
: Floating-point numbers (i.e., decimals).
Operations & API:
# Creation
integer_val = 100
float_val = 100.5
# Arithmetic
add = integer_val + 5 # 105
sub = float_val - 10.5 # 90.0
# Division
std_division = 10 / 4 # -> 2.5 (result is a float)
floor_division = 10 // 4 # -> 2 (floor division, result is an int)
# Type Conversion
str_num = "123"
num_from_str = int(str_num) # -> 123 (int)
float_from_int = float(num_from_str) # -> 123.0 (float)
# Converting float to int truncates the decimal part
int_from_float = int(2.9) # -> 2
# Other common APIs
print(abs(-99)) # -> 99 (absolute value)
print(round(2.9)) # -> 3 (rounding)
print((10.0).is_integer()) # -> True
print((10.5).is_integer()) # -> False
JavaScript
JavaScript uses a single Number
type to represent all numbers (both integers and floats). For very large integers beyond the safe range of Number
, BigInt
is used.
Operations & API:
// Creation
let numberVal = 100;
let floatVal = 100.5;
// Arithmetic
let add = numberVal + 5; // 105
let sub = floatVal - 10.5; // 90
// Division (only one kind)
let division = 10 / 4; // -> 2.5
// Type Conversion
let strNum = "123";
let numFromStr = parseInt(strNum); // -> 123 (Number)
let floatFromStr = parseFloat("123.45"); // -> 123.45 (Number)
let numFromStr2 = Number(strNum); // -> 123 (Number), stricter conversion
// Creating a BigInt
const bigIntValue = 9007199254740991n;
// Other common APIs
Math.abs(-99); // -> 99 (absolute value)
Math.round(2.9); // -> 3 (rounding)
Math.ceil(2.1); // -> 3 (ceiling)
Math.floor(2.9); // -> 2 (floor)
(123.456).toFixed(2); // -> "123.46" (string, 2 decimal places)
(255).toString(16); // -> "ff" (number to hex string)
Core Comparison
- Separated vs. Unified Types: Python distinguishes between
int
andfloat
, whereas JavaScript's unifiedNumber
type simplifies numeric operations but means developers must be mindful of precision issues with integer and float arithmetic. - Division: Python provides two division operators (
/
and//
) to clearly express intent, while JS has only one. - Large Integers: Python's
int
type natively supports arbitrary-precision integers. JS gained this capability with theBigInt
type in ES2020. - API Design: Python tends to use global functions (like
abs()
,round()
) for common math operations. JavaScript centralizes these in theMath
object and provides number-specific formatting methods (liketoFixed()
) on theNumber
prototype.
2. String / Text Type
Python
Uses the str
type. Single ('
) and double ("
) quotes are equivalent for creation.
Operations & API:
# Creation
single_quote = 'hello'
double_quote = "world"
# f-string (recommended formatting)
name = "Alice"
greeting = f"Hello, {name}!" # -> "Hello, Alice!"
# Operations
concatenation = single_quote + " " + double_quote # -> "hello world"
repetition = "Go! " * 3 # -> "Go! Go! Go! "
# Common APIs (snake_case)
s = " Python Developer "
s.upper() # -> " PYTHON DEVELOPER "
s.lower() # -> " python developer "
s.strip() # -> "Python Developer"
s.startswith('Py')# -> True
s.split(' ') # -> ['', '', 'Python', 'Developer', '', '']
# Slicing
py_part = s.strip()[0:6] # -> "Python"
# More common APIs
s_clean = s.strip()
print(s_clean.find("Dev")) # -> 7 (find substring, -1 if not found)
print(s_clean.replace(" ", "_")) # -> "Python_Developer"
print("a,b,c".split(",")) # -> ['a', 'b', 'c']
print("_".join(['a', 'b', 'c'])) # -> "a_b_c"
print("123".isdigit()) # -> True
print("abc".isalpha()) # -> True
JavaScript
Uses the String
type. Single quotes, double quotes, and backticks (`
) can all be used.
Operations & API:
// Creation
let singleQuote = 'hello';
let doubleQuote = "world";
// Template Literals
let name = "Alice";
let greeting = `Hello, ${name}!`; // -> "Hello, Alice!"
// Operations (concatenation only)
let concatenation = singleQuote + " " + doubleQuote; // -> "hello world"
// Common APIs (camelCase)
let s = " JavaScript Developer ";
s.toUpperCase(); // -> " JAVASCRIPT DEVELOPER "
s.toLowerCase(); // -> " javascript developer "
s.trim(); // -> "JavaScript Developer"
s.startsWith('Java'); // -> true
s.split(' '); // -> ["", "", "JavaScript", "Developer", "", ""]
// Substring extraction
let jsPart = s.trim().substring(0, 10); // -> "JavaScript"
// More common APIs
let sClean = s.trim();
sClean.includes("Dev"); // -> true (ES6, check for inclusion)
sClean.indexOf("Dev"); // -> 11 (find substring, -1 if not found)
sClean.replace(" ", "_"); // -> "JavaScript_Developer"
"a,b,c".split(","); // -> ["a", "b", "c"]
["a", "b", "c"].join("_"); // -> "a_b_c"
"5".padStart(3, "0"); // -> "005"
"5".padEnd(3, "0"); // -> "500"
Core Comparison
- Method Naming: Python string methods follow
snake_case
(e.g.,startswith
), while JS followscamelCase
(e.g.,startsWith
). - String Formatting: Python's f-strings and JS's template literals are functionally similar and are the modern, recommended methods for formatting.
- Unique Operations: Python allows string repetition with
*
, which is not supported in JS. Python's slicing syntax ([start:end:step]
) is also more powerful and flexible than JS'ssubstring
orslice
. - Finding & Joining: Python's
str.join()
has a unique and efficient design, called by the delimiter string on a sequence. In JS,join
is an array method. For searching, JS'sincludes()
method is more explicit in its intent than Python'sin
operator (not shown here).
2.1. String Slicing
String slicing is a common operation for extracting substrings. Python provides a very powerful and concise syntax for this.
References: String Slicing in Python - GeeksforGeeks
Python
Python uses the [start:end:step]
syntax for slicing, which is very flexible.
start
: The starting index (inclusive), defaults to 0 if omitted.end
: The ending index (exclusive), defaults to the end of the string if omitted.step
: The step size, defaults to 1 if omitted.
Operations & API:
s = "Hello, Python!"
# Basic slicing
print(s[0:5]) # -> "Hello"
print(s[7:13]) # -> "Python"
print(s[:5]) # -> "Hello" (from the beginning)
print(s[7:]) # -> "Python!" (to the end)
# Using a step
print(s[::2]) # -> "Hlo yhn" (every other character)
# Using negative indices
print(s[-1]) # -> "!" (last character)
print(s[-6:]) # -> "Python!" (from 6th-to-last character to the end)
print(s[:-1]) # -> "Hello, Python" (all but the last character)
# Reversing a string (the classic use case)
print(s[::-1]) # -> "!nohtyP ,olleH"
JavaScript
JavaScript does not have a corresponding slicing syntax and instead relies on built-in methods. The most common are slice()
and substring()
.
slice(beginIndex, endIndex)
: Extracts a section of a string and returns it as a new string.endIndex
is optional and not included. Supports negative indices, which indicate an offset from the end of the string.substring(indexStart, indexEnd)
: Similar toslice()
but does not support negative indices (treats them as 0).
Operations & API:
let s = "Hello, JavaScript!";
// Using slice() (recommended)
s.slice(0, 5); // -> "Hello"
s.slice(7, 17); // -> "JavaScript"
s.slice(7); // -> "JavaScript!" (to the end)
// slice() supports negative indices
s.slice(-1); // -> "!" (last character)
s.slice(-10); // -> "JavaScript!" (from 10th-to-last to the end)
s.slice(0, -1); // -> "Hello, JavaScript"
// Using substring()
s.substring(0, 5); // -> "Hello"
// substring() does not support negative indices
s.substring(-10, 5); // Negative is treated as 0 -> s.substring(0, 5) -> "Hello"
// JS has no direct one-step method for reversing a string; it requires a combination of methods
s.split('').reverse().join(''); // -> "!tpircSavaJ ,olleH"
Core Comparison
- Syntax vs. Method: This is the core difference. Python uses a built-in, powerful, and elegant
[]
syntax for slicing, while JavaScript must rely on method calls like.slice()
. - Functionality & Conciseness: Python's
step
parameter makes it functionally more powerful. Operations likes[::2]
ors[::-1]
require more complex code in JavaScript. String reversal, in particular, is extremely concise in Python. - Negative Indices: Python's slicing syntax offers consistent and intuitive support for negative indices. In JavaScript, only the
slice()
method supports them, whilesubstring()
does not, which can lead to confusion. - Immutability: Both are the same in this regard. Neither Python's slicing nor JavaScript's
.slice()
/.substring()
methods modify the original string; they return a new substring.
3. Boolean Type
Python
Uses the bool
type, whose values must be True
or False
, with a capital letter.
Important Feature: In Python, bool
is a subclass of int
. True
behaves like 1
, and False
behaves like 0
.
is_active = True
has_permission = False
print(True == 1) # -> True
print(False == 0) # -> True
print(True + 3) # -> 4
JavaScript
Uses the boolean
type, with values true
or false
, all lowercase.
let isActive = true;
let hasPermission = false;
console.log(true == 1); // -> true
console.log(false == 0); // -> true
console.log(true + 3); // -> 4
Core Comparison
The most obvious difference is casing: Python's True
/False
vs. JavaScript's true
/false
. This is a very common beginner mistake. Behaviorally, they are similar when compared or used in calculations with numbers.
4. Nullish Types
Python
Python has only one value to represent "nothing" or "empty": None
. It is a special, unique object of type NoneType
.
# Functions that don't return a value implicitly return None
def do_nothing():
pass
result = do_nothing() # result is None
# Checking for None
if result is None:
print("No value returned")
JavaScript
JavaScript has two values to represent "nothing" or "empty": null
and undefined
.
undefined
: Typically means a variable has been declared but not yet assigned a value.null
: Is usually assigned by a developer to intentionally represent an empty value.
let a; // a is undefined
let b = null; // b is null
// Function parameters not provided are also undefined
function greet(name) {
console.log(`Hello, ${name}`);
}
greet(); // Outputs "Hello, undefined"
Core Comparison
This is a key philosophical difference between the two languages. Python's None
simplifies checking for "nullness." JavaScript's null
and undefined
provide a more nuanced distinction but are also a frequent source of bugs, requiring developers to understand and correctly handle the different behaviors of ==
and ===
when checking for them.
5. Type Checking
Python
type()
: Returns the exact type of an object.isinstance()
: Checks if an object is an instance of a class or its subclasses. This is generally the recommended way to check types.
num = 10
is_int = isinstance(num, int) # -> True
is_float = isinstance(num, float) # -> False
is_num = isinstance(num, (int, float)) # -> True
type(num) == int # -> True
JavaScript
typeof
: An operator that returns a string representing the type of an operand (e.g.,"number"
,"string"
,"boolean"
).instanceof
: Checks if an object is an instance of a constructor.
let num = 10;
typeof num; // -> "number"
let s = "hello";
typeof s; // -> "string"
// A famous quirk of typeof
typeof null; // -> "object"
class Person {}
let p = new Person();
p instanceof Person; // -> true
Core Comparison
- Return Value: Python's
type()
returns a type object, whereas JS'stypeof
returns a string. - Reliability: JS's
typeof
can have unintuitive return values for things likenull
and arrays ("object"
). Python'sisinstance()
is generally the gold standard for type checking because it correctly handles inheritance.