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);

✎ Practise what you learned: 32 JavaScript string programs with solutions →

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

✎ Practise what you learned: 32 JavaScript function programs with solutions →

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

✎ Practise what you learned: 32 JavaScript loop programs with solutions →

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

✎ Practise what you learned: 31 JavaScript if-else programs with solutions →

Github Guide

Steps to Create a GitHub Account

  1. Go to https://github.com/
  2. Click on the signup button.
  3. Enter email ID
  4. Enter password
  5. Provide a unique Username,
  6. click on the checkbox -> click on the create account button.
  7. It will show some puzzles to verify -> we have to solve.
  8. User will receive a verification code via email -> provide the code on the GitHub screen.
  9. Account creation is Successful.

Steps to Create a GitHub Repository

  1. Go to the GitHub account
  2. Click on the create repository button.
  3. Provide repository name: AutomationPractice
  4. Provide a description. e.g. Automation practice for the user.
  5. Select the Repo visibility option Public/Private.
  6. Select the readme file option.
  7. Click on the Create repository button.
  8. Repository created successfully.

Steps to install the GitHub client

  1. Download the Git client from the given link
    https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.2/Git-2.53.0.2-64-bit.exe
  2. Double-click on the exe file and initiate installation with exe
    , select all default options, and complete the installation.
  3. Create a folder in C Drive with the name GithubCode, folder path should be C:\GithubCode
  4. Open folder and right-click -> show more options -> click on open git bash here.
  5. It will open the Git terminal in the C:\GithubCode folder.
  6. Run a command to check the git option
    git –help
  7. It will show available git commands

Steps to Add User Credentials in Git Config File

  1. Open the Git terminal in the C:\GitHubCode folder
  2. Run the command below to open the config file
    -> git config –global –edit
    -> It will open the config file in the vi editor
  3. Press i to enable insert mode, it should show –insert– in the bottom.
  4. Now use keyboard arrows and update the name and email with your git username and git email.
    [user]
    name = Divya4255
    email = divya.smsrinivas1995@gmail.com
  5. Make sure to remove # from the name and email line in the config file.
  6. Press the ESCAPE key to disabled insert mode.
  7. start type :wq and press enter
    -> It will save the configuration details.

Steps to Clone the Repository on the User’s Machine

  1. Go to the GitHub server, log in with your credentials
  2. Navigate to the repository that we have already created.
  3. Click on the Code (green color) button, and copy the repository from there.
  4. Open the Git terminal in the C:\GitHubCode folder.
  5. Run the command below to clone the repo
    -> git clone https://github.com/Divya4255/AutomationPractice.git
  6. Hit Enter -> It will clone repository from server to your local machine.
  7. The repository folder will be created on the local machine.

Steps to Create a New File and Push to the GitHub Server

  1. Create a text file in the git repository folder (AutomationPractice) and rename as demo_file.txt
  2. Open the text file and add some content to the file -> save the file.
  3. Open the Git terminal in C:\GitHubCode\AutomationPractice folder.
  4. Run the git status command
    -> git status: it will show the new demo file in red color.
  5. Run the git add command
    -> git add file_path/filename # It will add the file to GitHub tracking
  6. Check the status again.
    -> git status # It will show the demo file in green color.
  7. Initiate commit operation
    -> git commit -m “adding new file to repo.”
    -> It will complete the commit operation.
  8. Initiate the git push operation.
    -> git push
    -> It will launch a pop-up
    -> Click and open in browser option.
    -> It will open in browser and click on the Authorize git ecosystem button.
    -> Now push will be successful and file will be push to the server.
    -> Check on GitHub server, the file is available on GitHub server.

Home Work For Practice:

  1. Create three different file and push them to the server.
  2. Update file1 and push(git status, git add, git commit, git push) it.
  3. Rename file2 and push it from the terminal.
  4. Delete file3 and push it from terminal.

Create a Common Repo and Provide Access

  1. Create a repository with the name: e.g., GTM_PlaywrightTS_BATCH11
  2. Get students’ email and provide Access to collaborate.
    Go to Repository -> Settings -> Collaborators -> Add People -> Enter Your email -> Select User -> Add to Repository
  3. People will receive an invitation via email.
  4. Open the email, click View Invitation, then accept the invitation.
  5. Everyone has to accept the invitation.
  6. Make sure to accept the invitation from the laptop, and your GitHub account is already open in the same browser
    where you open the mail account.
  7. Once the invitation is accepted, the user will be able to see the common repository.

