40+ Angular and JavaScript Interview Questions


lets discuss 40 + frequently asked angular and JavaScript interview questions 


JavaScript Interview Questions

1. What are closures in JavaScript?

  • Closures allow an inner function to remember variables from its outer function even after the outer function has finished executing.

function outer() {

  let count = 0;

  return function inner() {

    count++;

    return count;

  };

}

const counter = outer();

console.log(counter()); // 1

console.log(counter()); // 2


  • Closures power callbacks, event listeners, and async programming all of which are used in Angular.

2. Difference between var, let, and const?

  • var : functionscoped, can be redeclared.
  • let : blockscoped, reassignable.
  • const: blockscoped, cannot be reassigned.

3. What is event delegation?

  • Instead of attaching event listeners to multiple child elements, you attach one to the parent. The event bubbles up and gets handled at the parent level.

  •  Saves memory and improves performance—super important in large apps.

4. Difference between == and ===?

  • ==  loose equality (performs type conversion).
  • ===  strict equality (compares type + value).
  • Always use === to avoid bugs.

5. What is the event loop in JavaScript?

  • The event loop is what makes JavaScript asynchronous. It constantly checks the call stack and the callback queue, allowing nonblocking code execution.

6. What are Promises and async/await?

  • Promise :represents a future value (resolved or rejected).
  • async/await: syntactic sugar for writing cleaner asynchronous code.

async function fetchData() {

  const res = await fetch('/api/data');

  return res.json();

}

7. What is hoisting?

  • Hoisting means JavaScript moves variable and function declarations to the top of their scope before code execution.

8. Difference between null and undefined?

  • null : intentional “no value.”
  • undefined : variable declared but not assigned.

9. What are arrow functions, and how are they different?

  • Arrow functions don’t have their own this. They inherit it from their surrounding scope.
  • Useful in Angular callbacks and RxJS streams.

10. What is the difference between synchronous and asynchronous JavaScript?

  • Synchronous : one task at a time.
  • Asynchronous : tasks can run in the background (timers, API calls).

11. What is a callback function?

  • A callback is a function passed as an argument and executed later.

12. What is a prototype in JavaScript?

  • Every JS object has a prototype, which enables inheritance. Angular’s TypeScript classes compile down to prototypebased JS.

13. What are higherorder functions?

  • Functions that take other functions as arguments or return them.
  • Examples: map(), filter(), reduce().

14. Explain deep copy vs shallow copy.

  • Shallow copy: copies only toplevel properties.
  • Deep copy  means copies nested objects as well.

Angular Interview Questions

15. What is Angular, and how does it differ from AngularJS?

  • AngularJS (1.x) :JavaScriptbased, MVC, slower.
  • Angular (2+) :TypeScriptbased, componentdriven, faster.

16. What are the main building blocks of Angular?

  • Modules
  • Components
  • Templates
  • Directives
  • Services
  • Pipes

17. What is Dependency Injection in Angular?

DI means Angular creates and injects services instead of you creating them manually. Makes code testable and modular.

18. Explain Angular data binding.

  • Interpolation : {{ name }}
  • Property binding : [src]="imageUrl"
  • Event binding :(click)="onClick()"
  • Twoway binding : [(ngModel)]="username"
check here for more details on data binding in angular

19. What are lifecycle hooks in Angular?

  • ngOnInit() : runs after component loads
  • ngOnChanges() : detects input property changes
  • ngOnDestroy() :cleanup before component is destroyed

for more details on 8 life cycle hooks angular 

20. How do Angular components communicate?

  • @Input() - Parent - Child
  • @Output() -Child -Parent
  • Services with RxJS :Share data across components

21. What are Angular directives?

  • Structural : *ngIf, *ngFor
  • Attribute : [ngClass], [ngStyle]

22. What is Angular Routing?

  • Routing allows navigation between views. Features include:
  • Route parameters (:id)
  • Lazy loading
  • Route guards

23. What are Observables in Angular?

  • Observables (via RxJS) handle async data streams (HTTP requests, events, sockets).
  • Unlike promises, they can emit multiple values over time.

24. What is Angular Ivy?

  • Ivy is the rendering engine that makes Angular apps smaller and faster.

25. What is Angular Universal?

  • It enables ServerSide Rendering (SSR) for SEO and performance.

