JavaScript/TypeScript use cases commonly used in Angular development

Nagesh BulbuleNagesh Bulbule
8 min read

1. Sorting an array of strings

Use CaseBehavior
list.sort()Sorts array in-place (modifies original array, case-sensitive)
[...list].sort()Sorts a shallow copy of the array (original remains unchanged)
list.sort((a,b)=>a.localeCompare(b))Case-insensitive sort (based on locale, modifies original)
[...list].sort((a,b)=>a.localeCompare(b))Case-insensitive sort without modifying original

2. Filtering an array

Use CaseBehavior
list.filter(item => item.includes('a'))Returns new array with items containing 'a'
list.filter(Boolean)Removes falsy values (null, undefined, false, 0, '')

3. Mapping array to transform data

Use CaseBehavior
list.map(item => item.toUpperCase())Returns new array with uppercased strings
list.map((x, i) => ${i+1}. ${x})Add index/numbering to array items

4. Finding elements

Use CaseBehavior
list.find(item => item === 'apple')Returns first matching element or undefined
list.findIndex(item => item === 'apple')Returns index of match or -1

5. Checking conditions

Use CaseBehavior
list.includes('apple')Checks if 'apple' is in the array
list.some(item => item.startsWith('a'))Checks if at least one item matches condition
list.every(item => typeof item === 'string')Checks if all items match condition

6. Removing duplicates

Use CaseBehavior
[...new Set(list)]Removes duplicate values from array

7. Shallow copy of objects/arrays

Use CaseBehavior
{...obj}Shallow copy of object
[...arr]Shallow copy of array

8. Merging objects/arrays

Use CaseBehavior
{...obj1, ...obj2}Merge two objects (right overrides left)
[...arr1, ...arr2]Merge two arrays

9. Nullish coalescing & optional chaining

Use CaseBehavior
user?.nameSafely access user.name without error if user is null/undefined
value ?? 'default'Return value if not null/undefined, else 'default'

10. Ternary for conditional rendering

Use CaseBehavior
flag ? 'Yes' : 'No'Returns 'Yes' if flag is true, else 'No'

11. Convert strings/numbers

Use CaseBehavior
parseInt('123') / Number('123')Convert string to number
String(123) / 123 + ''Convert number to string

12. Date handling

Use CaseBehavior
new Date()Current date-time object
new Date().toISOString()Returns ISO string format
new Date().toLocaleDateString()Returns local readable date
date.toDateString()Converts date to readable string

13. SetTimeout / SetInterval

Use CaseBehavior
setTimeout(() => {}, 1000)Run code once after 1 sec
setInterval(() => {}, 1000)Run code repeatedly every 1 sec
clearTimeout(id) / clearInterval(id)Cancel scheduled action

14. String operations

Use CaseBehavior
'text'.includes('e')Checks if string has character 'e'
'Hello'.toLowerCase() / .toUpperCase()Changes case
'item1,item2'.split(',')Converts comma string to array
['a', 'b'].join(',')Converts array to comma string

15. Template literals

Use CaseBehavior
Hello, ${name}String interpolation using variables

16. Looping over arrays

Use CaseBehavior
for (let item of list)Iterates values
for (let i in list)Iterates indexes
list.forEach(item => doSomething(item))Iterates with a callback

17. Type assertion in TypeScript

Use CaseBehavior
value as stringAsserts type to string
<string>valueAnother syntax for type assertion

18. Type checking

Use CaseBehavior
typeof value === 'string'Checks if type is string
Array.isArray(value)Checks if value is an array

19. Object iteration

Use CaseBehavior
Object.keys(obj)Get array of property names
Object.values(obj)Get array of property values
Object.entries(obj)Get array of [key, value] pairs

20. Angular-specific data patterns

