30 Practice Questions (JavaScript)

🔹 🟢 Easy Level (1–10)

  1. Check if a number is positive or negative
  2. Check if a number is even or odd
  3. Check if a person is eligible to vote (18+)
  4. Find the largest of two numbers
  5. Print numbers from 1 to 10 using for loop
  6. Print numbers from 10 to 1 (reverse)
  7. Print even numbers from 1 to 20
  8. Print odd numbers from 1 to 20
  9. Take a number and print its square
  10. Check if a number is divisible by 5

🔹 🟡 Medium Level (11–20)

  1. Find the largest of three numbers
  2. Check if a number is multiple of 3 and 5
  3. Print numbers from 1 to N (user input)
  4. Find the sum of first N natural numbers
  5. Print the multiplication table of a number
  6. Count numbers from 1 to 50 divisible by 7
  7. Reverse a number (e.g., 123 → 321)
  8. Count digits in a number
  9. Check if a number is palindrome
  10. Print this pattern:
*
**
***
****
*****

🔹 🔴 Hard Level (21–30)

  1. Find the factorial of a number
  2. Check if a number is prime
  3. Print all prime numbers from 1 to 100
  4. Generate Fibonacci series up to N terms
  5. Print this pattern:
1
12
123
1234
12345
  1. Find the sum of digits of a number
  2. Find the largest digit in a number
  3. Create a simple calculator using switch ( + – * / )
  4. Guessing game with limited attempts (5 tries)
  5. Print this pattern:
*****
****
***
**
*

🎯 Bonus Challenge (for smart students)

👉 FizzBuzz (very popular interview question)

  • Print numbers 1–50
  • If divisible by 3 → “Fizz”
  • If divisible by 5 → “Buzz”
  • If both → “FizzBuzz”

3️⃣ Control Statements (Decision Making)

Control statements help your program make decisions based on conditions.


✅ 1. if Statement

Runs code only if condition is true

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

👉 If condition is true → code runs
👉 If false → nothing happens


✅ 2. if...else

Runs one block if true, another if false

let age = 16;if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}

✅ 3. else if

Used when checking multiple conditions

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

✅ 4. switch Statement

Better alternative when checking many fixed values

let day = 2;switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}

👉 break stops execution
👉 Without break, next cases also run


🔹 🔁 Loops (Repeat Code)

Loops help run code multiple times automatically


✅ 1. for Loop

Used when you know how many times to run

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

👉 Output: 1 2 3 4 5


✅ 2. while Loop

Runs while condition is true

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

✅ 3. do...while

Runs at least once, even if condition is false

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

✅ 4. break

Stops loop immediately

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

👉 Output: 1 2 3 4


✅ 5. continue

Skips one iteration

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

👉 Output: 1 2 4 5


🧠 Practice Programs


🎯 1. Number Guessing Game

let secret = 7;
let guess;while (guess !== secret) {
guess = Number(prompt("Guess a number (1-10):")); if (guess === secret) {
console.log("🎉 Correct!");
} else {
console.log("❌ Try again");
}
}

👉 Concepts used:

  • while loop
  • if else

🎯 2. Multiplication Table Generator

let num = Number(prompt("Enter a number:"));for (let i = 1; i <= 10; i++) {
console.log(num + " x " + i + " = " + (num * i));
}

👉 Output example for 5:

5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50

2️⃣ JavaScript Basics

🔹 1. Variables

Variables are used to store data.

✅ var

  • Old way to declare variables
  • Function-scoped (not block-scoped)
var name = "Aditya";

✅ let

  • Modern way (recommended)
  • Block-scoped
  • Value can be changed
let age = 25;
age = 30;

✅ const

  • Block-scoped
  • Value cannot be reassigned
const pi = 3.14;

🔹 2. Data Types

📌 String

Text values

let name = "Aditya";

📌 Number

Numbers (integer or decimal)

let marks = 95;
let price = 99.99;

📌 Boolean

True or False

let isLogin = true;

📌 Undefined

Variable declared but not assigned

let x;

📌 Null

Empty value (intentionally)

let data = null;

📌 Object

Collection of key-value pairs

let user = {
name: "Aditya",
age: 25
};

📌 Array

List of values

let fruits = ["Apple", "Banana", "Mango"];

🔹 3. Operators