26. How does Angular handle forms?

  • Templatedriven forms : simpler.
  • Reactive forms:  more control, better validation.

27. What are Angular Pipes?

  • Transform data in templates. Examples: date, currency, async.
  • You can also build custom pipes.

28. What is lazy loading in Angular?

  • Loads modules only when needed, reducing initial bundle size.

29. What are Guards in Angular routing?

  • Guards like CanActivate and CanDeactivate control route access.

30. What is ViewEncapsulation?

  • Controls how CSS styles are applied:
  • Emulated (default)
  • None
  • ShadowDOM

31. What are standalone components in Angular 17+?

  • Standalone components don’t need NgModules, making apps simpler.

32. What are Angular Signals?

  • Signals are new reactive primitives for managing state, simpler than RxJS in some cases.

33. What are Angular Zones?

  • NgZone tracks async tasks and triggers change detection.

34. What is AheadofTime (AOT) compilation?

  • AOT compiles Angular templates at build time & faster runtime performance.

35. Difference between templatedriven and reactive forms?

36. How do you improve performance in Angular apps?

  • Lazy loading
  • OnPush change detection
  • TrackBy in *ngFor
  • Caching API responses

37. Difference between Subject, BehaviorSubject, and ReplaySubject in RxJS?

  • Subject: plain multicast observable.
  • BehaviorSubject: holds last value.
  • ReplaySubject: replays multiple past values.

38. How do you handle state management in Angular?

  • RxJS services
  • NgRx
  • Akita
  • Signals (newer alternative)

39. Difference between Reactive and Imperative programming?

  • Reactive: declarative, uses streams (RxJS, signals).
  • Imperative : stepbystep instructions.

40. How do you make Angular apps SEOfriendly?

  • Angular Universal (SSR)
  • Prerendering
  • Meta tags
  • Lazyloaded images

Here is Quick Revision for you: 40 Angular & JavaScript Interview Questions 

JavaScript Questions
  1. Closures: Inner function remembers variables from outer function even after execution.
  2. var vs let vs const: var = function scope, let = block scope, const = block scope (no reassignment).
  3. Event delegation:Attach one listener to parent, handle child events via bubbling.
  4. == vs === : == loose equality with type coercion, === strict equality.
  5. Event loop : Handles async tasks by moving them from queue to call stack.
  6. Promises vs async/await: Promise handles async values; async/await makes them cleaner.
  7. Hoisting:JS moves declarations (not assignments) to the top at runtime.
  8. null vs undefined: null = intentional empty, undefined = unassigned.
  9. Arrow functions: Short syntax, no own this.
  10. Sync vs Async JS: Sync = one task at a time; Async = tasks in background.
  11. Callback: Function passed into another to be executed later.
  12. Prototype: Enables inheritance in JS objects.
  13. Higherorder function: Function that takes/returns another function (map, filter).
  14. Deep vs shallow copy: Shallow copies only one level; deep copies nested too.
Angular Questions
  1. Angular vs AngularJS: Angular = TypeScript, faster, componentbased; AngularJS = JS, MVC.
  2. Building blocks: Modules, Components, Templates, Directives, Services, Pipes.
  3. Dependency Injection: Angular provides services/objects automatically.
  4. Data binding: Interpolation, property, event, twoway ([(ngModel)]).
  5. Lifecycle hooks: ngOnInit, ngOnChanges, ngOnDestroy.
  6. Component communication: @Input, @Output, services with RxJS.
  7. Directives: Structural (*ngIf, *ngFor) and Attribute (ngClass).
  8. Routing: Navigation between views, supports lazy loading and guards.
  9. Observables: Async streams of data (multiple values over time).
  10. Ivy: New rendering engine, smaller bundles, faster.
  11. Universal (SSR): Serverside rendering for SEO and performance.
  12. Forms: Templatedriven (simple) vs Reactive (scalable, powerful).
  13. Pipes: Transform data (date, currency, async, custom).
  14. Lazy loading: Loads modules on demand for performance.
  15. Guards: Control access to routes (CanActivate, CanDeactivate).
  16. ViewEncapsulation: Controls style scope (Emulated, ShadowDOM, None).
  17. Standalone components :Angular 17+, no need for NgModules.
  18. Signals : New reactive state primitive, simpler than RxJS in some cases.
  19. Zones (NgZone) :Detect async tasks, trigger change detection.
  20. AOT compilation : Precompiles templates at build time.
  21. Template vs Reactive forms :Template = simple, Reactive = complex validation.
  22. Performance optimization: Lazy load, OnPush, TrackBy, cache data.
  23. Subject vs BehaviorSubject vs ReplaySubject :Subject : plain, Behavior :last value, Replay : past values.
  24. State management: RxJS, NgRx, Akita, Signals.
  25. Reactive vs Imperative programming: Reactive = declarative streams, Imperative = stepbystep.
  26. SEO in Angular : Angular Universal, prerendering, meta tags, lazyloaded images.