Clone the Common Repo, Add folder your name

  1. Go to the common repository -> click on code (green button)
    -> click on copy clipboard to copy URL.
  2. Open the Git terminal in the C:\GitHubCode folder on the local system
  3. Run this command to clone the common repository
    -> git clone https://github.com/sqatools/GTM_PlaywrightTS_BATCH11.git
  4. It will clone the command repository into a C:\GitHubCode to the local directory.
    -> repository folder name: GTM_PlaywrightTS_BATCH11
  5. Create folder with your name in repo e.g. Deepesh and Add file inside the your folder e.g. first_file.txt
  6. Navigate back to git terminal.
  7. ON git terminal run below command to go inside repository folder.
    cd GTM_PlaywrightTS_BATCH11 -> It will open GTM_PlaywrightTS_BATCH11 folder.
  8. Check status using below command
    -> git status : New Folder name will show in red color.
  9. Run git add command
    -> git add /FolderName
  10. Initiate commit operation.
    -> git commit -m “added”
  11. Perform git push operation
    -> git push
  12. If push is rejected repeat this steps until push it not successful.
    -> git pull
    -> it will open merge editor
    -> we have to close the edit with command using :wq (save file)
    -> Once the edit is closed, re-initiate the push operation
    -> git push
    -> if push is still rejected (Repeat again from “git pull” command)
################ Multi branching in git
  1. Go to Git Repository on server : GTM_PlaywrightTS_BATCH11
  2. Click on repository dropdown. default is main
  3. click on view all branches.
  4. Create branch with your name e.g. deepesh_branch.
    -> New Branch
    -> Provide Branch Name e.g. firstname_branch
    -> click on create branch button
    -> Verify branch is created successfully.
  5. Open git terminal in repository folder
  6. run command to update the repo
    -> git pull (all newly created branches will show in the console output)
  7. Check current active branch
    -> git branch : It will show main as active branch in green color.
  8. Switch to new branch.
    -> git checkout deepesh_branch
  9. check again active branch
    -> git branch : your branch will show as active branch in green color e.g. deepesh_branch
  10. Go to your dedicated folder and add file inside the folder
    Folder Name : Deepesh
    Filename : deepesh_feature_file.txt (don’t add space in filename)

11 Go back to terminal and check status
-> git status : newly added file will show in red color

  1. Run git add command
    -> git add
  2. Initiate commit operation
    -> git commit -m “added new file to feature branch”
  3. Initiate push operation
    -> git push : file will push to the server on dedicated branch.
  4. Go to GitHub server and verify file is available in dedicated folder in your branch.
################### Create pull from server
  1. Go to server and navigate to repository.
  2. Click on “Compare & pull request” button (green button)
  3. Provide pull request description.
  4. Add reviwers to review the code.
  5. Click on create pull button.
################### Create workflow file in branch
  1. Go to repository on GitHub server
  2. Navigate to Actions Tab.
  3. Click on New Workflow (green color) button
  4. Select any workflow from given list. e.g. simple workflow
  5. click on configure button
  6. Select your branch from left side dropdown e.g. deepesh_branch.
  7. Provide workflow name default name is blank.yml
    default path: GTM_Playwright_Batch11/.gitHub/workflow/blank.yml keep this path alive
    pull_request:
    branches: [ “main” ] remove this part: this will execute workflow for every single push
    push:
    branches: [ “main” ]
  8. click on commit changes button.
  9. It will open pop to provide commit message -> we can click on commit changes
    and push to the current branch.
  10. It will create workflow on your dedicated branch and execute along with each
    PR.
########## Resolve Merge conflict

conflict scenario

  1. Create file1 in main branch add some code from line 1 to 10.
  2. Create new branch from main branch and then modify same file1 and same line numbers from 1 to 10.
  3. In main branch, modify same on same number of lines and push it.
  4. Create pull request from feature to main branch
  5. It will create conflict.
  6. We have to resolve conflict and merge the change
