Essential Linux Commands for Git Terminal

πŸ“ 1. File & Directory Navigation

1. pwd

Description: Shows the current working directory path.

pwd

2. ls

Description: Lists files and directories.

ls
ls -la # detailed list including hidden files

3. cd

Description: Changes directory.

cd project-folder
cd .. # move up one directory
cd ~ # go to home directory

πŸ“‚ 2. File & Directory Management

4. mkdir

Description: Creates a new directory.

mkdir my-repo

5. rmdir

Description: Removes an empty directory.

rmdir my-repo

6. rm

Description: Deletes files or directories.

rm file.txt
rm -r folder/ # remove directory recursively

7. cp

Description: Copies files or directories.

cp file.txt backup.txt
cp -r folder/ new-folder/

8. mv

Description: Moves or renames files.

mv file.txt newname.txt
mv file.txt folder/

πŸ“ 3. File Viewing & Editing

9. cat

Description: Displays file content.

cat README.md

10. less

Description: Views large files page by page.

less README.md

11. nano

Description: Simple terminal text editor.

nano file.txt

12. vim

Description: Advanced text editor.

vim file.txt

πŸ” 4. Search & Filtering

13. grep

Description: Searches text in files.

grep "function" file.js

14. find

Description: Finds files/directories.

find . -name "index.js"

βš™οΈ 5. Permissions & Ownership

15. chmod

Description: Changes file permissions.

chmod 755 script.sh

16. chown

Description: Changes file ownership.

chown user:user file.txt

🌐 6. Networking (Useful for Git)

17. ssh

Description: Connects securely to remote servers (used for GitHub SSH).

ssh -T git@github.com

18. curl

Description: Transfers data from URLs.

curl https://api.github.com

🧰 7. Archive & Compression

19. tar

Description: Creates/extracts archives.

tar -cvf project.tar folder/
tar -xvf project.tar

20. zip / unzip

Description: Compresses and extracts zip files.

zip -r project.zip folder/
unzip project.zip

πŸ§ͺ 8. System & Process Commands

21. clear

Description: Clears the terminal screen.

clear

22. history

Description: Shows previously used commands.

history

23. top

Description: Displays running processes.

top

πŸ”„ How These Help in Git Workflow

When working with Git, these Linux commands help you:

  • Navigate to repositories (cd, ls)
  • Create/manage project files (mkdir, rm, cp)
  • Edit code before committing (nano, vim)
  • Inspect changes (cat, less)
  • Search code (grep, find)
  • Handle SSH authentication (ssh)

πŸš€ Example Git Workflow with Linux Commands

mkdir my-project
cd my-project
git inittouch README.md
nano README.mdgit add .
git commit -m "Initial commit"

JavaScript String Fundamentals

A string in JavaScript is a sequence of characters used to represent text.

βœ… Ways to create strings

let str1 = "Hello";
let str2 = 'World';
let str3 = `Hello World`; // Template literal

String Methods

πŸ”Ή 1. length

Description: Returns the number of characters in a string.

let str = "Hello";
console.log(str.length); // 5

πŸ”Ή 2. toUpperCase()

Description: Converts all characters to uppercase.

"hello".toUpperCase(); // "HELLO"

πŸ”Ή 3. toLowerCase()

Description: Converts all characters to lowercase.

"HELLO".toLowerCase(); // "hello"

πŸ”Ή 4. trim()

Description: Removes whitespace from both ends.

"  hi  ".trim(); // "hi"

πŸ”Ή 5. trimStart() / trimEnd()

Description: Removes whitespace from start or end only.

"  hi".trimStart(); // "hi"
"hi ".trimEnd(); // "hi"

πŸ”Ή 6. includes(substring)

Description: Checks if string contains a substring β†’ returns true/false.

"JavaScript".includes("Script"); // true

πŸ”Ή 7. startsWith()

Description: Checks if string starts with given value.

"Hello".startsWith("He"); // true

πŸ”Ή 8. endsWith()

Description: Checks if string ends with given value.

"Hello".endsWith("lo"); // true

πŸ”Ή 9. indexOf()

Description: Returns first index of substring, or -1 if not found.

"Hello".indexOf("l"); // 2

πŸ”Ή 10. lastIndexOf()

Description: Returns last occurrence index.

"Hello".lastIndexOf("l"); // 3

πŸ”Ή 11. slice(start, end)

Description: Extracts part of string (supports negative index).

"JavaScript".slice(0, 4); // "Java"
"Hello".slice(-2); // "lo"

πŸ”Ή 12. substring(start, end)

Description: Similar to slice() but does not accept negative index.

"JavaScript".substring(4, 10); // "Script"

πŸ”Ή 13. substr(start, length) ⚠️ Deprecated

Description: Extracts substring using length (not recommended now).

"Hello".substr(1, 3); // "ell"

πŸ”Ή 14. replace(search, value)

Description: Replaces first match.

"Hello World".replace("World", "JS"); // "Hello JS"

πŸ”Ή 15. replaceAll()

Description: Replaces all occurrences.

"a-b-c".replaceAll("-", ","); // "a,b,c"

πŸ”Ή 16. split(separator)

Description: Converts string into array.

"a,b,c".split(","); // ["a", "b", "c"]

πŸ”Ή 17. concat()

Description: Joins two or more strings.

"Hello".concat(" ", "World"); // "Hello World"

πŸ”Ή 18. charAt(index)

Description: Returns character at given index.

"Hello".charAt(1); // "e"

πŸ”Ή 19. charCodeAt(index)

Description: Returns Unicode value of character.

"A".charCodeAt(0); // 65

πŸ”Ή 20. repeat(n)

Description: Repeats string n times.

"Hi ".repeat(3); // "Hi Hi Hi "

πŸ”Ή 21. padStart(length, char)

Description: Pads string from start.

"5".padStart(3, "0"); // "005"

πŸ”Ή 22. padEnd(length, char)

Description: Pads string from end.

"5".padEnd(3, "0"); // "500"

πŸ”Ή 23. match(regex)

Description: Returns matches based on regex.

"abc123".match(/\d+/); // ["123"]

πŸ”Ή 24. matchAll(regex)

Description: Returns all matches (iterator).

[..."a1b2".matchAll(/\d/g)]; // ["1", "2"]

πŸ”Ή 25. search(regex)

Description: Returns index of first match.

"hello123".search(/\d/); // 5

πŸ”Ή 26. localeCompare()

Description: Compares two strings (useful for sorting).

"a".localeCompare("b"); // -1

πŸ”Ή 27. normalize()

Description: Normalizes Unicode characters.

"Γ©".normalize(); 

πŸ”Ή 28. valueOf()

Description: Returns primitive string value.

let str = new String("hello");
str.valueOf(); // "hello"

πŸ”Ή 29. toString()

Description: Converts object to string.

let str = new String("hello");
str.toString(); // "hello"