Explain the difference between == and ===

  •  We all know that == is equality operator is used to compare two values in JavaScript.
  • === operator is strict equality operator
  • Both == & === are used to compare values in JavaScript. then what is the difference between == and === lets discuss in detail
  • == compares two values by converting them to same data types, 10 == ''10" will be true because string type of 10 converted in to number.
  • === compares two values without converting them to same data type. 10 === "10"
  • Use our JavaScript compiler to test your snippets
== vs === in JavaScript


1.  == ( loose Equality)
  • Checks value equality after type conversion

  • Converts operands to same type before conversion (ex: 10 == '10' here string 10 will be converted in to number) 

2. === Strict equality
  • checks value and type without conversion.
  • return false if types are different.
ScenarioLoose ==)Strict (===)
5 vs. "5truefalse
0 vs. falsetrue false
null vs. undefinedtruefalse
NaN vs NaNfalsefalse
{} vs {}falsefalse


Explanation:

1. 5 == "5" → true(loose)  
   - JavaScript converts "5" (string) to 5 (number) before comparison.  
  5 === "5" → false(strict)  
   - Different types: number vs. string.  

2. 0 == false → true(loose)  
   false is converted to 0, so 0 == 0 is true.  
  0 === false → false(strict)  
   - Number vs. boolean, so different types.  

3. null == undefined → true(loose)  
   - Special case:null andundefined are only loosely equal to each other.  
  null === undefined → false(strict)  
   - Different types:null vs.undefined.  

4. NaN == NaN → false(loose)  
   NaN is  not equal to itselfin JavaScript.  
  NaN === NaN → false(strict)  
   Same reason here: NaN is never equal to anything, including itself.  

5. {} == {} → false(loose)  
   - Objects are compared by **reference**, not by value.  
   - Different objects in memory, so alwaysfalse.  
  {} === {} → false (strict)  
   - Still different object references. 

  • "5" === "5" returns true
Remember these special cases:
  • NaN == NaN will be false even with == operator ,Use Number.isNaN(x) to check for NaN.
  • null == undefined will be true
When to use which operator:
  • always use === as it is recommended way and which avoids unexpected type conversion
  • use == for null/undefined check
  • if (x == null) { ... } // Catches both `null` and `undefined`.

splice vs slice in javascript

 'splice()' and 'slice()' are two array techniques in JavaScript that are often confused with each other. In order to resolve these ambiguities, we will compare the two methods below step by step.

splice vs slice javascript


1. Creating a Slice: The Simple Version

Purpose

Evaluates only a small part of an array without changing it.

Usage

array.slice(startIndex, endIndex);

Main Points

  • Produces a new array consisting of the elements from startIndex to endIndex (not inclusive).
  • Changes made to the original array are not visible.
  • If indexes are negative, they count from the end.
  • If no arguments are given, then array.slice() makes a shallow copy of the entire array.

Example

const fruits = ['apple', 'banana', 'cherry', 'date'];

const sliced = fruits.slice(1, 3);

console.log(sliced); // ['banana', 'cherry']

console.log(fruits); // ['apple', 'banana', 'cherry', 'date'] (that's how it remained)

2. splice(): Add/Remove Elements from an Array

Purpose

Alters the original array, inserts or deletes elements.

Syntax

array.splice(startIndex, deleteCount, item1, item2,...);

Key Points

  • Changes the original array.
  • Returns an array followed by the removed elements (if any).
  • Deleting, adding or changing elements on the spot are all possible.

Examples

