Javascript Classes and Functions
JavaScript Fundamentals โ Summary with Examples and Exercises
This document summarizes essential JavaScript concepts related to classes, functions, frontend (React), and backend (Node.js), including practical examples and exercises.
๐ 1. Difference Between Node.js and React
Technology | What it is | Purpose |
---|---|---|
Node.js | JavaScript runtime (backend) | Runs server-side code, builds APIs |
React | JavaScript library (frontend) | Builds user interfaces in the browser |
๐งช Example
Node.js server:
app.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from backend!' });
});
React frontend:
useEffect(() => {
fetch('http://localhost:5000/api/hello')
.then(res => res.json())
.then(data => setMessage(data.message));
}, []);
โ Exercise
- Create a simple Express API with one route that returns
"Welcome"
. - Create a React app that fetches this message and displays it.
๐งฑ 2. How Frontend Talks to Backend
- React uses
fetch()
oraxios
to request data. - Node.js must enable CORS to allow cross-origin access:
const cors = require('cors');
app.use(cors());
โ Exercise
- Add CORS support in Express.
- Create a button in React that fetches data from a
/api/data
route on click.
๐งฑ 3. Classes (class
) in JavaScript
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, my name is ${this.name}`);
}
}
โ Exercise
- Create a
Car
class withbrand
,model
, andyear
. - Add a
describe()
method that prints the car info. - Instantiate two cars and call their method.
๐ง 4. Functions (function
)
function isAdult(age) {
return age >= 18;
}
โ Exercise
- Create a function
calculatePrice(price, tax)
that returns total with tax. - Create a function
welcome(name)
that returnsWelcome, <name>
.
๐ค 5. Classes and Functions Together
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
function totalPrice(products) {
return products.reduce((sum, p) => sum + p.price, 0);
}
โ Exercise
- Create a
Customer
class withname
and acart
(list of products). - Create a function
calculateTotal(customer)
that sums the cart items.
๐งญ 6. Export and Import
Export a class:
export class Person {
constructor(name) {
this.name = name;
}
}
Import:
import { Person } from './Person.js';
โ Exercise
- Create a file
Person.js
with aPerson
class. - Export it and import it in
main.js
. - Instantiate the class and call a method.
โก 7. Arrow Functions
const add = (a, b) => a + b;
const greet = name => `Hi, ${name}`;
โ Exercise
- Create an arrow function
areEqual(a, b)
that returnstrue
if the numbers match. - Create an array of names, and use
map()
with an arrow function to printHi, <name>
.
๐ Key Concepts
Concept | Explanation |
---|---|
this | Refers to the object the method/function belongs to |
constructor() | Runs when using new on a class |
new | Creates a new object from a class |
export/import | Allows sharing code across files |
Updated: July 2025