➕ Arithmetic Operators

Used for calculations

let a = 10;
let b = 5;console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2

🔍 Comparison Operators

Compare values (returns true/false)

console.log(10 == "10");   // true (loose)
console.log(10 === "10"); // false (strict)
console.log(10 > 5); // true

🔗 Logical Operators

Used with conditions

let age = 20;console.log(age > 18 && age < 30); // true
console.log(age > 18 || age < 10); // true
console.log(!(age > 18)); // false

📝 Assignment Operators

Assign values

let x = 10;
x += 5; // x = x + 5 → 15
x -= 2; // 13

🔹 4. Type Conversion

📌 Convert to String

let num = 100;
String(num); // "100"

📌 Convert to Number

let str = "50";
Number(str); // 50

📌 Convert to Boolean

Boolean(1); // true
Boolean(0); // false

🧪 Practice Programs

✅ 1. Calculator Program

let a = 10;
let b = 5;console.log("Add:", a + b);
console.log("Subtract:", a - b);
console.log("Multiply:", a * b);
console.log("Divide:", a / b);

👉 Advanced (User Input)

let num1 = Number(prompt("Enter first number:"));
let num2 = Number(prompt("Enter second number:"));alert("Sum = " + (num1 + num2));

✅ 2. Temperature Converter

Celsius to Fahrenheit

let c = 30;
let f = (c * 9/5) + 32;console.log("Fahrenheit:", f);

Fahrenheit to Celsius

let f = 86;
let c = (f - 32) * 5/9;console.log("Celsius:", c);

JavaScript has different types of operators used to perform operations on values and variables. Here’s a complete, clean guide 👇


🔷 1. Arithmetic Operators

Used for mathematical calculations.

OperatorMeaningExample
+Addition5 + 2 = 7
-Subtraction5 - 2 = 3
*Multiplication5 * 2 = 10
/Division5 / 2 = 2.5
%Modulus (remainder)5 % 2 = 1
**Exponentiation2 ** 3 = 8
++Incrementx++
--Decrementx--

🔷 2. Assignment Operators

Used to assign values.

OperatorExampleMeaning
=x = 5Assign
+=x += 2x = x + 2
-=x -= 2x = x - 2
*=x *= 2x = x * 2
/=x /= 2x = x / 2
%=x %= 2x = x % 2
**=x **= 2x = x ** 2

🔷 3. Comparison Operators

Used to compare values (result = true/false).

OperatorExampleResult
==5 == "5"true ⚠️
===5 === "5"false ✅
!=5 != 3true
!==5 !== "5"true
>5 > 3true
<5 < 3false
>=5 >= 5true
<=5 <= 3false

👉 Always prefer === (strict equality)


🔷 4. Logical Operators

Used with boolean values.