πŸ”Ή 30. Template Literals (`)

Description: Allows interpolation and multi-line strings.

let name = "John";
console.log(`Hello ${name}`);

⚑ Quick Categorization

πŸ” Search Methods

  • includes(), indexOf(), search()

βœ‚οΈ Extract Methods

  • slice(), substring(), substr()

πŸ”„ Modify Methods

  • replace(), replaceAll(), trim()

πŸ”§ Utility Methods

  • split(), concat(), repeat()

πŸ”‘ Case Methods

  • toUpperCase(), toLowerCase()

πŸ”₯ 20 JavaScript String Programs (with Solutions)


βœ… 1. Reverse a string

let str = "hello";
let reversed = str.split("").reverse().join("");
console.log(reversed);

βœ… 2. Check palindrome

let str = "madam";
let result = str === str.split("").reverse().join("");
console.log(result);

βœ… 3. Count vowels

let str = "hello";
let count = str.match(/[aeiou]/gi)?.length || 0;
console.log(count);

βœ… 4. Count consonants

let str = "hello";
let count = str.match(/[^aeiou]/gi).length;
console.log(count);

βœ… 5. Remove spaces

let str = "h e l l o";
console.log(str.replaceAll(" ", ""));

βœ… 6. Convert first letter to uppercase

let str = "hello";
console.log(str.charAt(0).toUpperCase() + str.slice(1));

βœ… 7. Find longest word

let str = "I love JavaScript programming";
let words = str.split(" ");
let longest = words.reduce((a, b) => a.length > b.length ? a : b);
console.log(longest);

βœ… 8. Count words

let str = "Hello world JS";
console.log(str.split(" ").length);

βœ… 9. Check substring exists

let str = "JavaScript";
console.log(str.includes("Script"));

βœ… 10. Replace all vowels with *

let str = "hello";
console.log(str.replace(/[aeiou]/gi, "*"));

βœ… 11. Convert string to array

let str = "hello";
console.log(str.split(""));

βœ… 12. Remove duplicate characters

let str = "aabbcc";
let unique = [...new Set(str)].join("");
console.log(unique);

βœ… 13. Count character frequency

let str = "hello";
let obj = {};
for (let ch of str) {
obj[ch] = (obj[ch] || 0) + 1;
}
console.log(obj);

βœ… 14. Check anagram

let a = "listen";
let b = "silent";let result = a.split("").sort().join("") === b.split("").sort().join("");
console.log(result);

βœ… 15. Capitalize each word

let str = "hello world";
let result = str.split(" ").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
console.log(result);

βœ… 16. Extract numbers from string

let str = "abc123xyz";
console.log(str.match(/\d+/)[0]);

βœ… 17. Check if string contains only digits

let str = "12345";
console.log(/^\d+$/.test(str));

βœ… 18. Repeat string N times

let str = "hi";
console.log(str.repeat(3));

βœ… 19. Truncate string

let str = "JavaScript";
console.log(str.slice(0, 4));

βœ… 20. Convert string to title case

let str = "javascript is fun";
let result = str.split(" ")
.map(w => w[0].toUpperCase() + w.slice(1))
.join(" ");
console.log(result);

Github Interview Questions And Answers

1. What is GitHub? How is it different from Git?

πŸ‘‰ Answer:

  • Git is a distributed version control system used to track code changes.
  • GitHub is a cloud-based platform that hosts Git repositories and adds collaboration features.

πŸ‘‰ Use Case:
In a team project, developers use Git locally and push code to GitHub for collaboration, reviews, and CI/CD.


2. What is a Repository?

πŸ‘‰ Answer:
A repository (repo) is a storage space for your project that contains code, files, and version history.

πŸ‘‰ Use Case:
You create a repo for a Playwright automation project where all test scripts, configs, and reports are stored.


3. What is the difference between Fork and Clone?

πŸ‘‰ Answer:

  • Fork: Copy of someone else’s repo into your GitHub account.
  • Clone: Copy of a repo to your local machine.

πŸ‘‰ Use Case:

  • Fork: Contributing to open-source.
  • Clone: Working on your team project locally.

4. What is a Branch?

πŸ‘‰ Answer:
A branch is a separate line of development.

πŸ‘‰ Use Case:
You create:

  • main β†’ production code
  • feature/login-test β†’ new feature work

5. What is a Pull Request (PR)?

πŸ‘‰ Answer:
A PR is a request to merge changes from one branch to another.

πŸ‘‰ Use Case:
QA automation engineer raises a PR after adding test cases β†’ Developer reviews β†’ merges into main.


6. What is Merge Conflict?

πŸ‘‰ Answer:
Occurs when Git cannot automatically merge changes.

πŸ‘‰ Use Case:
Two developers modify the same file β†’ conflict β†’ manually resolved before merge.


7. What is GitHub Actions?

πŸ‘‰ Answer:
A CI/CD tool in GitHub used to automate workflows.

πŸ‘‰ Use Case:

  • Run Playwright tests automatically on every PR
  • Deploy app after merge

8. What is .gitignore?

πŸ‘‰ Answer:
A file that specifies which files Git should ignore.

πŸ‘‰ Use Case:
Ignore:

  • node_modules/
  • test-results/
  • .env

9. What is Git Workflow (Branching Strategy)?

πŸ‘‰ Answer:
A process defining how teams use branches.

πŸ‘‰ Common strategies:

  • Git Flow
  • Feature Branch Workflow

πŸ‘‰ Use Case:

  • Create feature branch
  • Push code
  • Raise PR
  • Review β†’ Merge

10. What is Staging in Git?

πŸ‘‰ Answer:
Intermediate area before committing changes.

πŸ‘‰ Commands:

git add .
git commit -m "message"

πŸ‘‰ Use Case:
You selectively add only required files before committing.


11. Difference between Commit and Push?

πŸ‘‰ Answer:

  • Commit: Save changes locally
  • Push: Upload changes to GitHub

πŸ‘‰ Use Case:
You commit multiple times locally β†’ push once after testing.


12. What is Rebase vs Merge?

πŸ‘‰ Answer:

  • Merge: Keeps history (creates merge commit)
  • Rebase: Rewrites history (linear)

πŸ‘‰ Use Case:
Rebase keeps clean commit history before merging feature branch.


13. What is Tag in Git?

πŸ‘‰ Answer:
A tag marks a specific version of code.

πŸ‘‰ Use Case:
Mark releases like:

v1.0
v2.0

14. What is Git Stash?

πŸ‘‰ Answer:
Temporarily saves uncommitted changes.

πŸ‘‰ Use Case:
You are working on a feature but need to switch branches quickly.


15. What is Code Review in GitHub?

πŸ‘‰ Answer:
Process of reviewing code before merging.

πŸ‘‰ Use Case:

  • Developer checks logic
  • QA verifies test coverage
  • Ensures code quality

πŸ”Ή Scenario-Based GitHub Interview Questions


16. You pushed wrong code to main branch. What will you do?

πŸ‘‰ Answer:

  • Revert commit:
git revert <commit-id>

OR

  • Reset (if safe):
git reset --hard HEAD~1

πŸ‘‰ Best Practice:
Avoid direct commits to main β†’ use PR workflow.


17. Multiple developers working on same feature. How to manage?

πŸ‘‰ Answer:

  • Use feature branches
  • Regularly pull latest changes
  • Resolve conflicts early

πŸ‘‰ Use Case:
Each dev works on sub-features β†’ merged via PR.


18. How do you handle large files in GitHub?

πŸ‘‰ Answer:
Use Git LFS (Large File Storage).

πŸ‘‰ Use Case:
Store large test data or binaries.


19. How do you secure sensitive data in GitHub?

πŸ‘‰ Answer:

  • Never commit secrets
  • Use GitHub Secrets
  • Use .gitignore

πŸ‘‰ Use Case:
Store API keys in environment variables.


20. Explain CI/CD pipeline using GitHub Actions

πŸ‘‰ Answer:

  1. Code pushed to GitHub
  2. Workflow triggers
  3. Build runs
  4. Tests execute
  5. Deploy

πŸ‘‰ Use Case:
Playwright tests run automatically on every commit.


πŸ”Ή Advanced Practical Questions


21. How do you revert a specific file to previous version?

git checkout <commit-id> -- file.js

22. How do you squash commits?

git rebase -i HEAD~3

πŸ‘‰ Combine multiple commits into one.


23. What is Detached HEAD?

πŸ‘‰ Answer:
When you’re not on any branch.

πŸ‘‰ Use Case:
Checking old commit without affecting current branch.


24. How do you delete a branch?

git branch -d branch-name
git push origin --delete branch-name

25. What is Upstream in Git?

πŸ‘‰ Answer:
Reference to original repository (especially in forks).

πŸ‘‰ Use Case:
Keep your fork updated with original repo.


Mock Interview: GitHub (Real Company Style)


πŸ”Ή Round 1: Basics + Practical Understanding

❓ Q1: Explain your GitHub workflow in your current project.

πŸ‘‰ Strong Answer:

β€œWe follow a feature branch workflow. Each task starts with a new branch from main. After development, we push code and raise a pull request. CI runs automatically using GitHub Actions. After code review and approvals, we merge into main. Direct commits to main are restricted.”

πŸ‘‰ What interviewer checks:

  • Real experience
  • Collaboration understanding
  • CI/CD awareness

❓ Q2: What happens when you run git push?

πŸ‘‰ Strong Answer:

β€œIt uploads local commits from my machine (using Git) to the remote repository on GitHub, making them available to the team.”

πŸ‘‰ Follow-up trap:
πŸ‘‰ β€œWhat if push is rejected?”

βœ”οΈ Answer:

β€œIt usually means my branch is behind. I pull the latest changes, resolve conflicts if any, and push again.”


πŸ”Ή Round 2: Scenario-Based Questions


❓ Q3: You and another developer changed the same file. Your PR shows conflict. What do you do?

πŸ‘‰ Strong Answer:

β€œI pull the latest changes from main, resolve conflicts locally, test the code, commit the fix, and push again to update the PR.”

πŸ‘‰ Bonus point:
Mention testing after conflict resolution.


❓ Q4: You accidentally pushed sensitive data (API key) to GitHub. What will you do?

πŸ‘‰ Strong Answer:

β€œFirst, I revoke the key immediately. Then I remove it from the repository, rewrite history if needed, and ensure it’s added to .gitignore. Going forward, I store secrets using GitHub Secrets.”

πŸ‘‰ What interviewer checks:

  • Security awareness
  • Real-world handling

❓ Q5: Your teammate’s PR broke the build. What should happen?

πŸ‘‰ Strong Answer:

β€œThe CI pipeline should fail automatically. The PR should not be merged until the issue is fixed. We enforce required checks before merging.”

πŸ‘‰ Extra credit:
Mention branch protection rules.


πŸ”Ή Round 3: CI/CD + Automation (Very Important)


❓ Q6: How do you integrate automation tests with GitHub?

πŸ‘‰ Strong Answer:

β€œWe use GitHub Actions to trigger Playwright tests on every PR. The workflow installs dependencies, runs tests, and publishes reports.”

πŸ‘‰ Example flow:

  • PR created
  • Tests run automatically
  • Pass β†’ merge allowed
  • Fail β†’ fix required

❓ Q7: How do you ensure code quality before merging?

πŸ‘‰ Strong Answer:

β€œWe use a combination of:

  • Pull request reviews
  • Automated tests
  • Linting checks
  • CI validation

Only after all checks pass, the PR is merged.”


πŸ”Ή Round 4: Advanced Problem Solving


❓ Q8: Your main branch is broken after a merge. What will you do?

πŸ‘‰ Strong Answer:

β€œI would quickly identify the faulty commit and revert it using git revert. Then fix the issue in a new branch and raise another PR.”

πŸ‘‰ Important:
Avoid rewriting history in shared branches.


❓ Q9: How do you handle multiple environments (dev, staging, prod)?

πŸ‘‰ Strong Answer:

β€œWe use different branches or deployment workflows. For example:

  • develop β†’ dev environment
  • main β†’ production
    CI/CD pipelines deploy automatically based on branch.”

❓ Q10: How do you manage large teams working on the same repo?

πŸ‘‰ Strong Answer:

β€œWe use:

  • Feature branches
  • Clear naming conventions
  • Code owners
  • Mandatory PR reviews
  • CI/CD checks

This ensures smooth collaboration and avoids conflicts.”


πŸ”Ή Round 5: Rapid Fire (Quick Checks)


❓ Difference between Fork and Clone?

πŸ‘‰ Fork = copy on GitHub
πŸ‘‰ Clone = copy on local machine


❓ What is HEAD in Git?

πŸ‘‰ Pointer to the current commit/branch


❓ What is Rebase?

πŸ‘‰ Rewrites commit history to make it linear


❓ What is Stash?

πŸ‘‰ Temporarily saves uncommitted changes


❓ What is a Tag?

πŸ‘‰ Marks a release/version


πŸ”Ή Real Interview Challenge (Hands-On Thinking)


❓ Q11: Design a GitHub workflow for automation testing.

πŸ‘‰ Strong Answer:

β€œI would:

  1. Trigger workflow on PR and push
  2. Install dependencies
  3. Run Playwright tests
  4. Generate reports
  5. Upload artifacts
  6. Fail build if tests fail

This ensures only tested code gets merged.”


πŸ”Ή Final HR + Practical Question


❓ Q12: Tell me a real problem you faced in GitHub and how you solved it.

πŸ‘‰ Sample Answer:

β€œWe had frequent merge conflicts due to long-running branches. I suggested smaller PRs and frequent rebasing. This reduced conflicts and improved deployment speed.”



Playwright Save Login Session with POM

Here’s a complete, real-world Playwright POM framework showing how to:

  • Login once using beforeAll
  • Share the session across tests
  • Use Page Object Model (POM)
  • Follow best practices for scalability

βœ… 1. Project Structure (Recommended)

playwright-project/
β”‚
β”œβ”€β”€ tests/
β”‚ β”œβ”€β”€ login.setup.ts # Login once & save session
β”‚ β”œβ”€β”€ example.spec.ts # Actual test cases
β”‚
β”œβ”€β”€ pages/
β”‚ β”œβ”€β”€ LoginPage.ts
β”‚ β”œβ”€β”€ DashboardPage.ts
β”‚
β”œβ”€β”€ utils/
β”‚ β”œβ”€β”€ baseTest.ts # Custom fixture (optional advanced)
β”‚
β”œβ”€β”€ playwright.config.ts
└── package.json

βœ… 2. Login Page (POM)

pages/LoginPage.ts

import { Page } from '@playwright/test';export class LoginPage {
readonly page: Page; constructor(page: Page) {
this.page = page;
} async navigate() {
await this.page.goto('https://example.com/login');
} async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#loginBtn');
}
}

βœ… 3. Dashboard Page (POM)

pages/DashboardPage.ts

import { Page, expect } from '@playwright/test';export class DashboardPage {
readonly page: Page; constructor(page: Page) {
this.page = page;
} async verifyDashboardLoaded() {
await expect(this.page.locator('h1')).toHaveText('Dashboard');
}
}

βœ… 4. Login Setup (Runs Once Before All Tests)

πŸ‘‰ This is the key part (beforeAll session handling)

tests/login.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';setup('Login and save session', async ({ page }) => {
const loginPage = new LoginPage(page); await loginPage.navigate();
await loginPage.login('testuser', 'password123'); // Save session
await page.context().storageState({ path: 'storageState.json' });
});

βœ… 5. Playwright Config (Use Stored Session)

playwright.config.ts

import { defineConfig } from '@playwright/test';export default defineConfig({
testDir: './tests', use: {
baseURL: 'https://example.com',
storageState: 'storageState.json', // reuse login session
headless: false
}, projects: [
{
name: 'setup',
testMatch: /login\.setup\.ts/,
},
{
name: 'tests',
dependencies: ['setup'], // ensures login runs first
testMatch: /.*\.spec\.ts/,
},
],
});

βœ… 6. Test File (Uses Shared Session)

tests/example.spec.ts

import { test } from '@playwright/test';
import { DashboardPage } from '../pages/DashboardPage';test.describe('Dashboard Tests', () => { test.beforeAll(async () => {
console.log('Runs once before all tests');
}); test('Verify dashboard page', async ({ page }) => {
const dashboard = new DashboardPage(page); await page.goto('/dashboard');
await dashboard.verifyDashboardLoaded();
}); test('Another test using same session', async ({ page }) => {
await page.goto('/dashboard/settings');
console.log('User is already logged in');
});});

βœ… 7. How This Works (Important)

πŸ”Ή Flow:

  1. login.setup.ts runs first
  2. Logs in and saves session β†’ storageState.json
  3. All test files reuse this session
  4. No repeated login β†’ faster execution

βœ… 8. Alternative: Using beforeAll Without storageState (Not Recommended)

test.beforeAll(async ({ browser }) => {
const context = await browser.newContext();
const page = await context.newPage(); await page.goto('/login');
await page.fill('#username', 'user');
await page.fill('#password', 'pass');
await page.click('#loginBtn'); // ❌ This session is NOT shared across tests automatically
});

πŸ‘‰ Problem:

  • Each test gets a new context
  • Session is NOT reused

βœ… 9. Best Practice Summary

βœ” Use storageState (Recommended)
βœ” Keep login logic in setup file
βœ” Use POM for maintainability
βœ” Use project dependencies
βœ” Avoid login in every test


βœ… 10. Pro Tips (Real Project)

  • Store credentials in .env
  • Use multiple storage states for multi-users
  • Use fixtures for advanced reuse
  • Add retry logic for flaky login

Here’s a complete, real-world Playwright setup for multi-user session handling (Admin + User) using POM + storageState + project dependencies.

This is how teams handle role-based testing at scale.


βœ… 1. Goal

We want to:

  • Login as Admin
  • Login as Normal User
  • Save both sessions separately
  • Run tests using either role without logging in again

βœ… 2. Project Structure

playwright-project/
β”‚
β”œβ”€β”€ tests/
β”‚ β”œβ”€β”€ setup/
β”‚ β”‚ β”œβ”€β”€ admin.setup.ts
β”‚ β”‚ β”œβ”€β”€ user.setup.ts
β”‚ β”‚
β”‚ β”œβ”€β”€ admin.spec.ts
β”‚ β”œβ”€β”€ user.spec.ts
β”‚
β”œβ”€β”€ pages/
β”‚ β”œβ”€β”€ LoginPage.ts
β”‚ β”œβ”€β”€ DashboardPage.ts
β”‚
β”œβ”€β”€ storage/
β”‚ β”œβ”€β”€ adminState.json
β”‚ β”œβ”€β”€ userState.json
β”‚
β”œβ”€β”€ playwright.config.ts

βœ… 3. Login Page (Reusable POM)

pages/LoginPage.ts

import { Page } from '@playwright/test';export class LoginPage {
constructor(private page: Page) {} async navigate() {
await this.page.goto('/login');
} async login(username: string, password: string) {
await this.page.fill('#username', username);
await this.page.fill('#password', password);
await this.page.click('#loginBtn');
}
}

βœ… 4. Admin Login Setup

tests/setup/admin.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';setup('Login as Admin', async ({ page }) => {
const login = new LoginPage(page); await login.navigate();
await login.login('adminUser', 'adminPass'); await page.context().storageState({
path: 'storage/adminState.json',
});
});

βœ… 5. User Login Setup

tests/setup/user.setup.ts

import { test as setup } from '@playwright/test';
import { LoginPage } from '../../pages/LoginPage';setup('Login as User', async ({ page }) => {
const login = new LoginPage(page); await login.navigate();
await login.login('normalUser', 'userPass'); await page.context().storageState({
path: 'storage/userState.json',
});
});

βœ… 6. Playwright Config (Multi-User Projects)

playwright.config.ts

import { defineConfig } from '@playwright/test';export default defineConfig({
testDir: './tests', use: {
baseURL: 'https://example.com',
headless: false,
}, projects: [
// πŸ”Ή Admin Setup
{
name: 'admin-setup',
testMatch: /admin\.setup\.ts/,
}, // πŸ”Ή User Setup
{
name: 'user-setup',
testMatch: /user\.setup\.ts/,
}, // πŸ”Ή Admin Tests
{
name: 'admin-tests',
dependencies: ['admin-setup'],
use: {
storageState: 'storage/adminState.json',
},
testMatch: /admin\.spec\.ts/,
}, // πŸ”Ή User Tests
{
name: 'user-tests',
dependencies: ['user-setup'],
use: {
storageState: 'storage/userState.json',
},
testMatch: /user\.spec\.ts/,
},
],
});

βœ… 7. Admin Test Example

tests/admin.spec.ts

import { test, expect } from '@playwright/test';test('Admin can access admin panel', async ({ page }) => {
await page.goto('/admin'); await expect(page.locator('h1')).toHaveText('Admin Dashboard');
});

βœ… 8. User Test Example

tests/user.spec.ts

import { test, expect } from '@playwright/test';test('User cannot access admin panel', async ({ page }) => {
await page.goto('/admin'); await expect(page.locator('text=Access Denied')).toBeVisible();
});

βœ… 9. Advanced: Use Fixtures (Cleaner Approach)

πŸ‘‰ Create a reusable fixture for roles

utils/fixtures.ts

import { test as base } from '@playwright/test';export const test = base.extend<{
adminPage: any;
userPage: any;
}>({
adminPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'storage/adminState.json',
});
const page = await context.newPage();
await use(page);
await context.close();
}, userPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'storage/userState.json',
});
const page = await context.newPage();
await use(page);
await context.close();
},
});

Use Fixture in Test

import { test } from '../utils/fixtures';test('Admin vs User behavior', async ({ adminPage, userPage }) => {
await adminPage.goto('/dashboard');
await userPage.goto('/dashboard'); console.log('Both sessions running in parallel');
});

βœ… 10. Key Benefits

βœ” No repeated login
βœ” Faster test execution
βœ” Role-based validation
βœ” Parallel execution ready
βœ” Clean separation of concerns


πŸš€ Real-World Use Cases

  • Admin vs Customer flows
  • RBAC (Role-Based Access Control) testing
  • Multi-tenant apps
  • Permission validation

⚠️ Common Mistakes

❌ Using same storageState for all users
❌ Logging in inside every test
❌ Hardcoding credentials
❌ Not using project dependencies


βœ… Pro Tips

  • Use .env for credentials
  • Add API login for speed
  • Rotate test users (avoid blocking)
  • Keep session fresh (auto re-login if expired)

JavaScript Function

What is a Function in JavaScript?

A function is a block of code designed to perform a specific task. It runs only when it is called (invoked).


πŸ”Ή Basic Function Syntax

function functionName(parameters) {
// code to execute
return result;
}

πŸ”Ή 1. Simple Function Example

function greet() {
console.log("Hello, Welcome!");
}greet(); // calling function

πŸ‘‰ Output:

Hello, Welcome!

πŸ”Ή 2. Function with Parameters

function greetUser(name) {
console.log("Hello " + name);
}greetUser("Deepesh");

πŸ‘‰ Output:

Hello Deepesh

πŸ”Ή 3. Function with Return Value

function add(a, b) {
return a + b;
}let result = add(5, 3);
console.log(result);

πŸ‘‰ Output:

8

πŸ”Ή 4. Function Expression

A function can also be stored in a variable.

const multiply = function(a, b) {
return a * b;
};console.log(multiply(4, 5));

πŸ‘‰ Output:

20

πŸ”Ή 5. Arrow Function (Modern Way)

Short syntax introduced in ES6.

const subtract = (a, b) => {
return a - b;
};console.log(subtract(10, 4));

πŸ‘‰ Short version:

const subtract = (a, b) => a - b;

πŸ”Ή 6. Default Parameters

function greet(name = "Guest") {
console.log("Hello " + name);
}greet(); // Hello Guest
greet("Ram"); // Hello Ram

πŸ”Ή 7. Function with Multiple Parameters

function userInfo(name, age, city) {
console.log(name + " is " + age + " years old from " + city);
}userInfo("Deepesh", 25, "Bhopal");

πŸ”Ή 8. Callback Function

A function passed as an argument to another function.

function processUser(name, callback) {
console.log("Processing " + name);
callback();
}function done() {
console.log("Completed!");
}processUser("Deepesh", done);

πŸ”Ή 9. Anonymous Function

A function without a name.

setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);

πŸ”Ή 10. Immediately Invoked Function (IIFE)

Runs immediately after definition.

(function() {
console.log("IIFE executed");
})();

πŸ”Ή 11. Function Scope

Variables inside a function are not accessible outside.

function testScope() {
let x = 10;
console.log(x);
}testScope();
// console.log(x); ❌ Error

πŸ”Ή 12. Rest Parameters

Used to handle multiple arguments.

function sum(...numbers) {
let total = 0;
for (let num of numbers) {
total += num;
}
return total;
}console.log(sum(1, 2, 3, 4));

πŸ”Ή 13. Higher-Order Function

Function that takes another function or returns one.

function calculator(a, b, operation) {
return operation(a, b);
}const add = (x, y) => x + y;console.log(calculator(5, 3, add));

πŸ”Ή Real-World Usage

Functions are used in:

  • πŸ”Ή Form validation
  • πŸ”Ή API calls
  • πŸ”Ή Event handling (click, submit)
  • πŸ”Ή Reusable utilities
  • πŸ”Ή Automation scripts (like Playwright tests)

πŸ”Ή Example: Real Use Case (Form Validation)

function validateEmail(email) {
return email.includes("@");
}function submitForm(email) {
if (validateEmail(email)) {
console.log("Form submitted");
} else {
console.log("Invalid email");
}
}submitForm("test@gmail.com");

πŸ”Ή Best Practices

βœ” Use meaningful function names
βœ” Keep functions small and focused
βœ” Use arrow functions for short logic
βœ” Avoid global variables
βœ” Always return values when needed


πŸ”Ή Summary

  • Functions make code reusable
  • Can take inputs (parameters)
  • Can return outputs
  • Support modern syntax (arrow functions)
  • Essential for real-world JavaScript development

JavaScript Loop Programs with Solutions

Print numbers from 1 to 10 (Basic for)

for (let i = 1; i <= 10; i++) {
console.log(i);
}

2️⃣ Print numbers from 10 to 1 (Reverse loop)

for (let i = 10; i >= 1; i--) {
console.log(i);
}

3️⃣ Print even numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 === 0) {
console.log(i);
}
}

4️⃣ Print odd numbers (Loop with if)

for (let i = 1; i <= 20; i++) {
if (i % 2 !== 0) {
console.log(i);
}
}

5️⃣ Sum of numbers from 1 to 10

let sum = 0;for (let i = 1; i <= 10; i++) {
sum += i;
}console.log(sum);

6️⃣ Multiplication table of 5

for (let i = 1; i <= 10; i++) {
console.log(`5 x ${i} = ${5 * i}`);
}

7️⃣ Nested loop: Print square pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += "* ";
}
console.log(row);
}

8️⃣ Nested loop: Number pattern

for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += j + " ";
}
console.log(row);
}

9️⃣ while loop: Print 1 to 5

let i = 1;while (i <= 5) {
console.log(i);
i++;
}

πŸ”Ÿ while loop: Sum of first 5 numbers

let i = 1;
let sum = 0;while (i <= 5) {
sum += i;
i++;
}console.log(sum);

1️⃣1️⃣ do...while: Print 1 to 5

let i = 1;do {
console.log(i);
i++;
} while (i <= 5);

1️⃣2️⃣ do...while: Run at least once

let i = 10;do {
console.log(i);
} while (i < 5);

1️⃣3️⃣ forEach: Print array elements

let arr = [10, 20, 30];arr.forEach(num => console.log(num));

1️⃣4️⃣ forEach: Sum of array

let arr = [1, 2, 3, 4];
let sum = 0;arr.forEach(num => {
sum += num;
});console.log(sum);

1️⃣5️⃣ Loop through string (characters)

let str = "Hello";for (let char of str) {
console.log(char);
}

1️⃣6️⃣ Count vowels in a string

let str = "javascript";
let count = 0;for (let char of str) {
if ("aeiou".includes(char)) {
count++;
}
}console.log(count);

1️⃣7️⃣ Loop through array using for

let arr = [5, 10, 15];for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}

1️⃣8️⃣ Find largest number in array

let arr = [10, 5, 20, 8];
let max = arr[0];for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}console.log(max);

1️⃣9️⃣ Loop through object properties (for...in)

let person = {
name: "John",
age: 25,
city: "Delhi"
};for (let key in person) {
console.log(key + ": " + person[key]);
}

2️⃣0️⃣ Count properties in an object

let obj = {
a: 1,
b: 2,
c: 3
};let count = 0;for (let key in obj) {
count++;
}console.log(count);

Beginner Level

  1. Write a JavaScript program to print numbers from 1 to 10 using a for loop.
  2. Write a JavaScript program to print numbers from 10 to 1 in reverse order.
  3. Write a JavaScript program to print all even numbers between 1 and 100.
  4. Write a JavaScript program to print all odd numbers between 1 and 100.
  5. Write a JavaScript program to calculate the sum of numbers from 1 to N.
  6. Write a JavaScript program to calculate the product of numbers from 1 to N.
  7. Write a JavaScript program to print the multiplication table of a given number.
  8. Write a JavaScript program to print the multiplication tables from 1 to 10.
  9. Write a JavaScript program to count the total number of digits in a given number.
  10. Write a JavaScript program to reverse a given number.

Intermediate Level

  1. Write a JavaScript program to check whether a given number is a palindrome.
  2. Write a JavaScript program to find the sum of digits of a given number.
  3. Write a JavaScript program to find the largest digit in a number.
  4. Write a JavaScript program to find the smallest digit in a number.
  5. Write a JavaScript program to calculate the factorial of a number.
  6. Write a JavaScript program to check whether a number is a prime number.
  7. Write a JavaScript program to print all prime numbers between 1 and N.
  8. Write a JavaScript program to count the total number of prime numbers between 1 and N.
  9. Write a JavaScript program to find the sum of all prime numbers between 1 and N.
  10. Write a JavaScript program to print the Fibonacci series up to N terms.

Pattern Programs

  1. Write a JavaScript program to print a right-angled triangle using *.
  2. Write a JavaScript program to print an inverted right-angled triangle.
  3. Write a JavaScript program to print a pyramid pattern using *.
  4. Write a JavaScript program to print an inverted pyramid pattern.
  5. Write a JavaScript program to print a diamond pattern.
  6. Write a JavaScript program to print Floyd’s Triangle.
  7. Write a JavaScript program to print Pascal’s Triangle.
  8. Write a JavaScript program to print a square pattern using *.
  9. Write a JavaScript program to print a hollow square pattern.
  10. Write a JavaScript program to print a hollow pyramid pattern.

Advanced Loop Programs

  1. Write a JavaScript program to find all Armstrong numbers between 1 and N.
  2. Write a JavaScript program to check whether a given number is an Armstrong number.
  3. Write a JavaScript program to find the Greatest Common Divisor (GCD) of two numbers.
  4. Write a JavaScript program to find the Least Common Multiple (LCM) of two numbers.
  5. Write a JavaScript program to convert a decimal number to binary.
  6. Write a JavaScript program to convert a binary number to decimal.
  7. Write a JavaScript program to calculate the power of a number without using built-in methods.
  8. Write a JavaScript program to print all perfect numbers between 1 and N.
  9. Write a JavaScript program to check whether a given number is a perfect number.
  10. Write a JavaScript program to find the sum of all even numbers between 1 and N.

Nested Loop Programs

  1. Write a JavaScript program to print a multiplication table using nested loops.
  2. Write a JavaScript program to print a number triangle pattern.
  3. Write a JavaScript program to print a character triangle pattern.
  4. Write a JavaScript program to print a checkerboard (# and *) pattern.
  5. Write a JavaScript program to print a hollow rectangle using nested loops.
  6. Write a JavaScript program to print an X pattern using *.
  7. Write a JavaScript program to print a butterfly pattern.
  8. Write a JavaScript program to print a sandglass pattern.
  9. Write a JavaScript program to print a zigzag pattern.
  10. Write a JavaScript program to create a simple number guessing game using loops.

JavaScript Loop Fundamentals

Loops allow you to execute code repeatedly based on a condition.


1️⃣ Basic for Loop

πŸ‘‰ Example:

for (let i = 1; i <= 5; i++) {
console.log(i);
}

πŸ’‘ Output:

1 2 3 4 5

2️⃣ Loop with if Condition

πŸ‘‰ Example: Print even numbers

for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
console.log(i);
}
}

πŸ’‘ Output:

2 4 6 8 10

3️⃣ Nested for Loop

πŸ‘‰ Example: Pattern (matrix)

for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`Row ${i}, Column ${j}`);
}
}

πŸ’‘ Concept:

  • Outer loop β†’ rows
  • Inner loop β†’ columns

4️⃣ while Loop

πŸ‘‰ Example:

let i = 1;while (i <= 5) {
console.log(i);
i++;
}

πŸ’‘ Use case:

  • When iteration count is unknown

5️⃣ do...while Loop

πŸ‘‰ Example:

let i = 1;do {
console.log(i);
i++;
} while (i <= 5);

πŸ’‘ Key Point:

  • Executes at least once

6️⃣ forEach Loop (Array Only)

πŸ‘‰ Example:

let arr = [10, 20, 30];arr.forEach((value, index) => {
console.log(index, value);
});

7️⃣ Loop with String Datatype

A string is iterable, so you can loop through characters.

πŸ‘‰ Example using for

let str = "Hello";for (let i = 0; i < str.length; i++) {
console.log(str[i]);
}

πŸ‘‰ Example using for...of

for (let char of "Hello") {
console.log(char);
}

πŸ’‘ Output:

H e l l o

8️⃣ Loop with Array Datatype

πŸ‘‰ Example using for

let numbers = [1, 2, 3, 4];for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}

πŸ‘‰ Example using for...of

for (let num of numbers) {
console.log(num);
}

πŸ‘‰ Example using forEach

numbers.forEach(num => console.log(num));

9️⃣ Loop with Object Datatype

Objects are not directly iterable like arrays, but we use for...in.

πŸ‘‰ Example:

let person = {
name: "John",
age: 25,
city: "Delhi"
};for (let key in person) {
console.log(key, person[key]);
}

πŸ’‘ Output:

name John
age 25
city Delhi

πŸ”₯ Summary Table

Loop TypeBest Use Case
forFixed iterations
whileUnknown iterations
do...whileRuns at least once
forEachArrays
for...ofArrays & strings
for...inObjects

Common Mistakes

❌ Infinite Loop

for (let i = 1; i <= 5; ) {
// missing increment
}

❌ Wrong Object Loop

for (let item of person) // ❌ Error

βœ” Correct:

for (let key in person)

βœ… Practice Ideas

  1. Reverse a string using loop
  2. Find largest number in array
  3. Count vowels in string
  4. Print object keys and values
  5. Create star pattern using nested loop

GitHub Fundamentals

1. What is GitHub?

  • GitHub is a platform to store, manage, and collaborate on code.
  • It uses Git (a version control system).

πŸ‘‰ Think of GitHub as:

β€œGoogle Drive for code + collaboration tools for developers”


2. What is Git?

  • Git tracks changes in your code.
  • Helps you:
    • Save versions
    • Undo mistakes
    • Work with teams

3. Repository (Repo)

A repository is a project folder stored on GitHub.

Example:

my-project/
β”œβ”€β”€ index.html
β”œβ”€β”€ style.css
└── script.js

πŸ‘‰ This entire folder = 1 repository


4. Clone a Repository

Copy a GitHub repo to your local machine.

Command:

git clone https://github.com/user/project.git

Example:

git clone https://github.com/deepesh/my-app.git

5. Basic Git Workflow

The most important concept πŸ‘‡

Working Directory β†’ Staging Area β†’ Repository

Steps:

git add file.js      # Add file to staging
git commit -m "Added feature" # Save changes
git push # Upload to GitHub

6. Commit

A commit is a snapshot of your code.

Example:

git commit -m "Fixed login bug"

πŸ‘‰ Good commit message = clear + meaningful


7. Branch

A branch lets you work on features without affecting main code.

Example:

git branch feature-login
git checkout feature-login

Or shortcut:

git checkout -b feature-login

8. Merge

Combine changes from one branch into another.

Example:

git checkout main
git merge feature-login

9. Pull Request (PR)

  • A Pull Request is used to merge code on GitHub.
  • You request others to review your code.

πŸ‘‰ Workflow:

  1. Create branch
  2. Push code
  3. Open PR
  4. Review β†’ Merge

10. Push & Pull

Push (upload changes):

git push origin main

Pull (get latest changes):

git pull origin main

11. Fork

A fork is a copy of someone else’s repository.

πŸ‘‰ Used in open-source contributions.


12. .gitignore

Tells Git which files to ignore.

Example:

node_modules/
.env
*.log

13. Real Example Workflow

Let’s say you’re building a JavaScript project:

Step 1: Initialize repo

git init

Step 2: Add files

git add .

Step 3: Commit

git commit -m "Initial project setup"

Step 4: Connect GitHub

git remote add origin https://github.com/user/project.git

Step 5: Push

git push -u origin main

14. Common Commands Cheat Sheet

CommandPurpose
git initStart repo
git cloneCopy repo
git addStage changes
git commitSave changes
git pushUpload
git pullDownload updates
git branchList branches
git checkoutSwitch branch

15. Best Practices

  • βœ… Commit often
  • βœ… Use clear commit messages
  • βœ… Use branches for features
  • βœ… Pull before push
  • ❌ Don’t push sensitive data

🎯 Mini Practice Exercise

Try this:

  1. Create a folder
  2. Add a file app.js
  3. Run:
  4. Push it to GitHub
git init
git add .
git commit -m "First commit"
git push

Pro Tip

Start with:

  • Personal projects
  • Practice branching + PRs

That’s how real developers learn GitHub fast.

16. GitHub Issues (Task Tracking)

  • Issues are used to track bugs, tasks, or feature requests.

Example:

You create an issue:

Title: Fix login error
Description: Login fails when password is incorrect

πŸ‘‰ You can:

  • Assign team members
  • Add labels (bug, feature, urgent)
  • Track progress

πŸ“Œ 17. Labels (Organizing Work)

Labels help categorize issues.

Example labels:

  • bug πŸ›
  • enhancement πŸš€
  • documentation πŸ“„

πŸ‘‰ Helps teams quickly understand task types.


πŸ“Š 18. GitHub Projects (Kanban Board)

GitHub provides project boards similar to Trello.

Example workflow:

To Do β†’ In Progress β†’ Done

πŸ‘‰ You can drag issues between columns.


πŸ” 19. README.md File

This is the first file people see in your repo.

Example:

# My AppThis is a simple JavaScript project.## Features
- Login system
- Dashboard

πŸ‘‰ A good README increases project visibility.


βš™οΈ 20. GitHub Actions (Automation)

  • GitHub Actions lets you automate workflows.

Example:

Run tests automatically when code is pushed.

name: Test App
on: [push]jobs:
test:
runs-on: ubuntu-latest
steps:
- run: echo "Running tests..."

πŸ‘‰ Used for:

  • CI/CD (Continuous Integration / Deployment)
  • Auto testing
  • Deployment

πŸ” 21. Pull vs Fetch

Git Pull:

git pull origin main

πŸ‘‰ Fetch + merge

Git Fetch:

git fetch

πŸ‘‰ Only downloads changes (no merge)


πŸ”„ 22. Merge Conflict (Important!)

Occurs when Git can’t merge automatically.

Example conflict:

<<<<<<< HEAD
console.log("Hello");
=======
console.log("Hi");
>>>>>>> branch

πŸ‘‰ You must manually fix it:

console.log("Hello Hi");

Then:

git add .
git commit -m "Resolved conflict"

πŸ§ͺ 23. Stash (Temporary Save)

Save changes without committing.

git stash

Restore:

git stash pop

πŸ‘‰ Useful when switching branches quickly.


πŸ“œ 24. Git Log (History)

View commit history:

git log

Short version:

git log --oneline

βͺ 25. Undo Changes

Undo staged file:

git reset file.js

Undo last commit:

git reset --soft HEAD~1

Discard changes:

git checkout -- file.js

🌐 26. Remote Repository

Link your local repo to GitHub.

git remote add origin https://github.com/user/repo.git

Check:

git remote -v

πŸ”’ 27. SSH vs HTTPS

Two ways to connect GitHub:

HTTPS:

https://github.com/user/repo.git

SSH:

git@github.com:user/repo.git

πŸ‘‰ SSH is more secure (no need to enter password repeatedly)


πŸ“¦ 28. Fork + Clone + PR (Real Open Source Flow)

Step-by-step:

  1. Fork repository on GitHub
  2. Clone it:
git clone https://github.com/your-username/repo.git
  1. Create branch:
git checkout -b fix-bug
  1. Make changes + commit
  2. Push:
git push origin fix-bug
  1. Create Pull Request

πŸ‘‰ This is how open-source contributions work.


🧱 29. Rebase (Advanced Concept)

Instead of merge, you can use rebase for cleaner history.

git checkout feature
git rebase main

πŸ‘‰ Keeps history linear (no extra merge commits)


🏷️ 30. Tags (Versioning)

Used for releases.

git tag v1.0
git push origin v1.0

πŸ‘‰ Example:

  • v1.0 β†’ first release
  • v2.0 β†’ major update

Real-World Scenario (Important)

Scenario: Team Development

  1. Developer A creates feature branch
  2. Developer B works on another branch
  3. Both create Pull Requests
  4. Code review happens
  5. Merge into main

πŸ‘‰ This prevents breaking the main codebase.


🧠 Pro Learning Tips

  • Practice daily with small repos
  • Break code β†’ fix using Git
  • Try merge conflicts intentionally
  • Explore open-source repos

πŸ’» Practice Tasks (Next Level)

Try these:

  1. Create 2 branches and merge them
  2. Create a merge conflict and resolve it
  3. Use git stash while switching branches
  4. Create a Pull Request on your own repo
  5. Add a README with project details

JavaScript If-Condition Programs

Here are 20 JavaScript programs with solutions covering:
βœ” if
βœ” if-else
βœ” if-else if
βœ” nested if
βœ” one-line (ternary) conditions


πŸ”Ή 1. Positive number (if)

let num = 5;if (num > 0) {
console.log("Positive");
}

πŸ”Ή 2. Even or odd (if-else)

let num = 4;if (num % 2 === 0) {
console.log("Even");
} else {
console.log("Odd");
}

πŸ”Ή 3. Voting eligibility (if-else)

let age = 16;if (age >= 18) {
console.log("Eligible");
} else {
console.log("Not eligible");
}

πŸ”Ή 4. Largest of two numbers (if-else)

let a = 10, b = 20;if (a > b) {
console.log("a is greater");
} else {
console.log("b is greater");
}

πŸ”Ή 5. Divisible by 3 (if)

let num = 9;if (num % 3 === 0) {
console.log("Divisible by 3");
}

πŸ”Ή 6. Grade system (if-else if)

let marks = 85;if (marks >= 90) {
console.log("A");
} else if (marks >= 70) {
console.log("B");
} else if (marks >= 50) {
console.log("C");
} else {
console.log("Fail");
}

πŸ”Ή 7. Largest of three numbers (if-else if)

let a = 5, b = 8, c = 3;if (a > b && a > c) {
console.log("a is largest");
} else if (b > c) {
console.log("b is largest");
} else {
console.log("c is largest");
}

πŸ”Ή 8. Leap year (if-else)

let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log("Leap year");
} else {
console.log("Not leap year");
}

πŸ”Ή 9. Check number range (if)

let num = 25;if (num >= 10 && num <= 50) {
console.log("Within range");
}

πŸ”Ή 10. Character type (if-else if)

let ch = 'A';if (ch >= 'A' && ch <= 'Z') {
console.log("Uppercase");
} else if (ch >= 'a' && ch <= 'z') {
console.log("Lowercase");
} else {
console.log("Other");
}

πŸ”Ή 11. Nested if (positive & even)

let num = 8;if (num > 0) {
if (num % 2 === 0) {
console.log("Positive and Even");
}
}

πŸ”Ή 12. Nested if (login system)

let username = "admin";
let password = "1234";if (username === "admin") {
if (password === "1234") {
console.log("Login successful");
} else {
console.log("Wrong password");
}
} else {
console.log("User not found");
}

πŸ”Ή 13. Nested if (marks & distinction)

let marks = 75;if (marks >= 40) {
if (marks >= 75) {
console.log("Distinction");
} else {
console.log("Pass");
}
} else {
console.log("Fail");
}

πŸ”Ή 14. One-line if (ternary)

let num = 10;console.log(num > 0 ? "Positive" : "Not positive");

πŸ”Ή 15. One-line even/odd

let num = 7;console.log(num % 2 === 0 ? "Even" : "Odd");

πŸ”Ή 16. One-line pass/fail

let marks = 35;console.log(marks >= 40 ? "Pass" : "Fail");

πŸ”Ή 17. Multiple conditions (if)

let num = 15;if (num % 3 === 0 && num % 5 === 0) {
console.log("Divisible by 3 and 5");
}

πŸ”Ή 18. Temperature check (if-else if)

let temp = 30;if (temp > 40) {
console.log("Hot");
} else if (temp > 20) {
console.log("Warm");
} else {
console.log("Cold");
}

πŸ”Ή 19. Triangle validity (if)

let a = 3, b = 4, c = 5;if (a + b > c && a + c > b && b + c > a) {
console.log("Valid triangle");
}

πŸ”Ή 20. Simple calculator (if-else if)

let a = 10, b = 5;
let op = "+";if (op === "+") {
console.log(a + b);
} else if (op === "-") {
console.log(a - b);
} else if (op === "*") {
console.log(a * b);
} else if (op === "/") {
console.log(a / b);
} else {
console.log("Invalid operator");
}

JavaScript if Condition Practice Programs (Without Solution)

Beginner Level

  1. Check whether a number is positive.
  2. Check whether a number is negative.
  3. Check whether a number is zero.
  4. Check whether a number is even or odd.
  5. Check whether a person is eligible to vote.
  6. Check whether a student passed or failed.
  7. Find the greater number between two numbers.
  8. Find the smaller number between two numbers.
  9. Check whether a character is a vowel or consonant.
  10. Check whether a year is a leap year.

Intermediate Level

  1. Check whether a number is divisible by 5.
  2. Check whether a number is divisible by both 3 and 7.
  3. Find the largest among three numbers.
  4. Find the smallest among three numbers.
  5. Check whether a character is uppercase or lowercase.
  6. Check whether a number is a 3-digit number.
  7. Check whether a person is a child, teenager, or adult.
  8. Check whether a triangle is valid based on angles.
  9. Check whether a temperature is hot, cold, or moderate.
  10. Calculate bonus based on salary conditions.

Advanced Beginner Level

  1. Check whether a number is divisible by 2 but not by 5.
  2. Check whether a student got distinction, first class, second class, or failed.
  3. Check whether a number is within a given range.
  4. Check whether three sides can form a triangle.
  5. Find the middle number among three numbers.
  6. Check whether a character is an alphabet, digit, or special character.
  7. Check whether a user entered the correct username and password.
  8. Check whether a number is a multiple of 10.
  9. Check whether a person is eligible for a driving license.
  10. Check whether an entered day is weekday or weekend.

JavaScript If Condition Fundamentals

βœ… 1. What is an if condition?

An if statement is used to execute code only when a condition is true.

πŸ“Œ Syntax:

if (condition) {
// code runs if condition is true
}

βœ… Example:

let age = 18;if (age >= 18) {
console.log("You are eligible to vote");
}

βœ… 2. if...else Statement

Used when you want to handle both true and false cases.

πŸ“Œ Syntax:

if (condition) {
// true block
} else {
// false block
}

βœ… Example:

let number = 5;if (number % 2 === 0) {
console.log("Even number");
} else {
console.log("Odd number");
}

βœ… 3. if...else if...else

Used when you have multiple conditions.

πŸ“Œ Syntax:

if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default block
}

βœ… Example:

let marks = 75;if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 70) {
console.log("Grade B");
} else {
console.log("Grade C");
}

βœ… 4. Nested if

An if inside another if.

βœ… Example:

let age = 20;
let hasLicense = true;if (age >= 18) {
if (hasLicense) {
console.log("You can drive");
} else {
console.log("Get a license first");
}
}

βœ… 5. Ternary Operator (Short if-else)

A short form of if...else.

πŸ“Œ Syntax:

condition ? value1 : value2;

βœ… Example:

let age = 16;let result = (age >= 18) ? "Adult" : "Minor";
console.log(result);

πŸ”· Important Concepts

πŸ”Ή Comparison Operators

OperatorMeaning
==Equal (loose)
===Equal (strict)
!=Not equal
!==Strict not equal
> < >= <=Comparison

πŸ‘‰ Always prefer === (strict equality)


πŸ”Ή Logical Operators

OperatorMeaning
&&AND
!NOT

βœ… Example:

let age = 20;
let hasID = true;if (age >= 18 && hasID) {
console.log("Allowed entry");
}

πŸ”· Practice Programs (Very Important πŸš€)

🟒 Beginner Level

1. Check Positive or Negative

let num = -5;if (num >= 0) {
console.log("Positive");
} else {
console.log("Negative");
}

2. Find Largest of Two Numbers

let a = 10, b = 20;if (a > b) {
console.log("A is larger");
} else {
console.log("B is larger");
}

3. Check Divisible by 5

let num = 25;if (num % 5 === 0) {
console.log("Divisible by 5");
} else {
console.log("Not divisible");
}

🟑 Intermediate Level

4. Find Largest of Three Numbers

let a = 10, b = 25, c = 15;if (a > b && a > c) {
console.log("A is largest");
} else if (b > c) {
console.log("B is largest");
} else {
console.log("C is largest");
}

5. Check Leap Year

let year = 2024;if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
console.log("Leap Year");
} else {
console.log("Not a Leap Year");
}

6. Grade Calculator

let marks = 85;if (marks >= 90) {
console.log("A");
} else if (marks >= 75) {
console.log("B");
} else if (marks >= 50) {
console.log("C");
} else {
console.log("Fail");
}

πŸ”΄ Advanced Level

7. Check Login Access

let username = "admin";
let password = "1234";if (username === "admin" && password === "1234") {
console.log("Login successful");
} else {
console.log("Invalid credentials");
}

8. Check Even/Odd using Ternary

let num = 7;let result = (num % 2 === 0) ? "Even" : "Odd";
console.log(result);

9. Traffic Light System

let color = "red";if (color === "red") {
console.log("Stop");
} else if (color === "yellow") {
console.log("Get Ready");
} else if (color === "green") {
console.log("Go");
} else {
console.log("Invalid color");
}

πŸ”· Pro Tips πŸ’‘

  • Use === instead of ==
  • Keep conditions simple and readable
  • Avoid deeply nested if β†’ use else if instead
  • Use ternary only for short conditions

πŸ”· Practice Questions (Try Yourself )

  1. Check if a number is divisible by both 3 and 7
  2. Check whether a character is vowel or consonant
  3. Find smallest of three numbers
  4. Check if a number is palindrome
  5. Create simple ATM withdrawal condition