JS Fundamentals


 * Basic JS functions: 

1. parseInt(string, radix)  |  parseInt("A", 16);  // Returns 10 (hexadecimal to decimal), parseFloat() parses a string and returns a floating-point number.

2. ${} is used to evaluate and embed expressions dynamically in template literals. It is used for expression interpolation within template literals. Template literals are strings enclosed by backticks (` `) instead of single quotes (' ') or double quotes (" "). The expression inside the ${} is evaluated, and its result is converted to a string and inserted into the template literal. 

3. slice(optional start, optional end)

4. substr(start, till what length)

5. splice(start, optional delete count, optional items to add) it returns an array containing deleted elements, delete count=0 if we don't want to delete any item.

6. push(put from front), pop(from right), shift(from left), unshift(put at end)

7. indexOf, lastindexOf, str.replace(a1, a2), value.split(delimiter) gives an array

8. arr1.concat(arr2) is used to merge two or more arrays, or values, into a new array. The original arrays are not modified.

9. arr1.forEach(callbackFn, optional thisArg) expects synchronous function and calls this function once for each element in an array in ascending index order.

10. Var is global and can be re-assigned, let is local and can be re-assigned, const is local and is fixed.

11. Internal linking is basically extraction of output from html file itself, while external linking is extraction of code from separate Js files (linked through src in html file).

12. Time functions .getDate(), .getMonth(), .getFullYear(), .getHours/Minutes/Seconds() similarly set functions are used.


* Key Notes: 

13. The 'new' operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

14. JavaScript 'Date' objects represent a single moment in time in a platform-independent format. Date objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).

15. setInterval(func, delay) method repeatedly calls a function or executes a code snippet, with a fixed time delay b/w each call.

16. The global setTimeout(functionRef, delay) method sets a timer which executes a function or specified piece of code once the timer expires.

17. JSON.parse() static method parses a JSON string, constructing the JS value/object described by the string. JSON.stringify() static method converts a JS value/object to a JSON string. MDN JSON Doc

18. In Js even if the callback is resolved and ready with its return value but our thread is busy somewhere the control will not reach the callback(as it is sent to callback queue). Only when the thread is ideal, the event loop runs and the control will reach out to address pending callbacks by placing them in call stack.

19. 'Promises' in Js are just syntactical sugar that still uses callbacks under the hood but it helps to get rid of callbacks syntactically in asynchronous code.

20. Every browser has a Js engine inside it so that Js code can be executed in that browser. NodeJs is a runtime environment of Js, a place where all of our program will be executed having access to file system, databases, and network attached to the server. Culmination of V8 engine and C++, due to which Js code can be executed outside of browser. Node.js has its own APIs, provided by libuv.

21. JS on its own is just a programming language, it has variables, functions, loops, basic objects etc. but it does not have built-in ways to interact with the browser window like handle timers, read/ write files, or make network requests. The runtime environment has some methods built into it and any program executed in that environment has access to these methods.

22. HTTP servers are used to expose some kind of functionality over the internet so that others can access it as well. 

23. Understanding URLs

Eg.1  https://www.example.com/: This URL points to the main page of the website example.com using the HTTPS protocol, including the www. subdomain. The trailing slash indicates that this URL points to a directory or a resource.

Eg.2  http://images.example.com/photo.jpg: This URL points to the image file photo.jpg located within the images subdomain of example.com, using the HTTP protocol. 

Eg.3  https://blog.example.com/post/article1?author=john&date=2025-05-31#section2: This URL points to a specific blog post, article1, within the blog subdomain of example.com, and includes parameters like author=john and date=2025-05-31, and a fragment section2, all using the HTTPS protocol. 
For a more detailed explanation visit:  MDN URLs Doc
    
24. In const app = express(); app is an instance of express and will act as our handler function, it represents our HTTP server logic, just like what http.createServer((req, res)=>{...}); represents. In app.METHOD(path, handler), handler is the function executed when the route is matched.

25. We use JWT tokens so that once the user is authenticated we use the token to confirm the identity in all future requests without needing the user to enter password again for every other route. Every time a user signs in, a new JWT token is generated to represent a fresh authenticated session. JWTs are stateless(thus no need to store app sessions in memory) and self-contained, the token itself serves as proof of authentication and includes metadata like the issued time and expiration. Generating a new token each time helps ensure that sessions remain secure and that the token's expiry (e.g., 1 hour from login) is always current. This approach also prevents misuse of old or previously leaked tokens.
    
26. Clusters of Node.js processes can be used to run multiple instances of Node.js that can distribute workloads among their application threads. 
* Problem: Node.js runs on a single thread, meaning it can only use one CPU core at a time. This can be a bottleneck if your server receives many requests.
* Solution: The cluster module lets you create "worker" processes that run concurrently. Each worker is a separate instance of your application, and they all share the same server port. This distributes the load across multiple CPU cores, improving performance and scalability. When process isolation is not needed, use the worker_threads module instead, which allows running multiple application threads within a single Node.js instance. Clusters Doc
    
27. We use encodeURI() function to encode a URL. This function requires a URL string as a parameter and it returns that encoded string. Opposingly, decodeURI() function is used to decode a URL. This function requires an encoded URL string as parameter and return that decoded string.
Note: If you want to encode characters such as / ? : @ & = + $ # then you need to use encodeURIComponent().
Eg:-
let uri = "employeeDetails?name=john&occupation=manager";
let encoded_uri = encodeURI(uri);
let decoded_uri = decodeURI(encoded_uri);

28. Server-sent events (SSE) is a server push technology enabling a browser to receive automatic updates from a server via HTTP connection without resorting to polling. These are a one way communications channel - events flow from server to client only. This has been used in Facebook/Twitter/X updates, stock price updates, news feeds etc. 
        
We can also perform browser support for server-sent events before using it as below:
if (typeof EventSource !== "undefined") {
  // Server-sent events supported. Can have some code here!
} else {
  // No server-sent events supported
}