OperatorMeaningExample
&&ANDtrue && false → false
||OR`true || false → false
!NOT!true → false

🔷 5. Bitwise Operators

Work on binary numbers.

OperatorExample
&AND
``
^XOR
~NOT
<<Left shift
>>Right shift

🔷 6. String Operators

let name = "Aditya" + " Singh";

👉 Output: "Aditya Singh"


🔷 7. Ternary Operator

Shortcut for if-else.

let result = age >= 18 ? "Adult" : "Minor";

🔷 8. Type Operators

OperatorExample
typeoftypeof "Hello"
instanceofobj instanceof Array

🔷 9. Nullish & Optional Operators (Modern JS)

OperatorMeaning
??Nullish coalescing
?.Optional chaining

Example:

let user = null;
console.log(user?.name); // undefined

🔷 10. Spread & Rest Operators

let arr = [1, 2, 3];
let newArr = [...arr, 4];

🔷 11. Comma Operator

let x = (1, 2, 3);
console.log(x); // 3

1️⃣ Introduction to JavaScript

✅ What is JavaScript?

JavaScript is a programming language used to make websites interactive and dynamic.

👉 Without JavaScript:

  • Website = Static (only text, images)

👉 With JavaScript:

  • Buttons respond
  • Forms validate
  • Animations work
  • Data updates without reload

📌 Example:

<button onclick="alert('Hello!')">Click Me</button>

📜 History of JavaScript

  • Created in 1995 by Brendan Eich
  • Developed at Netscape
  • Initially called Mocha, then LiveScript
  • Finally named JavaScript

👉 Important:

  • JavaScript is NOT Java
  • Name was for marketing 😄

📈 Today:

  • Runs in browsers
  • Also runs on servers (Node.js)

⚔️ JavaScript vs HTML vs CSS

TechnologyPurpose
HTMLStructure (Skeleton)
CSSDesign (Styling)
JavaScriptBehavior (Brain)

👉 Example:

<h1>Hello</h1>      <!-- HTML -->
<style>h1{color:red}</style> <!-- CSS -->
<script>alert('Hi')</script> <!-- JavaScript -->

🌐 How JavaScript Works in Browser

  1. Browser loads HTML
  2. Parses HTML → creates DOM
  3. Loads CSS
  4. Executes JavaScript

👉 JavaScript can:

  • Change HTML
  • Change CSS
  • Handle events

📌 Example:

<p id="demo">Hello</p><script>
document.getElementById("demo").innerHTML = "Changed!";
</script>

⚙️ JavaScript Engines

JavaScript engine = program that runs JS code

Popular Engines:

  • V8 → Chrome, Edge
  • SpiderMonkey → Firefox
  • JavaScriptCore → Safari

👉 What engine does:

  • Reads code
  • Converts to machine code
  • Executes fast

🧪 Writing First JavaScript Program

👉 Example:

console.log("Hello, World!");

📌 Output:

  • Appears in browser console

👉 Another example:

alert("Welcome to JavaScript!");

🔗 Adding JavaScript to HTML

There are 3 ways:


1️⃣ Inline JavaScript

👉 JS written inside HTML tag

<button onclick="alert('Clicked!')">Click</button>

📌 Use:

  • Small actions

❌ Not recommended for large projects


2️⃣ Internal JavaScript

👉 JS written inside <script> tag

<!DOCTYPE html>
<html>
<head>
</head>
<body><script>
alert("Internal JS");
</script></body>
</html>

📌 Best for:

  • Small to medium scripts

3️⃣ External JavaScript

👉 JS in separate .js file

HTML:

<script src="script.js"></script>

script.js:

alert("External JS");

📌 Best for:

  • Large projects
  • Clean code
  • Reusability

🚀 Summary

  • JavaScript makes websites interactive
  • Works with HTML & CSS
  • Runs inside browser using engines
  • Can be added in 3 ways:
    • Inline
    • Internal
    • External (best practice)

Change text according to days using JavaScript

<section class="hero bg-theme text-center">
  <div class="container">
<h2 id="dailyTitle" class="section-title h3 mb-2"></h2>
<p id="dailySubtitle" class="lead text-soft mb-3"></p>
<a href="https://soatechnology.net/ai/today-quote" class="btn btn-primary btn-lg">📜 उद्धरण</a>
  </div>
</section>
<script>
  const dailyTexts = [
    {
      title: "आज का प्रेरणादायक विचार",
      subtitle: "सकारात्मकता • जीवन • कर्म • प्रेरणा"
    },
    {
      title: "आज का शुभ संदेश",
      subtitle: "शांति • विश्वास • आत्म-चिंतन"
    },
    {
      title: "आज का सुविचार",
      subtitle: "प्रेरणा • आत्मविश्वास • सफलता"
    },
    {
      title: "आज का विचार",
      subtitle: "जीवन • अनुभव • सीख"
    },
    {
      title: "आज का संदेश",
      subtitle: "धैर्य • आशा • विश्वास"
    },
    {
      title: "आज की प्रेरणा",
      subtitle: "सपने • मेहनत • लक्ष्य"
    },
    {
      title: "आज का जीवन मंत्र",
      subtitle: "कर्म • संतुलन • सकारात्मक सोच"
    }
  ];

  const today = new Date().getDay(); // 0–6
  const text = dailyTexts[today];

  document.getElementById("dailyTitle").innerText = text.title;
  document.getElementById("dailySubtitle").innerText = text.subtitle;
</script>

Password Strength Tester

Password Strength Tester

Strength: Weak

Introduction to Cybersecurity

Cybersecurity is the practice of protecting systems, networks, and data from digital attacks. These attacks are usually aimed at accessing, changing, or destroying sensitive information.

Confidentiality: Protects data from unauthorized access.

Integrity: Keeps information accurate and unchanged.

Availability: Ensures data and systems are accessible when needed.

2. Common Cyber Threats

  • Malware (Viruses, Worms, Trojans)
  • Phishing (Fake emails to steal information)
  • DDoS Attacks (Overloading servers)
  • SQL Injection (Database manipulation)
  • Man-in-the-Middle Attack (Intercepting communications)

3. Defense Strategies

  1. Use strong passwords and 2FA
  2. Install antivirus and firewall
  3. Encrypt data and backup regularly
  4. Keep software updated
  5. Be aware of phishing scams

How to Download the current HTML as a file using JavaScript

      <div class=”text-right mt-4″>

        <button id=”downloadBtn” class=”btn btn-outline-secondary”>Download HTML</button>

      </div>

  
<script>
    // Download the current HTML as a file
    document.getElementById('downloadBtn').addEventListener('click', function () {
      const html = document.documentElement.outerHTML;
      const blob = new Blob([html], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'born_on_1st_profile.html';
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    });
  </script>

add underscore between words javascript

To add underscores between words in a JavaScript string, effectively replacing spaces with underscores, you can use the replace() or replaceAll() methods, or a combination of split() and join().

1. Using replace() with a Regular Expression:

This method uses a regular expression to find all occurrences of spaces and replaces them with an underscore. The /g flag ensures a global replacement (all occurrences, not just the first).

JavaScript

let str = "This is a sample string";
let result = str.replace(/ /g, "_");
console.log(result); // Output: This_is_a_sample_string

2. Using replaceAll():

The replaceAll() method directly replaces all occurrences of a specified substring with another.

JavaScript

let str = "Another example string";
let result = str.replaceAll(" ", "_");
console.log(result); // Output: Another_example_string

3. Using split() and join():

This method first splits the string into an array of words using space as a delimiter, and then joins the array elements back into a string using an underscore as the separator.

JavaScript

let str = "Words separated by spaces";
let result = str.split(" ").join("_");
console.log(result); // Output: Words_separated_by_spaces

How can create user preferences in JavaScript by storing the choice when the user clicks something, and then reloading it whenever the page is opened again

You can create user preferences in JavaScript by storing the choice when the user clicks something, and then reloading it whenever the page is opened again. The usual way is to use localStorage or cookies.

Here’s a step-by-step example:


Example: Save User Theme Preference (Dark/Light Mode)

HTML

<button id="themeToggle">Toggle Theme</button>
<p>Hello! This text will change theme.</p>

JavaScript

// Get saved preference (if any)
let userPref = localStorage.getItem("theme");
 document.cookie = "theme=light; path=/";

// Apply saved preference
if (userPref === "dark") {
  document.body.classList.add("dark");
  document.cookie = "theme=dark; path=/";
}

// Button click event
document.getElementById("themeToggle").addEventListener("click", () => {
  document.body.classList.toggle("dark");

  // Save user preference
  if (document.body.classList.contains("dark")) {
    localStorage.setItem("theme", "dark");
 document.cookie = "theme=dark; path=/";
  } else {
    localStorage.setItem("theme", "light");
 document.cookie = "theme=light; path=/";
  }
});

CSS

body {
  background: white;
  color: black;
}
body.dark {
  background: black;
  color: white;
}

How It Works

  1. When the user clicks the button → we toggle a CSS class.
  2. Save the preference in localStorage.
  3. Next time the user reloads, we restore the preference from localStorage.

how to create user preference in JavaScript on webpage click

<button id="themeToggle">Toggle Theme</button>
<p>Hello! This text will change theme.</p>
<style>
body {
  background: white;
  color: black;
}
body.dark {
  background: black;
  color: white;
}

</style>
<script>
// Get saved preference (if any)
let userPref = localStorage.getItem("theme");
 document.cookie = "theme=light; path=/";
// Apply saved preference
if (userPref === "dark") {
  document.body.classList.add("dark");
  document.cookie = "theme=dark; path=/";
}

// Button click event
document.getElementById("themeToggle").addEventListener("click", () => {
  document.body.classList.toggle("dark");

  // Save user preference
  if (document.body.classList.contains("dark")) {
    localStorage.setItem("theme", "dark");
    document.cookie = "theme=dark; path=/";
  } else {
    localStorage.setItem("theme", "light");
    document.cookie = "theme=light; path=/";
  }
});

</script>