Steps to reproduce conflict scenario
  1. Open git terminal in repository folder.
    -> make sure your current active branch should be main
    -> if not then you can switch to main branch.
    -> ‘git checkout main’ # it will switch to main branch.
    -> ‘git pull’ : Update your main branch with all change from server.
    -> ‘git branch’ : current active branch should be main branch in green color
  2. Create a file with name e.g. dy_conflict_file.txt, and code snipet in the file, and save the file.
    var num1 = 10
    if (num1%2 == 0) {
    console.log(“This is even number”)
    } else {
    console.log(“This is odd number”)
    }
  3. Push file to main branch.
    -> git status: show file in read color
    -> git add
    -> git status : show file in green color
    -> git commit -m “added file”
    -> git push : It push is rejected, then pull the code and perform push operation.
    -> git pull : it will open editor, we have close it with :wq! command.
    -> then try to push again, repeat (pull, push), until it is not successful.
  4. Create a branch from local git bash terminal.
    -> git checkout -b “dy_conflict_branch”
  5. Update dy_conflict_file.txt file as given below. if (num1%2 == 0) {
    console.log(“This is even number, divisible by 2”)
    } else {
    console.log(“This is odd number, not divisible by 2”)
    }
  6. go back to terminal and run below command
    -> git status : shows in red color
    -> git add
    -> git status : shows file in green color
    -> git commit -m “initiate commit operation”
  7. run below command to push local branch to server
    -> git push –set-upstream origin dy_conflict_branch
    -> push will be successful in feature.
  8. change branch from conflict branch to main branch in terminal
    -> git checkout main
    -> git pull : it will update all changes from server to local machine.
  9. Open conflict file in your folder and update few change in file content.
    var num1 = 10
    if (num1%2 == 0) {
    console.log(“condition is True”)
    console.log(“This is even number, can divide by 2”)
    } else {
    console.log(“condition is False”)
    console.log(“This is odd number, can not divide by 2”)
    }
  10. push the file change in main branch.
    -> git status
    -> git add
    -> git commit -m “updated file”
    -> git push (repeat pull and push commands)
  11. Go to GitHub server and create pull request from conflict branch to main branch
    -> go to repository
    -> search your branch name and select the branch.
    -> if the branch is old, then it will show contribute button
    -> click on contribute button and click on ‘Open pull request’ button.
    -> Provide request details (reviewer, description assignee)
    -> click on create pull request button.
  12. It will show merge conflict between main branch and feature branch.
    -> ‘merge pull request’ button will be in disable state. This branch has conflicts that must be resolved
    Use the web editor or the command line to resolve conflicts before continuing. Deepesh/dy_conflict_file.txt

—— Resolve merge conflict locally ——

  1. Go back to git terminal
  2. switch to feature branch.
    -> git checkout dy_conflict_branch
  3. run a command on terminal to update feature branch with main branch
    -> git pull origin main
    -> it will show conflict message on terminal Auto-merging Deepesh/dy_conflict_file.txt CONFLICT (content): Merge conflict in Deepesh/dy_conflict_file.txt Automatic merge failed; fix conflicts and then commit the result.
  4. Open dy_conflict_file.txt on local machine, will show below content

var num1 = 10
if (num1%2 == 0) {

HEAD : change from feature BRANCH (dy_conflict_branch)

<<<<<<< HEAD
console.log(“This is even number, divisible by 2”)
} else {

console.log(“This is odd number, not divisible by 2”)

Changes from MAIN branch

console.log(“condition is True”)
console.log(“This is even number, can divide by 2”)
} else {
console.log(“condition is False”)
console.log(“This is odd number, can not divide by 2”)

9f9d33c6d4f9d945d512c3b40e36783b758295fd
}

  1. Update the file content as per your requirements. var num1 = 10
    if (num1%2 == 0) {
    console.log(“condition is True”)
    console.log(“This is even number, divisible by 2”)
    } else {
    console.log(“condition is False”)
    console.log(“This is odd number, not divisible by 2”)
    }
  2. go to git terminal and run below commands
    -> git status : It will show in red color
    -> git add
    -> git commit -m “resolved merge”
    -> git push
  3. Once the push is successful, merge will conflict will be resolved in pull request
    -> Now go back to git server and check pull request, there is no conflict anymore.
  4. We can merge changes from feature to main branch.

JavaScript Data Type Conversion

Data type conversion means changing a value from one type to another.

๐Ÿ‘‰ There are two types of conversion:

  1. Implicit Conversion (Type Coercion)
  2. Explicit Conversion (Type Casting)

๐Ÿ”น 1. Implicit Conversion (Automatic)

JavaScript automatically converts types when needed.

โœ… Example 1: String + Number

let result = "5" + 2;
console.log(result); // "52"

๐Ÿ‘‰ Number 2 is converted to string.


โœ… Example 2: Number – String

let result = "5" - 2;
console.log(result); // 3

๐Ÿ‘‰ String "5" is converted to number.


โœ… Example 3: Boolean Conversion

let result = true + 1;
console.log(result); // 2