a. Deleting Elements

const numbers = [1, 2, 3, 4, 5];

const removed = numbers.splice(1, 2); // Start removing from position 1 and remove 2 from that

console.log(removed); // [2, 3]

console.log(numbers); // [1, 4, 5]

b. Adding Elements

const colors = ['red', 'blue'];

colors.splice(1, 0, 'green'); // Add 'green' after index 1 without deleting anything

console.log(colors); // ['red', 'green', 'blue']

c. Replacing Elements

const letters = ['a', 'b', 'c'];

letters.splice(1, 1, 'x'); // Replace 'b' with 'x' at index 1

console.log(letters); // ['a', 'x', 'c']

3. The Key Differences

Featureslice()splice()
Mutates OriginalNoYes
Return ValueNew array of extracted elementsArray of removed elements (if any)
Parameters(start, end)(start, deleteCount, items...)
Use CaseCopy a piece of an arrayAdd/remove elements in place

  • Slice Use it when you need to take a part from the array out without changing the original.
  • Example: Generate a copy of an array:
  • const copy = arr.slice();
  • Splice Use it when you need to remove, add, or adjust an array.
  • Example: Update a list dynamically, such as editing a to-do list.

5. Pitfalls of Using These Two Methods

Mixed Parameters Puzzle

  • Slice (1, 3) obtains elements from indices 1 and 2 (excluding index 3).
  • Splice (1, 3) starts at index 1 and removes three elements.

Splice's Mutability

  • Splice() changes the original array, so always make sure you don't need to preserve the original data before using it.

Summary

  • Slice: copy parts of an array without changing the original.
  • Splice: can edit an array directly, deleting, introducing or replacing parts.

prime number program in javascript

  • JavaScript prime number program
  • In this example will learn about how to find the number is prime or not.
  • WHATS IS PRIME NUMBER
  • A number greater than 1 with exactly two factors is called prime number.
  • Number which is divisible by 1 and itself is prime number. If it is divisible by any other number(other than 1 and itself) then it's not a prime number.
    • Consider an example of number 5 ,Which has only two factors  1 and 5. This means 5 is a prime number. Lets take one more example Number 6, which has more than two factors, i.e 1,2,3. This means 6 is not a prime number.
    • The first ten prime numbers are 2,3,5,7,11,13,17,19,23,29.
    • Note: It should be noted that 1 is non-prime number, because in the above defination already mentioned A number greater than 1 with 2 factors called prime number..

  • Here we have simple program to print the prime numbers in java script.
JavaScript program to check a number is prime number or not.

  1. <html>
  2.     <head>
  3. <script>
  4.     // javascript program to check the number is prime or not.
  5.     // prime number program in javascript
  6.     // javascript prime number program
  7.     // take input from the user
  8. const x = parseInt(prompt("Enter a number to check prime or not: "));
  9. let isPrimeNumber=true;

  10. // check if number is equal to 1
  11. if (x  === 1) {
  12.     alert("1 is neither prime nor composite number.");
  13. }

  14. // checking  if  number is greater than one or not

  15. else if (x  > 1) {

  16.     // iterating from 2 to number -1 (leaving 1 and itself )
  17.     for (let i = 2; i < x ; i++) {
  18.         if (x  % i == 0) {
  19.             isPrimeNumber = false;
  20.             break;
  21.         }
  22.     }

  23.     if (isPrimeNumber) {
  24.         alert(`${x } is a prime number`);
  25.     } else {
  26.         alert(`${x } is not a prime number`);
  27.     }
  28. }

  29. // check if number is less than 1
  30. else {
  31.     console.log("The number is not a prime number.");
  32. }
  33. </script>
  34.     </head>
  35.     <body>

  36.     </body>
  37. </html>




Output:
javascript prime number
javascript prime number program


Remove whitespace from string javascript

  • To remove white space in a string in JavaScript at the starting and ending. i.e both sides of a string we have trim() method in JavaScript.
  •  By Using .trim() method we can remove white spaces at both sides of a string.
  • var str = "       instanceofjava.com        ";
    alert(str.trim());
  • Will alert a popup with instanceofjava.com.
Javascript remove last character if comma 
  • If  we want to remove last character of a string then we need to use replace method in JavaScript.
  • str = str.replace(/,\s*$/, "");
  • We can also use slice method to remove last character.
