Topic: PHP Basics – Part 5 of 10: Functions in PHP (User-Defined, Built-in, Parameters, Return)
---
1. What is a Function in PHP?
• A function is a block of code that performs a specific task and can be reused.
• PHP has many built-in functions, and you can also create your own user-defined functions.
---
2. Creating User-Defined Functions
• Function names are case-insensitive.
---
3. Functions with Parameters
• Functions can accept arguments (input values):
• You can pass multiple parameters:
---
4. Default Parameter Values
• Parameters can have default values if not passed during the call:
---
5. Returning Values from Functions
• Use the
---
6. Variable Scope in PHP
• Local Scope: Variable declared inside function – only accessible there.
• Global Scope: Variable declared outside – accessible inside with
---
7. Anonymous Functions (Closures)
• Functions without a name – often used as callbacks.
---
8. Recursive Functions
• A function that calls itself.
---
9. Built-in PHP Functions (Examples)
•
•
•
•
•
---
10. Summary
• Functions keep your code organized, reusable, and clean.
• Mastering parameters, return values, and scopes is key to effective programming.
---
Exercise
• Write a function that takes a name and age, and returns a sentence like:
• Then, write a recursive function to compute the factorial of a number.
---
#PHP #Functions #PHPTutorial #WebDevelopment #Backend
https://t.iss.one/Ebooks2023
---
1. What is a Function in PHP?
• A function is a block of code that performs a specific task and can be reused.
• PHP has many built-in functions, and you can also create your own user-defined functions.
---
2. Creating User-Defined Functions
function greet() {
echo "Hello, welcome to PHP!";
}
greet(); // Call the function• Function names are case-insensitive.
---
3. Functions with Parameters
• Functions can accept arguments (input values):
function greetUser($name) {
echo "Hello, $name!";
}
greetUser("Ali"); // Output: Hello, Ali!• You can pass multiple parameters:
function add($a, $b) {
return $a + $b;
}
echo add(3, 5); // Output: 8---
4. Default Parameter Values
• Parameters can have default values if not passed during the call:
function greetLanguage($name, $lang = "English") {
echo "Hello $name, language: $lang";
}
greetLanguage("Sara"); // Output: Hello Sara, language: English---
5. Returning Values from Functions
function square($num) {
return $num * $num;
}
$result = square(6);
echo $result; // Output: 36• Use the
return statement to send a value back from the function.---
6. Variable Scope in PHP
• Local Scope: Variable declared inside function – only accessible there.
• Global Scope: Variable declared outside – accessible inside with
global.$x = 5;
function showX() {
global $x;
echo $x;
}
showX(); // Output: 5
---
7. Anonymous Functions (Closures)
• Functions without a name – often used as callbacks.
$square = function($n) {
return $n * $n;
};
echo $square(4); // Output: 16---
8. Recursive Functions
• A function that calls itself.
function factorial($n) {
if ($n <= 1) return 1;
return $n * factorial($n - 1);
}
echo factorial(5); // Output: 120---
9. Built-in PHP Functions (Examples)
•
strlen($str) – Get string length•
strtoupper($str) – Convert to uppercase•
array_sum($arr) – Sum of array elements•
isset($var) – Check if variable is set•
empty($var) – Check if variable is empty---
10. Summary
• Functions keep your code organized, reusable, and clean.
• Mastering parameters, return values, and scopes is key to effective programming.
---
Exercise
• Write a function that takes a name and age, and returns a sentence like:
"My name is Ali and I am 30 years old."• Then, write a recursive function to compute the factorial of a number.
---
#PHP #Functions #PHPTutorial #WebDevelopment #Backend
https://t.iss.one/Ebooks2023
❤3
Topic: PHP Basics – Part 7 of 10: Working with Strings
---
1. Introduction to Strings in PHP
• A string is a sequence of characters used to store and manipulate text.
• Strings can be defined using single quotes (`'`) or double quotes (`"`):
• Double quotes allow variable interpolation, single quotes do not.
---
2. Concatenating Strings
• Use the dot (
---
3. Common String Functions in PHP
Here are essential functions to manipulate strings:
•
•
•
•
•
•
---
4. Searching Within Strings
•
•
---
5. Extracting Substrings
•
---
6. Replacing Text in Strings
•
---
7. Trimming and Cleaning Strings
•
•
•
---
8. String Comparison
•
•
---
9. Escaping Characters
• Use backslash (
---
10. Summary
• Strings are core to user interaction and text processing.
• PHP offers powerful built-in functions to manipulate strings efficiently.
---
Exercise
• Write a function that takes a user's full name and returns:
* The name in all caps
* The reversed name
* The first name only using
---
#PHP #Strings #PHPTutorial #StringFunctions #WebDevelopment
https://t.iss.one/Ebooks2023
---
1. Introduction to Strings in PHP
• A string is a sequence of characters used to store and manipulate text.
• Strings can be defined using single quotes (`'`) or double quotes (`"`):
$name = "Ali";
$message = 'Welcome to PHP!';
• Double quotes allow variable interpolation, single quotes do not.
---
2. Concatenating Strings
• Use the dot (
.) operator to join strings.$first = "Hello";
$second = "World";
echo $first . " " . $second; // Output: Hello World
---
3. Common String Functions in PHP
Here are essential functions to manipulate strings:
•
strlen($str) – Returns the length of the string.echo strlen("PHP"); // Output: 3•
strtoupper($str) – Converts all letters to uppercase.•
strtolower($str) – Converts all letters to lowercase.•
ucfirst($str) – Capitalizes the first letter.•
ucwords($str) – Capitalizes first letter of each word.•
strrev($str) – Reverses the string.---
4. Searching Within Strings
•
strpos($str, $search) – Finds the position of first occurrence of a substring.echo strpos("Hello PHP", "PHP"); // Output: 6•
str_contains($str, $search) – Checks if substring exists (PHP 8+).---
5. Extracting Substrings
•
substr($str, $start, $length) – Extracts part of a string.$text = "Welcome to PHP";
echo substr($text, 0, 7); // Output: Welcome
---
6. Replacing Text in Strings
•
str_replace($search, $replace, $subject) – Replaces all occurrences.echo str_replace("PHP", "Laravel", "Welcome to PHP"); // Output: Welcome to Laravel---
7. Trimming and Cleaning Strings
•
trim($str) – Removes whitespace from both ends.•
ltrim($str) – From the left side only.•
rtrim($str) – From the right side only.---
8. String Comparison
•
strcmp($str1, $str2) – Returns 0 if both strings are equal.•
strcasecmp($str1, $str2) – Case-insensitive comparison.---
9. Escaping Characters
• Use backslash (
\) to escape quotes:echo "He said: \"Hello!\"";
---
10. Summary
• Strings are core to user interaction and text processing.
• PHP offers powerful built-in functions to manipulate strings efficiently.
---
Exercise
• Write a function that takes a user's full name and returns:
* The name in all caps
* The reversed name
* The first name only using
substr() and strpos()---
#PHP #Strings #PHPTutorial #StringFunctions #WebDevelopment
https://t.iss.one/Ebooks2023
❤3
Topic: PHP Basics – Part 10 of 10: Connecting PHP with MySQL Database (CRUD Operations)
---
1. Introduction
PHP works seamlessly with MySQL, one of the most popular open-source relational databases. In this lesson, we’ll learn how to:
• Connect to a MySQL database
• Perform basic CRUD operations (Create, Read, Update, Delete)
We’ll use the
---
### 2. Setting Up the Database
Suppose we have a MySQL database named
---
### 3. Connecting PHP to MySQL
---
### 4. Create (INSERT)
---
### 5. Read (SELECT)
---
### 6. Update (UPDATE)
---
### 7. Delete (DELETE)
---
### 8. Prepared Statements (Best Practice for Security)
Prevent SQL injection by using prepared statements:
---
### 9. Closing the Connection
---
### 10. Summary
• PHP connects easily with MySQL using
• Perform CRUD operations for full database interaction.
• Always use prepared statements for secure data handling.
---
### Exercise
1. Create a PHP page to add a student using a form.
2. Display all students in a table.
3. Add edit and delete buttons next to each student.
4. Implement all CRUD operations using
---
#PHP #MySQL #CRUD #PHPTutorial #WebDevelopment #Database
https://t.iss.one/Ebooks2023
---
1. Introduction
PHP works seamlessly with MySQL, one of the most popular open-source relational databases. In this lesson, we’ll learn how to:
• Connect to a MySQL database
• Perform basic CRUD operations (Create, Read, Update, Delete)
We’ll use the
mysqli extension (object-oriented style) in this tutorial.---
### 2. Setting Up the Database
Suppose we have a MySQL database named
school with a table students:CREATE DATABASE school;
USE school;
CREATE TABLE students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100),
age INT
);
---
### 3. Connecting PHP to MySQL
<?php
$host = "localhost";
$user = "root";
$password = "";
$db = "school";
$conn = new mysqli($host, $user, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
?>
---
### 4. Create (INSERT)
<?php
$sql = "INSERT INTO students (name, email, age) VALUES ('Ali', '[email protected]', 22)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully.";
} else {
echo "Error: " . $conn->error;
}
?>
---
### 5. Read (SELECT)
<?php
$sql = "SELECT * FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " | Name: " . $row["name"]. " | Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
?>
---
### 6. Update (UPDATE)
<?php
$sql = "UPDATE students SET age = 23 WHERE name = 'Ali'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully.";
} else {
echo "Error updating record: " . $conn->error;
}
?>
---
### 7. Delete (DELETE)
<?php
$sql = "DELETE FROM students WHERE name = 'Ali'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . $conn->error;
}
?>
---
### 8. Prepared Statements (Best Practice for Security)
Prevent SQL injection by using prepared statements:
<?php
$stmt = $conn->prepare("INSERT INTO students (name, email, age) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $name, $email, $age);
$name = "Sara";
$email = "[email protected]";
$age = 20;
$stmt->execute();
echo "Data inserted securely.";
$stmt->close();
?>
---
### 9. Closing the Connection
$conn->close();
---
### 10. Summary
• PHP connects easily with MySQL using
mysqli.• Perform CRUD operations for full database interaction.
• Always use prepared statements for secure data handling.
---
### Exercise
1. Create a PHP page to add a student using a form.
2. Display all students in a table.
3. Add edit and delete buttons next to each student.
4. Implement all CRUD operations using
mysqli.---
#PHP #MySQL #CRUD #PHPTutorial #WebDevelopment #Database
https://t.iss.one/Ebooks2023
❤2
Topic: 33 Important PHP Questions for Beginners (with Answers)
---
1. What does PHP stand for?
Answer: PHP stands for *PHP: Hypertext Preprocessor*.
---
2. What is PHP used for?
Answer: PHP is used to create dynamic web pages and server-side applications.
---
3. How do you declare a variable in PHP?
Answer: Variables in PHP start with a
---
4. Is PHP case-sensitive?
Answer: Function names are not case-sensitive, but variables are.
---
5. What is the difference between `echo` and `print`?
Answer: Both output data.
---
6. How do you write comments in PHP?
Answer:
---
7. How do you create a function in PHP?
Answer:
---
8. What are the different data types in PHP?
Answer: String, Integer, Float, Boolean, Array, Object, NULL, Resource.
---
9. How can you connect PHP to a MySQL database?
Answer: Using
---
10. What is a session in PHP?
Answer: A session stores user data on the server across multiple pages.
---
11. How do you start a session?
Answer:
---
12. How do you set a cookie in PHP?
Answer:
---
13. How can you check if a variable is set?
Answer:
---
14. What is `$_POST` and `$_GET`?
Answer: Superglobals used to collect form data sent via POST or GET methods.
---
15. How do you include a file in PHP?
Answer:
---
16. Difference between `include` and `require`?
Answer:
---
17. How do you loop through an array?
Answer:
---
18. How to define an associative array?
Answer:
---
19. What are superglobals in PHP?
Answer: Predefined variables like
---
20. What is the use of `isset()` and `empty()`?
Answer:
•
•
---
21. How to check if a file exists?
Answer:
---
22. How to upload a file in PHP?
Answer: Use
---
23. What is a constructor in PHP?
Answer: A special method
---
24. What is OOP in PHP?
Answer: Object-Oriented Programming using classes, objects, inheritance, etc.
---
25. What are magic constants in PHP?
Answer: Built-in constants like
---
26. How to handle errors in PHP?
Answer: Using
---
27. What is the difference between `==` and `===`?
Answer:
•
•
---
28. How to redirect a user in PHP?
Answer:
---
29. How to sanitize user input?
Answer: Use
---
30. How do you close a MySQL connection?
Answer: $conn->close();
---
31. What is `explode()` in PHP?
Answer: Splits a string into an array using a delimiter.
explode(",", "one,two,three");
---
32. How do you hash passwords in PHP?
Answer:
password_hash("123456", PASSWORD_DEFAULT);
---
33. What version of PHP should you use?
Answer: Always use the latest stable version (e.g., PHP 8.2+) for performance and security.
---
#PHP #InterviewQuestions #Beginners #PHPTutorial #WebDevelopment
https://t.iss.one/Ebooks2023
---
1. What does PHP stand for?
Answer: PHP stands for *PHP: Hypertext Preprocessor*.
---
2. What is PHP used for?
Answer: PHP is used to create dynamic web pages and server-side applications.
---
3. How do you declare a variable in PHP?
Answer: Variables in PHP start with a
$ sign, e.g., $name = "Ali";.---
4. Is PHP case-sensitive?
Answer: Function names are not case-sensitive, but variables are.
---
5. What is the difference between `echo` and `print`?
Answer: Both output data.
echo is faster and can output multiple strings, while print returns 1.---
6. How do you write comments in PHP?
Answer:
// Single line
# Another single line
/* Multi-line */
---
7. How do you create a function in PHP?
Answer:
function greet() {
echo "Hello!";
}---
8. What are the different data types in PHP?
Answer: String, Integer, Float, Boolean, Array, Object, NULL, Resource.
---
9. How can you connect PHP to a MySQL database?
Answer: Using
mysqli_connect() or new mysqli().---
10. What is a session in PHP?
Answer: A session stores user data on the server across multiple pages.
---
11. How do you start a session?
Answer:
session_start();---
12. How do you set a cookie in PHP?
Answer:
setcookie("name", "value", time()+3600);---
13. How can you check if a variable is set?
Answer:
isset($variable);---
14. What is `$_POST` and `$_GET`?
Answer: Superglobals used to collect form data sent via POST or GET methods.
---
15. How do you include a file in PHP?
Answer:
include "file.php";
require "file.php";
---
16. Difference between `include` and `require`?
Answer:
require will cause a fatal error if the file is missing; include will only raise a warning.---
17. How do you loop through an array?
Answer:
foreach ($array as $value) {
echo $value;
}---
18. How to define an associative array?
Answer:
$person = ["name" => "Ali", "age" => 25];
---
19. What are superglobals in PHP?
Answer: Predefined variables like
$_GET, $_POST, $_SESSION, etc.---
20. What is the use of `isset()` and `empty()`?
Answer:
•
isset() checks if a variable is set and not null.•
empty() checks if a variable is empty.---
21. How to check if a file exists?
Answer:
file_exists("filename.txt");---
22. How to upload a file in PHP?
Answer: Use
$_FILES and move_uploaded_file().---
23. What is a constructor in PHP?
Answer: A special method
__construct() that runs when an object is created.---
24. What is OOP in PHP?
Answer: Object-Oriented Programming using classes, objects, inheritance, etc.
---
25. What are magic constants in PHP?
Answer: Built-in constants like
__LINE__, __FILE__, __DIR__.---
26. How to handle errors in PHP?
Answer: Using
try...catch, error_reporting(), and set_error_handler().---
27. What is the difference between `==` and `===`?
Answer:
•
== checks value only.•
=== checks value and type.---
28. How to redirect a user in PHP?
Answer:
header("Location: page.php");---
29. How to sanitize user input?
Answer: Use
htmlspecialchars(), strip_tags(), trim().---
30. How do you close a MySQL connection?
Answer: $conn->close();
---
31. What is `explode()` in PHP?
Answer: Splits a string into an array using a delimiter.
explode(",", "one,two,three");
---
32. How do you hash passwords in PHP?
Answer:
password_hash("123456", PASSWORD_DEFAULT);
---
33. What version of PHP should you use?
Answer: Always use the latest stable version (e.g., PHP 8.2+) for performance and security.
---
#PHP #InterviewQuestions #Beginners #PHPTutorial #WebDevelopment
https://t.iss.one/Ebooks2023
❤5
# 📚 Connecting MySQL with Popular Web Frameworks
#MySQL #WebDev #Frameworks #Django #Laravel #Flask #ASPNET #Spring
MySQL is widely used in web development. Here’s how to connect it with top web frameworks.
---
## 🔹 1. Django (Python) with MySQL
#Django #Python #MySQL
Use
1️⃣ Install the driver:
2️⃣ Update `settings.py`:
3️⃣ If using `pymysql`, add this to `__init__.py`:
---
## 🔹 2. Laravel (PHP) with MySQL
#Laravel #PHP #MySQL
Laravel has built-in MySQL support.
1️⃣ Configure `.env`:
2️⃣ Run migrations:
---
## 🔹 3. Flask (Python) with MySQL
#Flask #Python #MySQL
Use
### Option 1: Using `flask-mysqldb`
### Option 2: Using SQLAlchemy
---
## 🔹 4. ASP.NET Core with MySQL
#ASPNET #CSharp #MySQL
Use
1️⃣ Install the package:
2️⃣ Configure in `Startup.cs`:
---
## 🔹 5. Spring Boot (Java) with MySQL
#SpringBoot #Java #MySQL
1️⃣ Add dependency in `pom.xml`:
2️⃣ Configure `application.properties`:
3️⃣ JPA Entity Example:
---
## 🔹 6. Express.js (Node.js) with MySQL
#Express #NodeJS #MySQL
Use
### Option 1: Using `mysql2`
### Option 2: Using Sequelize (ORM)
---
### 📌 Conclusion
MySQL integrates smoothly with all major web frameworks. Choose the right approach based on your stack!
#WebDevelopment #Backend #MySQLIntegration
🚀 Happy Coding! 🚀
#MySQL #WebDev #Frameworks #Django #Laravel #Flask #ASPNET #Spring
MySQL is widely used in web development. Here’s how to connect it with top web frameworks.
---
## 🔹 1. Django (Python) with MySQL
#Django #Python #MySQL
Use
mysqlclient or pymysql. 1️⃣ Install the driver:
pip install mysqlclient # Recommended
# OR
pip install pymysql
2️⃣ Update `settings.py`:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_database',
'USER': 'your_username',
'PASSWORD': 'your_password',
'HOST': 'localhost',
'PORT': '3306',
}
}3️⃣ If using `pymysql`, add this to `__init__.py`:
import pymysql
pymysql.install_as_MySQLdb()
---
## 🔹 2. Laravel (PHP) with MySQL
#Laravel #PHP #MySQL
Laravel has built-in MySQL support.
1️⃣ Configure `.env`:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
2️⃣ Run migrations:
php artisan migrate
---
## 🔹 3. Flask (Python) with MySQL
#Flask #Python #MySQL
Use
flask-mysqldb or SQLAlchemy. ### Option 1: Using `flask-mysqldb`
from flask import Flask
from flask_mysqldb import MySQL
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'your_username'
app.config['MYSQL_PASSWORD'] = 'your_password'
app.config['MYSQL_DB'] = 'your_database'
mysql = MySQL(app)
@app.route('/')
def index():
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM your_table")
data = cur.fetchall()
return str(data)
### Option 2: Using SQLAlchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/your_database'
db = SQLAlchemy(app)
---
## 🔹 4. ASP.NET Core with MySQL
#ASPNET #CSharp #MySQL
Use
Pomelo.EntityFrameworkCore.MySql. 1️⃣ Install the package:
dotnet add package Pomelo.EntityFrameworkCore.MySql
2️⃣ Configure in `Startup.cs`:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(
"server=localhost;database=your_database;user=your_username;password=your_password",
ServerVersion.AutoDetect("server=localhost;database=your_database")
)
);
---
## 🔹 5. Spring Boot (Java) with MySQL
#SpringBoot #Java #MySQL
1️⃣ Add dependency in `pom.xml`:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
2️⃣ Configure `application.properties`:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3️⃣ JPA Entity Example:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// Getters & Setters
}
---
## 🔹 6. Express.js (Node.js) with MySQL
#Express #NodeJS #MySQL
Use
mysql2 or sequelize. ### Option 1: Using `mysql2`
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.query('SELECT * FROM users', (err, results) => {
console.log(results);
});### Option 2: Using Sequelize (ORM)
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('your_database', 'your_username', 'your_password', {
host: 'localhost',
dialect: 'mysql'
});
// Test connection
sequelize.authenticate()
.then(() => console.log('Connected!'))
.catch(err => console.error('Error:', err));---
### 📌 Conclusion
MySQL integrates smoothly with all major web frameworks. Choose the right approach based on your stack!
#WebDevelopment #Backend #MySQLIntegration
Please open Telegram to view this post
VIEW IN TELEGRAM
❤1
## 🔹 Best Practices for Beginners
1. Use `const` by default,
2. Always declare variables before use
3. Use strict equality (`===`) instead of
4. Name variables meaningfully (e.g.,
5. Comment your code for complex logic
---
### 📌 What's Next?
In Part 2, we'll cover:
➡️ Conditionals (if/else, switch)
➡️ Loops (for, while)
➡️ Functions
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create variables for your name, age, and country
2. Calculate the area of a circle (PI * r²)
3. Try different type conversions
1. Use `const` by default,
let when needed, avoid var 2. Always declare variables before use
3. Use strict equality (`===`) instead of
== 4. Name variables meaningfully (e.g.,
userAge not x) 5. Comment your code for complex logic
---
### 📌 What's Next?
In Part 2, we'll cover:
➡️ Conditionals (if/else, switch)
➡️ Loops (for, while)
➡️ Functions
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create variables for your name, age, and country
2. Calculate the area of a circle (PI * r²)
3. Try different type conversions
❤3
# 📚 JavaScript Tutorial - Part 2/10: Control Flow & Functions
#JavaScript #WebDev #Programming #Beginners
Welcome to Part 2 of our JavaScript series! Today we'll master decision-making and functions - the building blocks of programming logic.
---
## 🔹 Conditional Statements
Control program flow based on conditions.
### 1. if-else Statement
### 2. Ternary Operator (Shorthand if-else)
### 3. switch-case Statement
---
## 🔹 Loops
Execute code repeatedly.
### 1. for Loop
### 2. while Loop
### 3. do-while Loop
### 4. for...of Loop (Arrays)
### 5. for...in Loop (Objects)
---
## 🔹 Functions
Reusable blocks of code.
### 1. Function Declaration
### 2. Function Expression
### 3. Arrow Functions (ES6+)
### 4. Default Parameters
### 5. Rest Parameters
---
## 🔹 Practical Example: Grade Calculator
---
## 🔹 Scope in JavaScript
### 1. Global Scope
### 2. Function Scope (var)
### 3. Block Scope (let/const)
---
## 🔹 Error Handling
### 1. try-catch-finally
### 2. Throwing Custom Errors
---
## 🔹 Best Practices
1. Use strict equality (
2. Prefer const/let over var
3. Keep functions small/single-purpose
4. Always handle errors
5. Use descriptive names for functions/variables
---
### 📌 What's Next?
In Part 3, we'll cover:
➡️ Arrays & Array Methods
➡️ Objects & JSON
➡️ Destructuring
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create a function to check if a number is even/odd
2. Write a loop that prints prime numbers up to 20
3. Make a temperature converter function (Celsius ↔️ Fahrenheit)
#JavaScript #WebDev #Programming #Beginners
Welcome to Part 2 of our JavaScript series! Today we'll master decision-making and functions - the building blocks of programming logic.
---
## 🔹 Conditional Statements
Control program flow based on conditions.
### 1. if-else Statement
let age = 18;
if (age >= 18) {
console.log("You're an adult");
} else {
console.log("You're a minor");
}
### 2. Ternary Operator (Shorthand if-else)
let message = (age >= 18) ? "Adult" : "Minor";
console.log(message);
### 3. switch-case Statement
let day = 3;
let dayName;
switch(day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
default: dayName = "Unknown";
}
console.log(dayName); // "Wednesday"
---
## 🔹 Loops
Execute code repeatedly.
### 1. for Loop
for (let i = 1; i <= 5; i++) {
console.log(`Count: ${i}`);
}
// Output: 1, 2, 3, 4, 5### 2. while Loop
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
### 3. do-while Loop
let x = 1;
do {
console.log(x);
x++;
} while (x <= 5);
### 4. for...of Loop (Arrays)
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
### 5. for...in Loop (Objects)
const person = {name: "Ali", age: 25};
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}---
## 🔹 Functions
Reusable blocks of code.
### 1. Function Declaration
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Ali")); // "Hello, Ali!"### 2. Function Expression
const square = function(x) {
return x * x;
};
console.log(square(5)); // 25### 3. Arrow Functions (ES6+)
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
### 4. Default Parameters
function createUser(name, role = "user") {
console.log(`${name} is a ${role}`);
}
createUser("Ali"); // "Ali is a user"### 5. Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6---
## 🔹 Practical Example: Grade Calculator
function calculateGrade(score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 70) return "C";
else return "F";
}
const studentScore = 85;
console.log(`Grade: ${calculateGrade(studentScore)}`); // "Grade: B"---
## 🔹 Scope in JavaScript
### 1. Global Scope
const globalVar = "I'm global";
function test() {
console.log(globalVar); // Accessible
}
### 2. Function Scope (var)
function test() {
var functionVar = "I'm function-scoped";
}
console.log(functionVar); // Error: Not accessible### 3. Block Scope (let/const)
if (true) {
let blockVar = "I'm block-scoped";
}
console.log(blockVar); // Error: Not accessible---
## 🔹 Error Handling
### 1. try-catch-finally
try {
// Risky code
nonExistentFunction();
} catch (error) {
console.log("Error occurred:", error.message);
} finally {
console.log("This always executes");
}### 2. Throwing Custom Errors
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;
}---
## 🔹 Best Practices
1. Use strict equality (
===) over == 2. Prefer const/let over var
3. Keep functions small/single-purpose
4. Always handle errors
5. Use descriptive names for functions/variables
---
### 📌 What's Next?
In Part 3, we'll cover:
➡️ Arrays & Array Methods
➡️ Objects & JSON
➡️ Destructuring
#LearnJavaScript #CodingBasics #WebDevelopment 🚀
Practice Exercise:
1. Create a function to check if a number is even/odd
2. Write a loop that prints prime numbers up to 20
3. Make a temperature converter function (Celsius ↔️ Fahrenheit)
❤5
## 🔹 Practical Example: Todo List Manager
---
## 🔹 Best Practices
1. Use `const` for arrays/objects (the reference is constant)
2. Prefer functional methods (
3. Validate JSON before parsing
4. Use descriptive property names
5. Destructure deeply nested objects carefully
---
### 📌 What's Next?
In Part 4, we'll cover:
➡️ DOM Manipulation
➡️ Event Handling
➡️ Form Validation
#JavaScript #WebDevelopment #Programming 🚀
Practice Exercise:
1. Create an array of products (name, price, inStock)
2. Write functions to:
- Filter out-of-stock products
- Calculate total inventory value
- Sort by price (high-to-low)
3. Convert your array to JSON and back
const todoList = [
{id: 1, task: 'Buy groceries', completed: false},
{id: 2, task: 'Do laundry', completed: true}
];
// Add new task
function addTask(task) {
const newTask = {
id: todoList.length + 1,
task,
completed: false
};
todoList.push(newTask);
}
// Mark task as complete
function completeTask(id) {
const task = todoList.find(item => item.id === id);
if (task) task.completed = true;
}
// Get pending tasks
function getPendingTasks() {
return todoList.filter(task => !task.completed);
}
---
## 🔹 Best Practices
1. Use `const` for arrays/objects (the reference is constant)
2. Prefer functional methods (
map, filter) over loops3. Validate JSON before parsing
4. Use descriptive property names
5. Destructure deeply nested objects carefully
---
### 📌 What's Next?
In Part 4, we'll cover:
➡️ DOM Manipulation
➡️ Event Handling
➡️ Form Validation
#JavaScript #WebDevelopment #Programming 🚀
Practice Exercise:
1. Create an array of products (name, price, inStock)
2. Write functions to:
- Filter out-of-stock products
- Calculate total inventory value
- Sort by price (high-to-low)
3. Convert your array to JSON and back
## 🔹 Practical Example: Interactive Todo List
---
## 🔹 Working with Forms
### 1. Accessing Form Data
### 2. Form Validation
---
## 🔹 Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### 📌 What's Next?
In Part 5, we'll cover:
➡️ Asynchronous JavaScript
➡️ Callbacks, Promises, Async/Await
➡️ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment 🚀
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
// DOM Elements
const form = document.querySelector('#todo-form');
const input = document.querySelector('#todo-input');
const list = document.querySelector('#todo-list');
// Add new todo
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value.trim() === '') return;
const todoText = input.value;
const li = document.createElement('li');
li.innerHTML = `
${todoText}
<button class="delete-btn">X</button>
`;
list.appendChild(li);
input.value = '';
});
// Delete todo (using delegation)
list.addEventListener('click', function(e) {
if (e.target.classList.contains('delete-btn')) {
e.target.parentElement.remove();
}
});
---
## 🔹 Working with Forms
### 1. Accessing Form Data
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault();
// Get form values
const username = form.elements['username'].value;
const password = form.elements['password'].value;
console.log({ username, password });
});### 2. Form Validation
function validateForm() {
const email = document.getElementById('email').value;
if (!email.includes('@')) {
alert('Please enter a valid email');
return false;
}
return true;
}---
## 🔹 Best Practices
1. Cache DOM queries (store in variables)
2. Use event delegation for dynamic elements
3. Always prevent default on form submissions
4. Separate JS from HTML (avoid inline handlers)
5. Throttle rapid-fire events (resize, scroll)
---
### 📌 What's Next?
In Part 5, we'll cover:
➡️ Asynchronous JavaScript
➡️ Callbacks, Promises, Async/Await
➡️ Fetch API & AJAX
#JavaScript #FrontEnd #WebDevelopment 🚀
Practice Exercise:
1. Create a color picker that changes background color
2. Build a counter with + and - buttons
3. Make a dropdown menu that shows/hides on click
❤2
Data Analytics
## 🔹 Practical Example: Interactive Todo List // DOM Elements const form = document.querySelector('#todo-form'); const input = document.querySelector('#todo-input'); const list = document.querySelector('#todo-list'); // Add new todo form.addEventListener('submit'…
function oldFetch(url, callback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = () => {
if (xhr.status === 200) {
callback(JSON.parse(xhr.response));
} else {
callback(null, xhr.status);
}
};
xhr.send();
}---
## 🔹 Best Practices
1. Always handle errors in promises/async functions
2. Use async/await for better readability
3. Cancel requests when no longer needed (AbortController)
4. Throttle rapid API calls (debounce input handlers)
5. Cache responses when appropriate
---
### 📌 What's Next?
In Part 6, we'll cover:
➡️ JavaScript Modules
➡️ ES6+ Features
➡️ Tooling (Babel, Webpack, npm)
#JavaScript #AsyncProgramming #WebDevelopment 🚀
Practice Exercise:
1. Fetch GitHub user data (https://api.github.com/users/username)
2. Create a function that fetches multiple Pokémon in parallel
3. Build a retry mechanism for failed requests (max 3 attempts)