4.1: JavaScript Fundamentals & Syntax
Learn JavaScript fundamentals including variables, data types, and basic syntax for adding interactivity to web pages. Understand how JavaScript works in the browser and write your first interactive scripts.
1. What is JavaScript?
JavaScript (JS) is the programming language of the web, enabling dynamic and interactive behavior on websites.
The Three Pillars Revisited
HTML (Structure) → The content and layout
CSS (Presentation) → The visual styling
JavaScript (Behavior) → The interactivity and logic
What JavaScript does:
- Respond to user interactions (clicks, typing, scrolling)
- Modify HTML content and CSS styles dynamically
- Validate form inputs before submission
- Fetch data from servers without page reload (AJAX)
- Build complex web applications (SPAs)
- Power animations and visual effects
JavaScript vs Python: First Impressions
Python:
# Python
def greet(name):
return f"Hello, {name}!"
print(greet("World")) # Hello, World!
JavaScript:
// JavaScript
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World")); // Hello, World!
Key differences:
- JavaScript uses
{}curly braces instead of indentation - JavaScript uses
functionkeyword (Python usesdef) - JavaScript uses
;semicolons (optional but recommended) - JavaScript uses
console.log()(Python usesprint())
2. JavaScript Syntax Basics
Statement Structure
Unlike Python's indentation-based syntax, JavaScript uses curly braces and semicolons.
Python:
if x > 5:
print("Greater than 5")
print("Still in if block")
JavaScript:
if (x > 5) {
console.log("Greater than 5");
console.log("Still in if block");
}
Semicolons
JavaScript statements typically end with semicolons:
let x = 10;
let y = 20;
let sum = x + y;
console.log(sum); // 30
Note: Semicolons are technically optional due to Automatic Semicolon Insertion (ASI), but best practice is to use them to avoid unexpected behavior.
Comments
Single-line comments:
// This is a single-line comment
let x = 5; // This is also a comment
Multi-line comments:
/*
This is a multi-line comment
spanning multiple lines
like Python's triple quotes
*/
Python comparison:
# Python single-line comment
"""
Python multi-line comment
or docstring
"""
Case Sensitivity
JavaScript is case-sensitive (like Python):
let name = "Alice";
let Name = "Bob"; // Different variable!
let NAME = "Charlie"; // Also different!
console.log(name); // Alice
console.log(Name); // Bob
Whitespace
JavaScript ignores extra whitespace (unlike Python):
// All valid:
let x=5;
let x = 5;
let x = 5;
// Same for objects
let user={name:"Alice",age:30};
let user = { name: "Alice", age: 30 }; // More readable
3. Where JavaScript Runs
1. Browser Console
The quickest way to test JavaScript:
Chrome/Edge/Firefox:
- Press
F12or right-click → "Inspect" - Click "Console" tab
- Type JavaScript and press Enter
// Try in console:
console.log("Hello from console!");
2 + 2
Math.random()
alert("Hello!")
2. Inline Script
JavaScript embedded in HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline JavaScript</title>
</head>
<body>
<h1>JavaScript Demo</h1>
<script>
console.log("Page loaded!");
alert("Welcome to JavaScript!");
</script>
</body>
</html>
3. External JavaScript File (Best Practice)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>External JavaScript</title>
</head>
<body>
<h1>External Script Demo</h1>
<!-- Load JavaScript at end of body -->
<script src="script.js"></script>
</body>
</html>
script.js:
console.log("Script loaded from external file!");
function greet() {
alert("Hello from external script!");
}
greet();
Best practice: Place <script> tags at the end of the <body> to ensure HTML loads before JavaScript runs.
Script Loading Strategies
<!-- Defers execution until HTML is parsed -->
<script src="script.js" defer></script>
<!-- Downloads and executes immediately -->
<script src="script.js" async></script>
<!-- Traditional: blocks HTML parsing -->
<script src="script.js"></script>
4. Variables and Constants
Variable Declaration
JavaScript has three ways to declare variables:
1. let (block-scoped, modern):
let age = 25;
let name = "Alice";
let isStudent = true;
age = 26; // Can reassign
2. const (block-scoped, constant):
const PI = 3.14159;
const APP_NAME = "MyApp";
// PI = 3.14; // Error: Cannot reassign constant
3. var (function-scoped, legacy):
var oldWay = "Avoid using var";
// var has quirky scoping rules - use let/const instead
Python comparison:
# Python - no declaration keyword needed
age = 25
name = "Alice"
is_student = True
# Python constants are just conventions (UPPERCASE)
PI = 3.14159
Best practice:
- Use
constby default - Use
letwhen you need to reassign - Never use
varin modern JavaScript
Naming Conventions
JavaScript (camelCase):
let firstName = "John";
let lastName = "Doe";
let userAge = 30;
let isLoggedIn = false;
Python (snake_case):
first_name = "John"
last_name = "Doe"
user_age = 30
is_logged_in = False
Constants:
const MAX_USERS = 100; // UPPERCASE for true constants
const API_URL = "https://...";
5. Data Types
Primitive Types
JavaScript has 7 primitive types:
1. Number (includes integers and floats):
let age = 25; // Integer
let price = 19.99; // Float
let negative = -10;
let infinity = Infinity;
let notNumber = NaN; // Not a Number
Python comparison:
age = 25 # int
price = 19.99 # float
2. String:
let single = 'Hello';
let double = "World";
let backtick = `Template literal`;
// Template literals (like Python f-strings)
let name = "Alice";
let greeting = `Hello, ${name}!`; // Hello, Alice!
Python comparison:
name = "Alice"
greeting = f"Hello, {name}!" # f-string
3. Boolean:
let isTrue = true; // lowercase (not True)
let isFalse = false; // lowercase (not False)
4. Undefined:
let x;
console.log(x); // undefined (no Python equivalent)
5. Null:
let empty = null; // Intentional absence of value
6. Symbol (advanced, rarely used):
let id = Symbol("id");
7. BigInt (for large integers):
let bigNumber = 1234567890123456789012345678901234567890n;
Complex Types
Objects:
let person = {
name: "Alice",
age: 30,
city: "NYC"
};
Arrays:
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "two", true, null];
Type Checking
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (JavaScript quirk!)
typeof [1, 2, 3]; // "object" (arrays are objects)
typeof {name: "A"}; // "object"
Python comparison:
type(42) # <class 'int'>
type("hello") # <class 'str'>
type(True) # <class 'bool'>
6. Operators
Arithmetic Operators
Same as Python:
let sum = 10 + 5; // 15
let diff = 10 - 5; // 5
let product = 10 * 5; // 50
let quotient = 10 / 5; // 2
let remainder = 10 % 3; // 1
let power = 10 ** 2; // 100 (exponentiation)
Increment/Decrement (not in Python):
let count = 0;
count++; // 1 (same as count = count + 1)
count--; // 0 (same as count = count - 1)
// Pre vs Post increment
let x = 5;
let y = x++; // y = 5, x = 6 (post-increment)
let z = ++x; // z = 7, x = 7 (pre-increment)
Comparison Operators
Strict equality (recommended):
5 === 5 // true (same value and type)
5 === "5" // false (different types)
5 !== "5" // true (not equal)
Loose equality (avoid):
5 == "5" // true (type coercion!)
0 == false // true (type coercion!)
null == undefined // true (quirky!)
Python comparison:
5 == 5 # True
5 == "5" # False (no type coercion)
Best practice: Always use === and !== in JavaScript.
Other comparisons:
5 > 3 // true
5 < 3 // false
5 >= 5 // true
5 <= 4 // false
Logical Operators
true && false // false (AND)
true || false // true (OR)
!true // false (NOT)
Python comparison:
True and False # False
True or False # True
not True # False
String Concatenation
let first = "Hello";
let last = "World";
let result = first + " " + last; // "Hello World"
// Template literals (better)
let greeting = `${first} ${last}`; // "Hello World"
7. Console Methods
Output to console:
console.log("Normal message");
console.error("Error message");
console.warn("Warning message");
console.info("Info message");
console.table([{name: "Alice", age: 30}, {name: "Bob", age: 25}]);
Python comparison:
print("Message") # Basic output
Debugging:
let x = 10;
console.log("Value of x:", x);
// Multiple values
console.log("x:", x, "type:", typeof x);
// Template literal
console.log(`x = ${x}`);
8. Practical Examples
Example 1: Basic Calculator
JavaScript:
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
console.log(add(5, 3)); // 8
console.log(multiply(4, 7)); // 28
Python equivalent:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
print(add(5, 3)) # 8
print(multiply(4, 7)) # 28
Example 2: String Manipulation
let message = "JavaScript is awesome!";
console.log(message.length); // 22
console.log(message.toUpperCase()); // JAVASCRIPT IS AWESOME!
console.log(message.toLowerCase()); // javascript is awesome!
console.log(message.includes("Java")); // true
console.log(message.startsWith("Java")); // true
console.log(message.slice(0, 10)); // JavaScript
Python comparison:
message = "JavaScript is awesome!"
len(message) # 22
message.upper() # JAVASCRIPT IS AWESOME!
message.lower() # javascript is awesome!
"Java" in message # True
message.startswith("Java") # True
message[0:10] # JavaScript
Example 3: Type Conversion
// String to Number
let strNum = "42";
let num = Number(strNum); // 42
let num2 = parseInt(strNum); // 42
let float = parseFloat("3.14"); // 3.14
// Number to String
let num3 = 42;
let str = String(num3); // "42"
let str2 = num3.toString(); // "42"
// Boolean conversion
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
Python comparison:
str_num = "42"
num = int(str_num) # 42
float_num = float("3.14") # 3.14
num = 42
string = str(num) # "42"
bool(1) # True
bool(0) # False
bool("") # False
bool("hello") # True
9. JavaScript Quirks (vs Python)
1. Truthy and Falsy Values
Falsy values in JavaScript:
false
0
-0
0n (BigInt zero)
"" (empty string)
null
undefined
NaN
Everything else is truthy:
if ("0") console.log("Truthy!"); // Runs!
if ("false") console.log("Truthy!"); // Runs!
if ([]) console.log("Truthy!"); // Runs! (empty array)
if ({}) console.log("Truthy!"); // Runs! (empty object)
Python comparison:
# Falsy: False, 0, 0.0, "", [], {}, None
if []:
print("Won't run") # Empty list is falsy in Python
2. Type Coercion
JavaScript automatically converts types:
"3" + 2 // "32" (number to string)
"3" - 2 // 1 (string to number)
"3" * "2" // 6 (both to numbers)
true + 1 // 2 (true = 1)
false + 1 // 1 (false = 0)
Python:
"3" + 2 # Error: cannot concatenate str and int
3. No Integer Division Operator
10 / 3 // 3.3333... (always float division)
Math.floor(10 / 3) // 3 (manual integer division)
Python:
10 / 3 # 3.3333...
10 // 3 # 3 (integer division)
10. Debugging JavaScript
Using Browser DevTools
Console Tab:
console.log("Debug message");
console.error("Error occurred");
console.warn("Warning");
// Inspect objects
let user = { name: "Alice", age: 30 };
console.log(user);
console.table(user);
Breakpoints:
- Open DevTools → Sources tab
- Find your script file
- Click line number to set breakpoint
- Reload page - execution pauses at breakpoint
- Inspect variables, step through code
Debugger Statement:
function calculate(x, y) {
debugger; // Execution pauses here if DevTools open
return x * y;
}
11. Practical Exercises
Exercise 4.1.1: First JavaScript Program
Create an HTML file with external JavaScript that:
- Declares variables for your name, age, and city
- Uses
console.log()to print them - Uses template literals to create a greeting
Exercise 4.1.2: Type Exploration
Write JavaScript to:
- Create variables of each primitive type
- Use
typeofto check each type - Experiment with type coercion (e.g.,
"5" + 5)
Exercise 4.1.3: Python to JavaScript Translation
Translate this Python code to JavaScript:
name = "Alice"
age = 30
is_student = False
print(f"{name} is {age} years old")
if age >= 18:
print("Adult")
else:
print("Minor")
Exercise 4.1.4: Console Calculator
Create a calculator that:
- Defines functions for add, subtract, multiply, divide
- Tests each function with
console.log() - Handles division by zero
12. Knowledge Check
Question 1: What are the three ways to include JavaScript in an HTML page?
Show answer
Inline (in script tags), external (linked .js file), and inline event handlers (not recommended). Best practice is external .js files loaded at end of body.Question 2: What's the difference between let and const?
Show answer
`let` allows reassignment, `const` does not. Both are block-scoped. Use `const` by default, `let` when reassignment needed.Question 3: What's the difference between == and ===?
Show answer
`==` performs type coercion (5 == "5" is true), `===` checks both value and type (5 === "5" is false). Always use `===`.Question 4: How does JavaScript handle division differently from Python?
Show answer
JavaScript always performs float division (10/3 = 3.333...). Python has // for integer division. JavaScript needs Math.floor(10/3) for integer division.Question 5: What are falsy values in JavaScript?
Show answer
false, 0, -0, 0n, "" (empty string), null, undefined, and NaN. Everything else is truthy, including "0", "false", [], and {}.13. Key Takeaways
- JavaScript is the programming language for web interactivity
- JavaScript uses curly braces
{}and semicolons;(unlike Python's indentation) - Use
constby default,letfor reassignment, nevervar - JavaScript has 7 primitive types: number, string, boolean, undefined, null, symbol, bigint
- Always use
===for equality (not==) - JavaScript uses
camelCasenaming (Python usessnake_case) console.log()is JavaScript'sprint()- Template literals
\${variable}`` work like Python f-strings - JavaScript has quirky type coercion - be aware of truthy/falsy values
- Browser DevTools Console is essential for testing and debugging
14. Further Resources
Documentation:
- MDN JavaScript Guide
- JavaScript.info - Comprehensive tutorial
Practice:
Reference:
Next Steps
Congratulations! You've learned JavaScript fundamentals and syntax, and how it compares to Python.
In Lesson 4.2: Variables, Data Types & Operators, you'll dive deeper into JavaScript's type system, explore operators in detail, and master type conversion and coercion.
Next: Lesson 4.2 - Variables, Data Types & Operators →