remove white spaces in javascript

Remove specific characters from a string in Javascript


  • To remove specific character from string in java script we can use

  1. var string = 'www.Instanceofjava.com'; 
  2. string.replace(/^www.+/i, ''); 'Instanceofjava.com'

How to use Javascript confirm dialogue box

  • Confirm dialogue box in java script used to display a message for an action weather its is required to perform or not.
  • JavaScript confirm dialogue box contains two buttons "Ok" and "Cancel".
  • If user clicks on OK button confirm dialogue box returns true. If user clicks on cancel button it returns false.
  • So based on the user entered option we can continue our program. So confirm dialogue box used to test an action is required or not from user.



  • Its not possible to change values of confirm dialogue box buttons from "Ok" and "Cancel"to "Yes" and "No".
  • We need to use custom popups or jquery popups to use "Yes" and "No".
  •   var res= confirm("Are you sure to continue?");

How to use Javascript  confirm dialogue box:

  1. function myFunction() {
  2.     var text;
  3.     var res= confirm("Are you sure to continue?");
  4.     if (res == true) {
  5.         text= "You clicked OK!";
  6.     } else {
  7.         text= "You clicked Cancel!";
  8.     }
  9.     document.getElementById("demo").innerHTML = txt
  10. }
  11. </script>

Javascript confirm delete onclick:

  • If we are deleting a record from database then we need to ask user  to confirm deletion if ye really want to delete record then user checks Ok otherwise cancel based on this we can proceed furthur.
  • To implement this functionality we need to call a JavaScript function onClick()  whenever user clicks on delete record button.

Program#1: JavaScript program to show confirm dialogue box on clicking delete student record.

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <p>Click the button to delete student record</p>
  6.  
  7. <button onclick="toConfirm()">Delete student record </button>
  8.  
  9. <p id="student"></p>
  10. <script>
  11. function toConfirm() {
  12.     var text;
  13.     var r = confirm("You clicked on a button to delete student recored. Clik ok ro proceed");
  14.     if (r == true) {
  15.        //code to delete student record.
  16.         text = "You clikced on ok. Student record deleted";
  17.     } else {
  18.         text = "You clicked on cancel. transaction cancelled.";
  19.     }
  20.     document.getElementById("student").innerHTML = text;
  21. }
  22. </script>
  23.  
  24. </body>
  25. </html>

javascript confirm delete yes no

  • If we click on Ok then it will delete student record. otherwise it wont.

javascript onclick confirm dialog

Validate email address using javascript

  • One of the famous interview question in JavaScript : how to validate email address in JavaScript.
  • In order to validate a text field of HTML we need a JavaScript function.
  • On submit form we need to call a java script function to validate all fields in the form also known as client side validation.
  • Now on form submit we need to check email text field and validate it whether entered email is in correct format or not for ex: [email protected]



JavaScript program for email validation:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var x = document.forms["Form_Name"]["txt_email"].value;
  7.     var atpos = x.indexOf("@");
  8.     var dotpos = x.lastIndexOf(".");
  9.     if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
  10.         alert("Not a valid e-mail address");
  11.         return false;
  12.     }
  13. }
  14. </script>
  15. </head>
  16.  
  17. <body>
  18. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  19. validateEmailForm();" method="post">
  20. Email: <input type="text" name="txt_email">
  21. <input type="submit" value="Submit">
  22. </form>
  23. </body>
  24.  
  25. </html>

Validate email in java-script using regular expression: on submit form validation

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var email = document.forms["Form_Name"]["txt_email"].value;
  7.   
  8.  var re = /\S+@\S+\.\S+/;
  9.     return re.test(email);
  10.   
  11.     }
  12. }
  13. </script>
  14. </head>
  15.  
  16. <body>
  17. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  18. validateEmailForm();" method="post">
  19. Email: <input type="text" name="txt_email">
  20. <input type="submit" value="Submit">
  21. </form>
  22. </body>
  23.  
  24. </html>


javascript program for email validation


HTML 5 Email validation:



  1. <form>
  2. <input type="email" placeholder="Enter your email">
  3. <input type="submit" value="Submit">
  4. </form>
email address validation code in java script

Select Menu