Write a program to check three digit number is Armstrong or not without using if and loop only using ternary operator

<html>
<head><title> </title>
</title></head>
<body>
<script>
num=prompt("Enter the 3-digit number");
num=parseInt(num);
org=num;
res=0;
q=parseInt(num/10);
r=num%10;
res+=r*r*r;
num=q;
q=parseInt(num/10);
r=num%10;
res+=r*r*r;
num=q;
q=parseInt(num/10);
r=num%10;
res+=r*r*r;
num=q;
console.log(num);
result=org==res?"Armstrong":"not";
document.write(result);
</script>

</body>
</html>

associativity and precedence in javascript

In JavaScript, operator precedence and associativity determine how expressions are evaluated when multiple operators are used together.


🔷 1. Operator Precedence (Priority)

Precedence defines which operator is executed first in an expression.

👉 Higher precedence = executed first
👉 Lower precedence = executed later

Example:

let result = 10 + 5 * 2;

👉 Here:

  • * has higher precedence than +
  • So calculation is:
5 * 2 = 10
10 + 10 = 20

✅ Output: 20


🔹 Common Precedence Order (High → Low)

OperatorDescription
()Parentheses
++ --Increment/Decrement
* / %Multiplication
+ -Addition/Subtraction
< > <= >=Comparison
== ===Equality
&&Logical AND
`
=Assignment

Example with Parentheses:

let result = (10 + 5) * 2;

👉 Parentheses override precedence:

10 + 5 = 15
15 * 2 = 30

✅ Output: 30


🔷 2. Associativity (Direction of Evaluation)

When operators have same precedence, associativity decides left-to-right or right-to-left evaluation.


🔹 Left-to-Right Associativity

Most operators follow this.

Example:

let result = 10 - 5 - 2;

👉 Evaluation:

10 - 5 = 5
5 - 2 = 3

✅ Output: 3


🔹 Right-to-Left Associativity

Assignment operators follow this.

Example:

let a, b, c;
a = b = c = 10;

👉 Evaluation:

c = 10
b = 10
a = 10

✅ Output:

a = 10, b = 10, c = 10

🔷 Combined Example

let result = 10 + 5 * 2 ** 2;

👉 Step-by-step:

  1. ** → 2² = 4
  2. * → 5 × 4 = 20
  3. + → 10 + 20 = 30

✅ Output: 30


🔷 Key Points to Remember

✔ Precedence = priority of operators
✔ Associativity = direction of execution
✔ Use () to control evaluation
✔ Always use parentheses for clarity in complex expressions


🔷 Simple Trick 💡

👉 BODMAS works here too:

Brackets → Orders (powers) → Division/Multiplication → Addition/Subtraction

🔷 JavaScript Associativity Table

OperatorDescriptionAssociativity
()GroupingLeft → Right
[]Array accessLeft → Right
.Object propertyLeft → Right
++ -- (postfix)Increment/DecrementLeft → Right
++ -- (prefix)Increment/DecrementRight → Left
! ~ + - typeofUnary operatorsRight → Left
**ExponentiationRight → Left ⚠️
* / %MultiplicationLeft → Right
+ -Addition/SubtractionLeft → Right
< <= > >=ComparisonLeft → Right
== != === !==EqualityLeft → Right
&&Logical ANDLeft → Right
``
??Nullish CoalescingLeft → Right
?:Ternary operatorRight → Left
=AssignmentRight → Left
+= -= *= /=Compound assignmentRight → Left
,Comma operatorLeft → Right

🔷 Important Cases (Must Know)

1️⃣ Exponentiation (Right → Left)

let result = 2 ** 3 ** 2;

👉 Evaluates as:

2 ** (3 ** 2) = 2 ** 9 = 512

2️⃣ Assignment (Right → Left)

let a, b, c;
a = b = c = 5;

👉 Works as:

c = 5 → b = 5 → a = 5

3️⃣ Ternary Operator

let result = true ? 1 : false ? 2 : 3;

👉 Evaluates Right → Left


🔷 Quick Memory Trick 💡

  • Most operators → Left to Right
  • Exceptions (Right to Left):
    • **
    • =
    • ?:
    • Unary operators (!, typeof, etc.)

1️⃣7️⃣ Final Projects (Portfolio Level)

These Final Projects (Portfolio Level) are meant to show real-world skills—the kind companies actually look for. I’ll explain each one in a practical way so your students understand what to build + what they learn.


1️⃣ E-commerce Product Filter 🛒

📌 What it is:

A shopping page where users can filter products by:

  • Price
  • Category
  • Rating
  • Search keyword

⚙️ Features:

  • Filter products dynamically (no page reload)
  • Sort (Low → High, High → Low)
  • Search bar
  • Category buttons (Electronics, Clothes, etc.)

🧠 Skills Learned:

  • Array filtering (filter())
  • DOM manipulation
  • Event handling
  • JSON data handling

💡 Example:

Flipkart / Amazon product filtering


2️⃣ Chat Application 💬

📌 What it is:

A real-time messaging app like WhatsApp (basic version)

⚙️ Features:

  • Send & receive messages
  • User name input
  • Chat UI (left/right messages)
  • Timestamp

🚀 Advanced (optional):

  • Real-time chat using Firebase / Socket.io
  • Online/offline status

🧠 Skills Learned:

  • Event handling
  • Real-time data (if using Firebase)
  • UI rendering

3️⃣ Blog System 📝

📌 What it is:

A mini blogging platform

⚙️ Features:

  • Create post (title + content)
  • Edit/Delete post
  • Display all blogs
  • Search blog

🚀 Advanced:

  • Login system
  • Save data in database (MongoDB / Firebase)

🧠 Skills Learned:

  • CRUD operations (Create, Read, Update, Delete)
  • Forms handling
  • LocalStorage / backend basics

4️⃣ Movie Search App 🎬

📌 What it is:

Search movies using API (like IMDb)

⚙️ Features:

  • Search movie by name
  • Show:
    • Poster
    • Rating
    • Release date
  • Responsive UI

🔗 API Example:

  • OMDB API (free)

🧠 Skills Learned:

  • Fetch API / AJAX
  • Working with APIs
  • JSON parsing
  • Async JavaScript

5️⃣ Online Code Editor 💻

📌 What it is:

A browser-based coding tool like CodePen

⚙️ Features:

  • Write HTML, CSS, JS
  • Live preview output
  • Run button
  • Clear/reset

🚀 Advanced:

  • Syntax highlighting (Monaco Editor)
  • Save code

🧠 Skills Learned:

  • iframe usage
  • Live rendering
  • Advanced DOM handling

🔥 Final Advice for Students

These are portfolio projects, so:

  • UI should look professional
  • Code should be clean & structured
  • Add project to GitHub + live demo
  • Write a short description

1️⃣6️⃣ Mini Projects (Important for Students)

These mini projects are perfect for students because they combine real-world logic + JavaScript practice. I’ll explain each one in a simple way so you understand what to build + what concepts you’ll learn.


1️⃣ Calculator

What it is:
A simple calculator that performs +, −, ×, ÷

Features:

  • Number buttons (0–9)
  • Operators (+, -, *, /)
  • Display screen
  • Equal (=) and Clear (C)

What students learn:

  • DOM manipulation
  • Event handling (button clicks)
  • Basic logic & conditions
  • Functions

2️⃣ Digital Clock

What it is:
A live clock showing current time (HH:MM:SS)

Features:

  • Real-time updating clock
  • Optional: date display

What students learn:

  • Date() object
  • setInterval()
  • Formatting time

3️⃣ Todo List

What it is:
A task manager where users can add/remove tasks

Features:

  • Add task
  • Delete task
  • Mark as completed
  • Save tasks (localStorage)

What students learn:

  • Arrays & objects
  • Local Storage
  • Dynamic UI updates

4️⃣ Quiz App

What it is:
A multiple-choice quiz system

Features:

  • Questions with options
  • Score calculation
  • Next/Previous buttons
  • Final result display

What students learn:

  • Arrays of objects
  • Conditional logic
  • State management

5️⃣ Password Generator

What it is:
Generates strong random passwords

Features:

  • Choose length
  • Include uppercase/lowercase/numbers/symbols
  • Copy to clipboard

What students learn:

  • Random functions (Math.random())
  • String manipulation
  • Checkbox inputs

6️⃣ Notes App

What it is:
A simple note-taking app

Features:

  • Add/edit/delete notes
  • Auto-save notes
  • Search notes

What students learn:

  • CRUD operations (Create, Read, Update, Delete)
  • LocalStorage / JSON
  • UI design thinking

7️⃣ Weather App

What it is:
Shows weather based on city or current location

Features:

  • Search city
  • Display temperature, humidity, condition
  • Weather icons

What students learn:

  • API integration
  • Fetch/AJAX
  • Async JavaScript (fetch, async/await)

8️⃣ Expense Tracker

What it is:
Track income and expenses

Features:

  • Add income/expense
  • Show balance
  • Transaction history
  • Charts (optional)

What students learn:

  • Data handling
  • Calculations
  • Local storage
  • UI + logic combination

🔥 Why these projects are important

  • Build real-world skills
  • Improve problem-solving
  • Help in job interviews
  • Make portfolio strong
  • Increase AdSense earning potential (for your site)

JavaScript OOP MCQ Test

🧠 JavaScript OOP MCQ Test (25 Questions)

🟢 Basic Level

1. What is OOP?

A. Programming with loops
B. Programming with objects
C. Programming with HTML
D. None
👉 Answer: B


2. Which keyword is used to create a class?

A. function
B. object
C. class
D. define
👉 Answer: C


3. What is an object?

A. Function
B. Instance of class
C. Loop
D. Variable
👉 Answer: B


4. Which method runs automatically when object is created?

A. init()
B. start()
C. constructor()
D. create()
👉 Answer: C


5. What does this refer to?

A. Global object
B. Current object
C. Function
D. Class
👉 Answer: B


🟡 Intermediate Level

6. Which keyword is used for inheritance?

A. inherit
B. extends
C. super
D. prototype
👉 Answer: B


7. What is encapsulation?

A. Looping
B. Hiding data
C. Printing output
D. Debugging
👉 Answer: B


8. Private fields are declared using?

A. _
B. $
C. #
D. @
👉 Answer: C


9. What is polymorphism?

A. Same function, different behavior
B. Same output
C. Same variable
D. Same loop
👉 Answer: A


10. Which method overrides parent method?

A. Same name method in child
B. New method
C. Static method
D. Private method
👉 Answer: A


11. What is prototype?

A. Loop
B. Object mechanism for inheritance
C. Function
D. Array
👉 Answer: B


12. What is super used for?

A. Create object
B. Call parent class
C. Delete object
D. Print value
👉 Answer: B


13. Which is correct?

A. JS supports class-based inheritance only
B. JS uses prototype-based inheritance
C. JS has no inheritance
D. None
👉 Answer: B


14. What is a method?

A. Property
B. Function inside object/class
C. Loop
D. Variable
👉 Answer: B


15. Which creates object?

A. new
B. create
C. make
D. object
👉 Answer: A


🔴 Advanced Level

16. Static methods belong to?

A. Object
B. Class
C. Function
D. Array
👉 Answer: B


17. Getters are used to?

A. Set values
B. Get values
C. Delete values
D. Loop values
👉 Answer: B


18. Setters are used to?

A. Get values
B. Set values
C. Print values
D. Loop values
👉 Answer: B


19. What is abstraction?

A. Showing all details
B. Hiding complexity
C. Looping
D. Debugging
👉 Answer: B


20. JavaScript supports multiple inheritance?

A. Yes
B. No
C. Sometimes
D. Only in ES5
👉 Answer: B


21. What is method chaining?

A. Calling methods in sequence
B. Looping
C. Debugging
D. None
👉 Answer: A


22. __proto__ refers to?

A. Class
B. Object reference
C. Loop
D. Variable
👉 Answer: B


23. Classes in JS are?

A. Real classes
B. Syntactic sugar
C. Functions only
D. Variables
👉 Answer: B


24. Which is NOT OOP concept?

A. Inheritance
B. Encapsulation
C. Looping
D. Polymorphism
👉 Answer: C


25. Which is correct syntax?

A. class = Person {}
B. class Person {}
C. Person class {}
D. define class Person {}
👉 Answer: B


JavaScript OOP Interview Questions from basic to advanced

🟢 Basic Level Questions

1. What is OOP in JavaScript?

👉 A programming paradigm based on objects and classes to structure code.


2. What is a class in JavaScript?

👉 A blueprint to create objects using properties and methods.


3. What is an object?

👉 An instance of a class that contains data (properties) and behavior (methods).


4. What is a constructor?

👉 A special method used to initialize object values when created.


5. What is this keyword?

👉 Refers to the current object.


6. Difference between class and object?

👉 Class = blueprint
👉 Object = real instance


🟡 Intermediate Level Questions

7. What is inheritance?

👉 Mechanism to reuse code from another class using extends.


8. What is encapsulation?

👉 Wrapping data and methods together and restricting direct access.


9. What are private fields in JS?

👉 Variables declared using # and cannot be accessed outside the class.


10. What is polymorphism?

👉 Same method behaves differently in different classes.


11. What is method overriding?

👉 Redefining a parent class method in a child class.

class Animal {
speak() {
console.log("Animal sound");
}
}class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}

12. What is the difference between function constructor and class?

👉 Both create objects, but:

  • Class = modern, cleaner syntax
  • Function constructor = older way

13. What is prototype in JavaScript?

👉 Mechanism by which objects inherit features from another object.


14. What is prototype chain?

👉 Chain of objects used to resolve properties.


15. Difference between __proto__ and prototype?

👉 prototype → property of constructor
👉 __proto__ → reference of object


🔴 Advanced Level Questions

16. What is static method?

👉 Method belongs to class, not object.

class MathUtil {
static add(a, b) {
return a + b;
}
}MathUtil.add(2, 3);

17. What is abstraction?

👉 Hiding implementation details and showing only essential features.


18. Can JavaScript support multiple inheritance?

👉 ❌ No (directly)
👉 ✅ Can be done using mixins


19. What are getters and setters?

👉 Methods to get/set values safely.

class Person {
constructor(name) {
this._name = name;
} get name() {
return this._name;
} set name(value) {
this._name = value;
}
}

20. What is method chaining?

👉 Calling multiple methods in one line.

obj.method1().method2().method3();

21. What is super keyword?

👉 Used to call parent class constructor/method.


22. Difference between shallow copy and deep copy?

👉 Shallow → reference copy
👉 Deep → full independent copy


23. How does JavaScript implement OOP internally?

👉 Using prototype-based inheritance


24. What is mixin?

👉 Technique to add reusable functionality to classes.


25. What are ES6 classes syntactic sugar for?

👉 Prototype-based inheritance


🔥 Bonus Practical Question

26. Create a class with inheritance example

👉 Very common in interviews:

class Vehicle {
constructor(name) {
this.name = name;
} start() {
console.log(this.name + " starting...");
}
}class Car extends Vehicle {
drive() {
console.log(this.name + " driving...");
}
}const c = new Car("BMW");
c.start();
c.drive();

💡 Pro Tip (For Interviews)

Interviewers often check:

  • Clear concept understanding
  • Real-life examples
  • Ability to write small code

1️⃣5️⃣ JavaScript OOP

1️⃣ JavaScript OOP (Overview)

OOP is a way of writing code using objects and classes to organize and reuse logic.

Instead of writing everything in functions, we create blueprints (classes) and objects (instances).


2️⃣ Classes

A class is a blueprint to create objects.

Example:

class Person {
greet() {
console.log("Hello!");
}
}const p1 = new Person();
p1.greet(); // Hello!

👉 Person is a class
👉 p1 is an object (instance)


3️⃣ Constructor

A constructor is a special method that runs automatically when an object is created.

Used to initialize values.

Example:

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
} show() {
console.log(this.name, this.age);
}
}const p1 = new Person("Aditya", 25);
p1.show(); // Aditya 25

👉 this refers to the current object


4️⃣ Inheritance

Inheritance allows one class to reuse properties and methods of another class.

Example:

class Animal {
speak() {
console.log("Animal makes sound");
}
}class Dog extends Animal {
bark() {
console.log("Dog barks");
}
}const d = new Dog();
d.speak(); // inherited
d.bark(); // own method

👉 extends is used for inheritance


5️⃣ Encapsulation

Encapsulation means hiding data and controlling access.

In JavaScript, we use private fields (#).

Example:

class BankAccount {
#balance = 0; // private deposit(amount) {
this.#balance += amount;
} getBalance() {
return this.#balance;
}
}const acc = new BankAccount();
acc.deposit(1000);console.log(acc.getBalance()); // 1000
// console.log(acc.#balance); ❌ Error (private)

👉 Data is protected from direct access


6️⃣ Polymorphism

Polymorphism means same method, different behavior.

Example:

class Animal {
speak() {
console.log("Animal sound");
}
}class Dog extends Animal {
speak() {
console.log("Dog barks");
}
}class Cat extends Animal {
speak() {
console.log("Cat meows");
}
}const animals = [new Dog(), new Cat()];animals.forEach(a => a.speak());

👉 Output:

Dog barks
Cat meows

👉 Same method speak() behaves differently


🔥 Quick Summary

ConceptMeaning
ClassBlueprint for objects
ConstructorInitialize values
InheritanceReuse code from parent class
EncapsulationHide and protect data
PolymorphismSame method, different behavior

30 practice questions on error handling

🚀 JavaScript Error Handling – 30 Practice Questions

🔹 Beginner Level (1–10)

1.

Write a program that divides two numbers using try...catch and handles division by zero.

2.

Create a try...catch block to handle an undefined variable error.

3.

Write code that parses invalid JSON and catches the error.

4.

Use finally to print “Execution Completed” whether error occurs or not.

5.

Create a function that throws an error if a number is negative.

6.

Handle an error when accessing a property of undefined.

7.

Write a program that catches invalid user input (non-number).

8.

Use try...catch to handle NaN results.

9.

Create a custom error using throw for empty string input.

10.

Write a program where catch prints only error.message.


🔹 Intermediate Level (11–20)

11.

Create a function that checks age and throws error if age < 18.

12.

Write a program to validate email format using throw.

13.

Handle JSON API response errors using try...catch.

14.

Create nested try...catch blocks.

15.

Write a function that throws different errors for:

  • negative number
  • zero
  • valid number

16.

Use finally to close a simulated database connection.

17.

Handle array index out-of-bound error manually.

18.

Create a calculator that throws error for invalid operator.

19.

Write code that re-throws an error after catching it.

20.

Handle missing function arguments using throw.


🔹 Advanced Level (21–30)

21.

Create a custom error class using class extends Error.

22.

Handle asynchronous errors using try...catch with async/await.

23.

Write an API call using fetch and handle network errors.

24.

Create a retry mechanism if API fails (use error handling).

25.

Differentiate between SyntaxError, ReferenceError, and TypeError in code.

26.

Log errors to console and also store them in an array.

27.

Create a global error handler for a web app.

28.

Write a function that validates multiple fields and throws combined errors.

29.

Handle file upload errors (simulate using conditions).

30.

Build a form validator that:

  • throws errors
  • catches them
  • displays user-friendly messages

💡 Bonus Tip (Important)

👉 In real projects:

  • Use try...catch for runtime errors
  • Use throw new Error() for custom validation
  • Use finally for cleanup tasks

1️⃣4️⃣ JavaScript Error Handling

JavaScript Error Handling helps you manage runtime errors so your program doesn’t crash unexpectedly. Let’s break down each keyword clearly:


🔹 1. try

The try block contains code that might cause an error.

👉 JavaScript will attempt to run this code.

try {
let result = 10 / x; // x is not defined → error
}

🔹 2. catch

The catch block runs if an error occurs in try.

👉 It receives the error object (you can name it anything, usually err).

try {
let result = 10 / x;
} catch (err) {
console.log("Error occurred:", err.message);
}

✔ Output:

Error occurred: x is not defined

🔹 3. finally

The finally block always executes, whether an error happens or not.

👉 Useful for cleanup tasks (closing connections, stopping loaders, etc.)

try {
console.log("Trying...");
} catch (err) {
console.log("Error:", err.message);
} finally {
console.log("This always runs");
}

✔ Output:

Trying...
This always runs

🔹 4. throw

The throw statement is used to create your own custom error.

👉 You can throw:

  • String
  • Number
  • Boolean
  • Object (best practice: use Error)
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older");
}
return "Access granted";
}try {
console.log(checkAge(16));
} catch (err) {
console.log(err.message);
}

✔ Output:

You must be 18 or older

🔥 Full Example (All Together)

try {
let age = 15; if (age < 18) {
throw new Error("Underage user");
} console.log("Access granted");} catch (err) {
console.log("Caught error:", err.message);} finally {
console.log("Execution finished");
}

🧠 Key Points

  • try → test code
  • catch → handle errors
  • finally → always runs
  • throw → create custom errors

🚀 Interview Tip

  • Always use Error object in throw:
throw new Error("Something went wrong");

1️⃣3️⃣ Local Storage (Browser Storage)

Local Storage allows you to save data in the user’s browser so it persists even after page refresh or closing the browser.

There are two types:


🔹 1. localStorage

  • Stores data permanently (until manually deleted)
  • Data stays even after browser is closed

✅ Syntax:

// Save data
localStorage.setItem("key", "value");// Get data
localStorage.getItem("key");// Remove one item
localStorage.removeItem("key");// Clear all
localStorage.clear();

📌 Example:

localStorage.setItem("username", "Aditya");let user = localStorage.getItem("username");
console.log(user); // Aditya

🔹 2. sessionStorage

  • Stores data temporarily
  • Data is deleted when the tab is closed

✅ Syntax:

sessionStorage.setItem("key", "value");
sessionStorage.getItem("key");
sessionStorage.removeItem("key");
sessionStorage.clear();

📌 Example:

sessionStorage.setItem("theme", "dark");let theme = sessionStorage.getItem("theme");
console.log(theme); // dark

🔥 Key Difference

FeaturelocalStoragesessionStorage
LifetimePermanentTab session only
Storage Limit~5MB~5MB
AccessibleSame origin onlySame origin only

💡 Important Notes

  • Data is stored as strings only
  • To store objects/arrays → use JSON.stringify()

Example:

let user = {name: "Aditya", age: 22};// Save
localStorage.setItem("user", JSON.stringify(user));// Get
let data = JSON.parse(localStorage.getItem("user"));
console.log(data.name);

🧪 Practice: Todo App with Local Storage

🎯 Goal:

  • Add tasks
  • Delete tasks
  • Save tasks in localStorage
  • Load tasks on refresh

✅ Basic HTML

<input type="text" id="taskInput" placeholder="Enter task">
<button onclick="addTask()">Add</button><ul id="taskList"></ul>

✅ JavaScript

let tasks = JSON.parse(localStorage.getItem("tasks")) || [];function displayTasks() {
let list = document.getElementById("taskList");
list.innerHTML = ""; tasks.forEach((task, index) => {
let li = document.createElement("li");
li.innerHTML = `
${task}
<button onclick="deleteTask(${index})">❌</button>
`;
list.appendChild(li);
});
}function addTask() {
let input = document.getElementById("taskInput");
let task = input.value; if (task === "") return; tasks.push(task);
localStorage.setItem("tasks", JSON.stringify(tasks)); input.value = "";
displayTasks();
}function deleteTask(index) {
tasks.splice(index, 1);
localStorage.setItem("tasks", JSON.stringify(tasks));
displayTasks();
}// Load tasks on page load
displayTasks();

🚀 What You Learn from This

  • DOM manipulation
  • Array handling
  • localStorage usage
  • Data persistence