Introduction
JavaScript is a versatile programming language used in web development, backend (Node.js), and even mobile applications. This chapter provides a refresher on JavaScript fundamentals.
1. Variables and Data Types
JavaScript supports three main variable declarations:
var
(old, avoid using it)let
(block-scoped, preferred for mutable variables)const
(block-scoped, used for constants)
Example:
let name = "Alice";
const age = 25;
var city = "Paris";
console.log(name, age, city);
Data Types:
- Primitive: Number, String, Boolean, Null, Undefined, Symbol, BigInt
- Non-Primitive: Object, Array, Function
Example:
let isDeveloper = true; // Boolean
let salary = 5000.50; // Number
let emptyValue = null; // Null
let notDefined; // Undefined
2. Operators
Arithmetic Operators:
let x = 10;
let y = 5;
console.log(x + y, x - y, x * y, x / y, x % y);
Comparison Operators:
console.log(10 > 5); // true
console.log(10 === "10"); // false (strict equality)
console.log(10 == "10"); // true (loose equality)
3. Control Flow (if, else, switch)
Example:
let num = 10;
if (num > 5) {
console.log("Number is greater than 5");
} else {
console.log("Number is 5 or less");
}
Switch Statement:
let fruit = "apple";
switch (fruit) {
case "apple":
console.log("It’s an apple!");
break;
case "banana":
console.log("It’s a banana!");
break;
default:
console.log("Unknown fruit");
}
4. Loops (for, while, do-while)
For Loop Example:
for (let i = 0; i < 5; i++) {
console.log("Iteration", i);
}
While Loop Example:
let count = 3;
while (count > 0) {
console.log("Countdown: ", count);
count--;
}
5. Functions
Function Declaration:
function greet(name) {
return "Hello, " + name;
}
console.log(greet("Alice"));
Arrow Function:
const add = (a, b) => a + b;
console.log(add(3, 7));
6. Arrays and Objects
Arrays:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[1]); // Access element
fruits.push("Mango"); // Add element
console.log(fruits);
Objects:
let person = {
name: "Alice",
age: 25,
city: "Paris"
};
console.log(person.name); // Access property
7. Promises & Async/Await
Using Promises:
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 2000);
});
myPromise.then(result => console.log(result));
Async/Await Example:
async function fetchData() {
let result = await myPromise;
console.log(result);
}
fetchData();
🏆 Exercises
- 1. Fix the errors:
let name = "John";
const age;
age = 30;
console.log("Name:" name "Age:" age);
- 2. Write a function that checks if a number is even or odd.
- 3. Create an array of numbers and find the sum of all elements.
- 4. Write a function that takes a string and returns it reversed.
- 5. Create an object with at least three properties and log one of them.
Conclusion
Mastering JavaScript fundamentals is essential before diving deeper into Node.js. Understanding variables, functions, loops, and async programming will help in backend development.