๐Ÿ‘‰ true โ†’ 1, false โ†’ 0


โœ… Example 4: Null Conversion

let result = null + 5;
console.log(result); // 5

๐Ÿ‘‰ null behaves like 0


โš ๏ธ Strange Cases

console.log("5" * "2"); // 10
console.log("hello" * 2); // NaN

๐Ÿ‘‰ "hello" cannot be converted โ†’ NaN (Not a Number)


๐Ÿ”น 2. Explicit Conversion (Manual)

You manually convert using JavaScript functions.


โœ… Convert to Number

Using Number()

Number("123");    // 123
Number("abc"); // NaN
Number(true); // 1
Number(false); // 0

Using parseInt() and parseFloat()

parseInt("10.5");   // 10
parseFloat("10.5"); // 10.5

โœ… Convert to String

Using String()

String(123);      // "123"
String(true); // "true"

Using .toString()

let num = 100;
num.toString(); // "100"

โœ… Convert to Boolean

Using Boolean()

Boolean(1);        // true
Boolean(0); // false
Boolean(""); // false
Boolean("Hello"); // true
Boolean(null); // false
Boolean(undefined);// false

๐Ÿ”น Truthy vs Falsy Values

โŒ Falsy Values:

  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN
  • false

โœ… Truthy Values:

Everything else is true

Boolean("Hi"); // true
Boolean(100); // true

๐Ÿ”น Comparison with Type Coercion

== (Loose Equality)

console.log("5" == 5); // true

๐Ÿ‘‰ Converts types before comparison


=== (Strict Equality)

console.log("5" === 5); // false

๐Ÿ‘‰ No conversion โ†’ safer


๐Ÿง  Quick Summary

Conversion TypeExampleResult
Implicit"5" + 2"52"
Implicit"5" - 23
ExplicitNumber("10")10
ExplicitString(10)"10"
ExplicitBoolean(0)false

✎ Practise what you learned: 31 JavaScript type conversion programs with solutions →

JavaScript Data Types

JavaScript Data Types (Basics)

JavaScript data types define the kind of value a variable can hold.

๐Ÿ‘‰ There are two main categories:

  1. Primitive Data Types
  2. Non-Primitive (Reference) Data Types

๐Ÿ”น 1. Primitive Data Types

Primitive types store single values and are immutable.

โœ… 1. Number

Represents both integers and floating-point numbers.

let age = 25;
let price = 99.99;

โœ… 2. String

Represents text (inside quotes).

let name = "Deepesh";
let message = 'Hello World';

โœ… 3. Boolean

Represents true or false.

let isLoggedIn = true;
let isAdmin = false;

โœ… 4. Undefined

A variable declared but not assigned a value.

let x;
console.log(x); // undefined

โœ… 5. Null

Represents intentional absence of value.

let data = null;

โœ… 6. BigInt

Used for very large integers.

let bigNumber = 123456789012345678901234567890n;

โœ… 7. Symbol

Used for unique identifiers.

let id = Symbol("userId");

๐Ÿ”น 2. Non-Primitive (Reference) Data Types

These store collections or complex data.


โœ… 1. Object

Key-value pairs.

let user = {
name: "Deepesh",
age: 25,
isActive: true
};

โœ… 2. Array

Ordered list of values.

let fruits = ["apple", "banana", "mango"];

โœ… 3. Function

A block of reusable code.

function greet() {
return "Hello!";
}

๐Ÿ”น typeof Operator

Used to check the data type.

console.log(typeof 10);          // number
console.log(typeof "Hello"); // string
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof null); // object (known JS bug)
console.log(typeof {}); // object
console.log(typeof []); // object

โš ๏ธ Important Notes

  • null returns "object" โ†’ historical bug in JavaScript
  • Arrays are technically objects
  • Functions are also treated as objects

๐Ÿง  Quick Summary Table

TypeExample
Number10, 3.14
String"Hello"
Booleantrue, false
Undefinedlet x;
Nullnull
BigInt123n
SymbolSymbol("id")
Object{name: "John"}
Array[1,2,3]
Functionfunction(){}

๐Ÿš€ Simple Example Combining All

let user = {
name: "Deepesh", // string
age: 25, // number
isLoggedIn: true, // boolean
balance: 1000000000000000000n, // BigInt
id: Symbol("id"), // symbol
hobbies: ["coding", "music"], // array
address: null // null
};console.log(typeof user);

✎ Practise what you learned: 31 JavaScript data types programs with solutions →