1. Sorting an array of strings
Use Case | Behavior |
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 Case | Behavior |
list.filter(item => item.includes('a')) | Returns new array with items containing 'a' |
list.filter(Boolean) | Removes falsy values (null , undefined , false , 0 , '' ) |
Use Case | Behavior |
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 Case | Behavior |
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 Case | Behavior |
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 Case | Behavior |
[...new Set(list)] | Removes duplicate values from array |
7. Shallow copy of objects/arrays
Use Case | Behavior |
{...obj} | Shallow copy of object |
[...arr] | Shallow copy of array |
8. Merging objects/arrays
Use Case | Behavior |
{...obj1, ...obj2} | Merge two objects (right overrides left) |
[...arr1, ...arr2] | Merge two arrays |
9. Nullish coalescing & optional chaining
Use Case | Behavior |
user?.name | Safely 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 Case | Behavior |
flag ? 'Yes' : 'No' | Returns 'Yes' if flag is true, else 'No' |
11. Convert strings/numbers
Use Case | Behavior |
parseInt('123') / Number('123') | Convert string to number |
String(123) / 123 + '' | Convert number to string |
12. Date handling
Use Case | Behavior |
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 Case | Behavior |
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 Case | Behavior |
'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 Case | Behavior |
Hello, ${name} | String interpolation using variables |
16. Looping over arrays
Use Case | Behavior |
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 Case | Behavior |
value as string | Asserts type to string |
<string>value | Another syntax for type assertion |
18. Type checking
Use Case | Behavior |
typeof value === 'string' | Checks if type is string |
Array.isArray(value) | Checks if value is an array |
19. Object iteration
Use Case | Behavior |
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 Case | Behavior |
@Input() data: string | Accepts 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 Case | Code | Behavior |
Create observable manually | const obs = new Observable(observer => { observer.next ('data'); }) | Emits custom data stream |
Subscribe to observable | obs.subscribe(data => console.log(data)) | Reacts to emitted values |
Create observable from value | of('a', 'b') | Emits values in order |
From array to observable | from([1, 2, 3]) | Emits each item one by one |
Use Case | Code | Behavior |
Transform emitted data | source.pipe(map(val => val * 2)) | Applies function to each emitted value |
Filter emissions | source.pipe(filter(val => val > 10)) | Emits only values passing condition |
Chain operators | source.pipe(map(), filter()) | Process stream step-by-step |
๐ Operators โ Timing
Use Case | Code | Behavior |
Delay values | obs.pipe(delay(1000)) | Adds delay to each emitted value |
Debounce values | obs.pipe(debounceTime(300)) | Emits only after silence period |
Throttle emissions | obs.pipe(throttleTime(1000)) | Emits first value in each time window |
๐ Switch, Merge, Combine Streams
Use Case | Code | Behavior |
Cancel previous and switch | switchMap(val => http.get(...)) | Cancels previous call, starts new one |
Merge multiple observables | merge(obs1, obs2) | Emits from both as they arrive |
Combine latest values | combineLatest([obs1, obs2]) | Emits array when any source emits |
๐ Subjects โ Observable + Observer
Use Case | Code | Behavior |
Create Subject | const subject = new Subject() | Emits values manually using .next() |
Subscribe to Subject | subject.subscribe(...) | Acts like observable |
Emit value | subject.next ('hello') | Triggers all subscribers |
โป๏ธ ReplaySubject & BehaviorSubject
Use Case | Code | Behavior |
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 Case | Code | Behavior |
Inject HttpClient | constructor(private http: HttpClient) | Use in service or component |
GET request | http.get('/api/data') | Returns observable of response |
POST request | http.post ('/api/data', payload) | Sends data to server |
PUT request | http.put('/api/data', payload) | Updates full resource |
DELETE request | http.delete('/api/data/1') | Deletes resource |
Use Case | Code | Behavior |
Add headers | http.get(url, { headers: new HttpHeaders({ 'Auth': 'token' }) }) | Adds custom headers |
Add query params | http.get(url, { params: new HttpParams().set('q', 'search') }) | Adds URL params |
๐งฐ Handling Response
Use Case | Code | Behavior |
Get only data | http.get(...).subscribe(data => this.data = data) | Subscribes to response |
Error handling | http.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 Case | Code | Behavior |
Intercept every request | Create interceptor and implement HttpInterceptor | Automatically attach token |
Attach token | req.clone({ setHeaders: { Authorization: Bearer ${token} } }) | Adds auth to each request |
Subscribe to my newsletter
Read articles from Nagesh Bulbule directly inside your inbox. Subscribe to the newsletter, and don't miss out.