Variables and Operators in JavaScript
Learn JavaScript variables, data types, and operators from a Python developer's perspective, with direct comparisons and practical examples.
1. Variable Declaration
Python vs JavaScript Variable Declaration
Python:
# Python - Simple assignmentname = "Alice"age = 25is_student = True# Variables can be reassignedname = "Bob"age = 30
JavaScript:
// JavaScript - Explicit declaration keywordsconst name = "Alice"; // Cannot be reassignedlet age = 25; // Can be reassignedvar isStudent = true; // Legacy, avoid using// Reassignment// name = "Bob"; // Error! const cannot be reassignedage = 30; // OK with let
Variable Declaration Keywords
| Keyword | Reassignable | Block Scoped | Hoisted | When to Use |
|---|---|---|---|---|
const | ❌ No | ✅ Yes | ❌ No | Default choice, immutable binding |
let | ✅ Yes | ✅ Yes | ❌ No | When you need to reassign |
var | ✅ Yes | ❌ No | ✅ Yes | Legacy, avoid in modern code |
2. Data Types Comparison
Primitive Types
Python:
# Python data typestext = "Hello" # strnumber = 42 # intfloat_num = 3.14 # floatis_true = True # boolnothing = None # NoneType
JavaScript:
// JavaScript data typesconst text = "Hello"; // stringconst number = 42; // numberconst floatNum = 3.14; // number (same as integer)const isTrue = true; // booleanconst nothing = null; // nullconst undefined = undefined; // undefined (unique to JS)
Type Checking
Python:
print(type(42)) # <class 'int'>print(isinstance(42, int)) # True
JavaScript:
console.log(typeof 42); // "number"console.log(Number.isInteger(42)); // true
3. Operators
Arithmetic Operators
| Operation | Python | JavaScript | Notes |
|---|---|---|---|
| Addition | + | + | Same |
| Subtraction | - | - | Same |
| Multiplication | * | * | Same |
| Division | / | / | Python: float result, JS: number |
| Floor Division | // | Math.floor(a/b) | Different syntax |
| Modulo | % | % | Same |
| Exponentiation | ** | ** | Same (ES2016+) |
Examples:
# Pythonresult = 10 / 3 # 3.3333...floor_div = 10 // 3 # 3power = 2 ** 3 # 8
// JavaScriptconst result = 10 / 3; // 3.3333...const floorDiv = Math.floor(10 / 3); // 3const power = 2 ** 3; // 8
Comparison Operators
Python:
# Python - Straightforward comparisonsprint(5 == 5) # Trueprint(5 == "5") # False (no type coercion)print(5 is 5) # True (identity)
JavaScript:
// JavaScript - Two types of equalityconsole.log(5 == 5); // trueconsole.log(5 == "5"); // true (type coercion!)console.log(5 === "5"); // false (strict equality)console.log(5 === 5); // true
Logical Operators
| Operation | Python | JavaScript |
|---|---|---|
| AND | and | && |
| OR | or | || |
| NOT | not | ! |
Examples:
# Pythonresult = True and False # Falseresult = True or False # Trueresult = not True # False
// JavaScriptconst result1 = true && false; // falseconst result2 = true || false; // trueconst result3 = !true; // false
4. String Operations
String Formatting
Python:
name = "Alice"age = 25# f-strings (preferred)message = f"Hello, {name}! You are {age} years old."# .format() methodmessage = "Hello, {}! You are {} years old.".format(name, age)
JavaScript:
const name = "Alice";const age = 25;// Template literals (preferred)const message = `Hello, ${name}! You are ${age} years old.`;// String concatenationconst message2 = "Hello, " + name + "! You are " + age + " years old.";
String Methods
Python:
text = "Hello World"print(text.lower()) # "hello world"print(text.upper()) # "HELLO WORLD"print(text.split()) # ["Hello", "World"]print(len(text)) # 11
JavaScript:
const text = "Hello World";console.log(text.toLowerCase()); // "hello world"console.log(text.toUpperCase()); // "HELLO WORLD"console.log(text.split(" ")); // ["Hello", "World"]console.log(text.length); // 11
5. Type Conversion
Explicit Conversion
Python:
# Python type conversionnum_str = "42"num = int(num_str) # 42float_num = float(num_str) # 42.0str_num = str(42) # "42"bool_val = bool(1) # True
JavaScript:
// JavaScript type conversionconst numStr = "42";const num = parseInt(numStr); // 42const floatNum = parseFloat(numStr); // 42const strNum = String(42); // "42"const boolVal = Boolean(1); // true// Alternative methodsconst num2 = Number(numStr); // 42const num3 = +numStr; // 42 (unary plus)
Implicit Conversion (JavaScript Only)
// JavaScript automatic type coercionconsole.log("5" + 3); // "53" (string concatenation)console.log("5" - 3); // 2 (numeric subtraction)console.log("5" * 3); // 15 (numeric multiplication)console.log(!"hello"); // false (truthy string becomes false)
6. Best Practices
Variable Naming
Python:
# Python - snake_caseuser_name = "alice"max_retry_count = 3is_valid_email = True
JavaScript:
// JavaScript - camelCaseconst userName = "alice";const maxRetryCount = 3;const isValidEmail = true;
Modern JavaScript Recommendations
- Use
constby default,letwhen reassignment is needed - Avoid
var- it has confusing scoping rules - Use strict equality (
===) instead of loose equality (==) - Use template literals for string interpolation
- Be aware of type coercion - it can cause unexpected behavior
7. Common Pitfalls for Python Developers
1. Truthy/Falsy Values
Python:
# Python falsy valuesif not 0: print("0 is falsy") # Printsif not "": print("Empty string is falsy") # Printsif not []: print("Empty list is falsy") # Prints
JavaScript:
// JavaScript falsy values (more than Python)if (!0) console.log("0 is falsy"); // Printsif (!"") console.log("Empty string is falsy"); // Printsif (!null) console.log("null is falsy"); // Printsif (!undefined) console.log("undefined is falsy"); // Printsif (!NaN) console.log("NaN is falsy"); // Prints
2. Variable Hoisting
// This works in JavaScript (but shouldn't be used)console.log(x); // undefined (not an error!)var x = 5;// This is what actually happens:// var x;// console.log(x); // undefined// x = 5;
8. Next Steps
In the next module, we'll explore:
- Functions and their different syntax
- Arrow functions vs regular functions
- Scope and closures
- Function parameters and default values
Practice Exercise: Try converting some of your Python variable declarations and operations to JavaScript syntax!