Use CaseBehavior
@Input() data: stringAccepts input from parent component
@Output() event = new EventEmitter()Emits events to parent component
ngOnInit()Lifecycle method: runs after component initialized
*ngFor="let item of items"Loop in HTML template
*ngIf="condition"Show/hide template based on condition
[(ngModel)]="value"Two-way binding with forms

๐Ÿ” RxJS / Observables Basics

Use CaseCodeBehavior
Create observable manuallyconst obs = new Observable(observer => { observer.next('data'); })Emits custom data stream
Subscribe to observableobs.subscribe(data => console.log(data))Reacts to emitted values
Create observable from valueof('a', 'b')Emits values in order
From array to observablefrom([1, 2, 3])Emits each item one by one

๐Ÿ”„ Operators โ€“ Transformation

Use CaseCodeBehavior
Transform emitted datasource.pipe(map(val => val * 2))Applies function to each emitted value
Filter emissionssource.pipe(filter(val => val > 10))Emits only values passing condition
Chain operatorssource.pipe(map(), filter())Process stream step-by-step

๐Ÿ•’ Operators โ€“ Timing

Use CaseCodeBehavior
Delay valuesobs.pipe(delay(1000))Adds delay to each emitted value
Debounce valuesobs.pipe(debounceTime(300))Emits only after silence period
Throttle emissionsobs.pipe(throttleTime(1000))Emits first value in each time window

๐Ÿ” Switch, Merge, Combine Streams

Use CaseCodeBehavior
Cancel previous and switchswitchMap(val => http.get(...))Cancels previous call, starts new one
Merge multiple observablesmerge(obs1, obs2)Emits from both as they arrive
Combine latest valuescombineLatest([obs1, obs2])Emits array when any source emits

๐Ÿ”— Subjects โ€“ Observable + Observer

Use CaseCodeBehavior
Create Subjectconst subject = new Subject()Emits values manually using .next()
Subscribe to Subjectsubject.subscribe(...)Acts like observable
Emit valuesubject.next('hello')Triggers all subscribers

โ™ป๏ธ ReplaySubject & BehaviorSubject

Use CaseCodeBehavior
new BehaviorSubject('initial')Keeps last value, emits it to new subscribers
new ReplaySubject(2)Remembers last 2 values, replays to new subs

๐ŸŒ Angular HTTP Client โ€“ Basics

Use CaseCodeBehavior
Inject HttpClientconstructor(private http: HttpClient)Use in service or component
GET requesthttp.get('/api/data')Returns observable of response
POST requesthttp.post('/api/data', payload)Sends data to server
PUT requesthttp.put('/api/data', payload)Updates full resource
DELETE requesthttp.delete('/api/data/1')Deletes resource

โš™๏ธ HTTP Options & Headers

Use CaseCodeBehavior
Add headershttp.get(url, { headers: new HttpHeaders({ 'Auth': 'token' }) })Adds custom headers
Add query paramshttp.get(url, { params: new HttpParams().set('q', 'search') })Adds URL params

๐Ÿงฐ Handling Response

Use CaseCodeBehavior
Get only datahttp.get(...).subscribe(data => this.data = data)Subscribes to response
Error handlinghttp.get(...).pipe(catchError(err => of([])))Catch and handle errors gracefully

๐Ÿ“ฆ Angular Service Example (Best Practice)

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    return this.http.get('/api/data');
  }

  saveData(payload: any): Observable<any> {
    return this.http.post('/api/data', payload);
  }
}

Use in Component:

@Component({...})
export class AppComponent implements OnInit {
  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(data => console.log(data));
  }
}

๐Ÿ”’ Authentication Token Handling (Interceptor)

Use CaseCodeBehavior
Intercept every requestCreate interceptor and implement HttpInterceptorAutomatically attach token
Attach tokenreq.clone({ setHeaders: { Authorization: Bearer ${token} } })Adds auth to each request
0
Subscribe to my newsletter

Read articles from Nagesh Bulbule directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nagesh Bulbule
Nagesh Bulbule

Hi, I'm developer who loves coding and learning new things.