What is JavaScript?
5 min read
JavaScript is a high-level, interpreted programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. Created by Brendan Eich in 1995, JavaScript enables interactive web pages and is an essential part of web applications.
JavaScript is the most widely used programming language in the world, running on virtually every website. It's used for frontend development (React, Vue, Angular), backend development (Node.js), mobile apps (React Native), and even desktop applications. JavaScript's versatility and ubiquity make it essential for modern web development.
⚡ Why JavaScript is Essential
- ✓Universal: Runs in every browser, no installation needed
- ✓Versatile: Frontend, backend, mobile, desktop - one language for all
- ✓Huge ecosystem: Millions of packages on npm, vast frameworks
- ✓High demand: #1 most used language, essential for web jobs
- ✓Modern features: ES6+ brings powerful features like async/await, classes, modules
// Your first JavaScript program
console.log("Hello, World!");
const name = "JavaScript";
console.log(`Welcome to ${name}!`);JavaScript Syntax Basics
8 min read
JavaScript syntax is clean and readable. Understanding these fundamental rules will help you write JavaScript code effectively.
✓ JavaScript Features
- •Indentation-based blocks (no curly braces)
- •Dynamic typing (no type declarations)
- •Comments start with
# - •Case-sensitive (name ≠ Name)
- •Variables don't need declaration
- •Multiple assignment:
a, b = 1, 2
📝 Code Structure
- •Use 4 spaces for indentation (standard)
- •Colon
:starts code blocks - •No semicolons needed (optional)
- •Line continuation with
\or parentheses - •String quotes: single or double (both work)
✗ Wrong Indentation
if x > 0:
print("Positive") # IndentationError!
print("Still positive")✓ Correct Indentation
if x > 0:
print("Positive") # Correct!
print("Still positive")Try It Yourself
Edit the JavaScript code and see the results
Try these examples:
Variables & Data Types
10 min read
JavaScript is dynamically typed, meaning you don't need to declare variable types. Python automatically determines the type based on the value assigned.
Basic Data Types
Integer
age = 30
count = -5
big_number = 1000000Whole numbers, positive or negative. No size limit in Python 3.
Float
price = 19.99
pi = 3.14159
temperature = -5.5Decimal numbers. Use for calculations requiring precision.
String
name = "Python"
message = 'Hello, World!'
multiline = """This is
a multiline
string"""Text data. Can use single, double, or triple quotes. Triple quotes for multiline strings.
Boolean
is_active = True
is_complete = False
has_permission = TrueTrue or False (capitalized). Used for conditional logic.
List
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]Ordered, mutable collection. Can contain any data type, including mixed types.
Dictionary
person = {
"name": "John",
"age": 30,
"city": "NYC"
}Key-value pairs. Keys must be immutable (strings, numbers, tuples).
Tuple
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # Note the commaOrdered, immutable collection. Faster than lists, used for fixed data.
None
result = None
value = NoneRepresents absence of value. Similar to null in other languages.
Operators & Expressions
8 min read
JavaScript supports various operators for performing operations on variables and values.
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 10 - 4 = 6 |
| * | Multiplication | 3 * 4 = 12 |
| / | Division (float) | 10 / 3 = 3.333... |
| // | Floor division | 10 // 3 = 3 |
| % | Modulus (remainder) | 10 % 3 = 1 |
| ** | Exponentiation | 2 ** 3 = 8 |
Comparison Operators
x = 5
y = 10
print(x == y) # False (equal)
print(x != y) # True (not equal)
print(x < y) # True (less than)
print(x > y) # False (greater than)
print(x <= y) # True (less than or equal)
print(x >= y) # False (greater than or equal)Logical Operators
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # FalseControl Flow
12 min read
Control flow statements allow you to control the execution order of your code. JavaScript supports if/else, loops, and more.
If/Else Statements
age = 20
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")For Loops
# Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Iterate with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Range function
for i in range(5):
print(i) # 0, 1, 2, 3, 4While Loops
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# Break and continue
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
if user_input == 'skip':
continue
print(f"You entered: {user_input}")Functions
10 min read
Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.
Defining Functions
# Simple function
def greet(name):
return f"Hello, {name}!"
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
# Function with multiple return values
def get_name_and_age():
return "John", 30
name, age = get_name_and_age()Lambda Functions
# Lambda (anonymous) function
square = lambda x: x ** 2
print(square(5)) # 25
# Used with map, filter, etc.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]Objects & Arrays
12 min read
Objects and arrays are JavaScript's most commonly used data structures for storing collections of data.
Lists
# Create a list
fruits = ["apple", "banana", "orange"]
# Access elements
print(fruits[0]) # "apple"
print(fruits[-1]) # "orange" (last item)
# Modify list
fruits.append("grape") # Add item
fruits.remove("banana") # Remove item
fruits.insert(1, "mango") # Insert at index
# List methods
fruits.sort() # Sort alphabetically
fruits.reverse() # Reverse order
length = len(fruits) # Get lengthDictionaries
# Create a dictionary
person = {
"name": "John",
"age": 30,
"city": "NYC"
}
# Access values
print(person["name"]) # "John"
print(person.get("age")) # 30
print(person.get("email", "N/A")) # "N/A" (default)
# Modify dictionary
person["email"] = "john@example.com" # Add/update
person.pop("age") # Remove key
person.clear() # Clear all items
# Dictionary methods
keys = person.keys() # Get all keys
values = person.values() # Get all values
items = person.items() # Get key-value pairsDOM Manipulation
15 min read
The Document Object Model (DOM) represents the structure of HTML documents. JavaScript can manipulate the DOM to create dynamic, interactive web pages.
Selecting Elements
// Select elements
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"I'm {self.name}, {self.age} years old"
def have_birthday(self):
self.age += 1
# Create objects (instances)
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.introduce()) # "I'm Alice, 25 years old"
person1.have_birthday()
print(person1.age) # 26Inheritance
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# Derived class
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Buddy")
print(dog.speak()) # "Woof!"Events
12 min read
Events allow JavaScript to respond to user interactions like clicks, keyboard input, and form submissions. Understanding events is essential for creating interactive web applications.
Event Listeners
// Add event listener
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
// Arrow function syntax
button.addEventListener('click', () => {
console.log('Button clicked!');
});
# Read all lines into list
with open('data.txt', 'r') as file:
lines = file.readlines()Writing Files
# Write to file (overwrites)
with open('output.txt', 'w') as file:
file.write("Hello, World!")
# Append to file
with open('output.txt', 'a') as file:
file.write("\nNew line")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open('output.txt', 'w') as file:
file.writelines(lines)Async JavaScript
15 min read
JavaScript is single-threaded but handles asynchronous operations through callbacks, Promises, and async/await. Understanding async programming is essential for working with APIs, timers, and user interactions.
Promises
// Create a Promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded!");
}, 1000);
});
};
// Use Promise
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));Async/Await
// Async function
async function fetchUserData() {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}
// Call async function
fetchUserData().then(user => console.log(user));Fetch API
// Fetch data from API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
// Using async/await
async function getData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}Modules & Packages
12 min read
ES6 (ECMAScript 2015) and later versions introduced powerful features like arrow functions, destructuring, template literals, classes, and modules. These modern features make JavaScript more expressive and easier to write.
Arrow Functions
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function (ES6+)
const add = (a, b) => a + b;
// Arrow function with body
const greet = (name) => {
return `Hello, ${name}!`;
}
// Arrow function with single parameter (no parentheses needed)
const square = x => x * x;Destructuring
// Array destructuring
const [first, second, third] = [1, 2, 3];
// Object destructuring
const person = { name: "John", age: 30 };
const { name, age } = person;
// Destructuring with default values
const { name, age = 25 } = person;Template Literals
// Template literals (backticks)
const name = "JavaScript";
const message = `Hello, ${name}!`;
// Multi-line strings
const html = `
<div>
<h1>Title</h1>
</div>
`;Common Mistakes
10 min read
Even experienced JavaScript developers make these mistakes. Learn to avoid them early.
Indentation Errors
JavaScript uses indentation to define code blocks. Use 4 spaces consistently (not tabs).
✗ Wrong
if x > 0:
print("Positive") # IndentationError!✓ Correct
if x > 0:
print("Positive") # Correct indentationMutable Default Arguments
Mutable default arguments are shared across function calls. Use None as default instead.
✗ Wrong
def add_item(item, my_list=[]):
my_list.append(item)
return my_list✓ Correct
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_listModifying List While Iterating
Modifying a list while iterating can cause unexpected behavior. Use list comprehension or iterate over a copy.
✗ Wrong
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Dangerous!✓ Correct
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0] # List comprehensionUsing == for None
Use "is" or "is not" for None comparisons, not == or !=. This checks identity, not equality.
✗ Wrong
if value == None: # Not recommended
print("No value")✓ Correct
if value is None: # Correct
print("No value")Forgetting Return Statement
Functions without a return statement return None. Always use return for values you want to use.
✗ Wrong
def calculate_sum(a, b):
a + b # Missing return!✓ Correct
def calculate_sum(a, b):
return a + b # CorrectBest Practices
12 min read
Follow these Python best practices to write clean, maintainable, and Pythonic code.
📋Follow PEP 8 Style Guide
PEP 8 is Python's official style guide. Following it makes your code more readable and professional.
✓ Good naming
user_name = "John"
def calculate_total():
pass✗ Bad naming
userName = "John"
def CalculateTotal():
pass⚡Use List Comprehensions
List comprehensions are more Pythonic and often faster than loops.
✗ Loop approach
squares = []
for x in range(10):
squares.append(x ** 2)✓ List comprehension
squares = [x ** 2 for x in range(10)]💬Use f-strings for Formatting
f-strings (Python 3.6+) are the most readable and efficient way to format strings.
✗ Old style
name = "John"
message = "Hello, %s" % name✓ f-string
name = "John"
message = f"Hello, {name}"🔒Use Context Managers (with statement)
Always use 'with' for file operations to ensure proper cleanup.
✗ Manual cleanup
file = open('data.txt')
content = file.read()
file.close() # Easy to forget!✓ Context manager
with open('data.txt') as file:
content = file.read()
# Automatically closed📚Write Docstrings
Document your functions and classes with docstrings for better code documentation.
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle
width (float): The width of the rectangle
Returns:
float: The area of the rectangle
"""
return length * widthPractice Coding
Interactive exercises to test your skills
Put your JavaScript knowledge to the test! Complete these exercises to reinforce what you've learned. Each exercise has a solution you can check when you're ready.
Exercise 1: Hello World Program
BeginnerWrite a JavaScript program that logs "Hello, World!" to the console.
Exercise 2: Variables and Template Literals
BeginnerCreate two variables: name (string) and age (number). Then log a message combining them using a template literal.
Exercise 3: Create a Function
IntermediateWrite a function called greet that takes a name parameter and returns a greeting message. Then call it with "Alice" and log the result.
Exercise 4: Array Operations
IntermediateCreate an array of numbers [1, 2, 3, 4, 5]. Use the map() method to create a new array with each number squared.
Exercise 5: Create a Class
AdvancedCreate a Person class with a constructor that takes name and age. Add a method introduce() that returns a string with the person's name and age.