Javascript Notes

Primitive values and reference value

Primitive Values :

number
string
boolean
symbol
null
undefined
bigint

are immutable and shared by copy

let number = 1;
console.log(number + 2); //copied 1 and added 2
number = number + 3; //copied 1 and added 3 then assigned to number

Reference Value
Any Object in javascript is a reference value and that its important to keep in mind that arrays and functions are also objects (reference value) in javascript
Ex : Objects(ie plain objects, arrays, functions,…)

are mutable and shared by well reference

const person = {age: 31};
const me = person;
person = {name: 'Max'} // Invalid
person.me = 32;
console.log(me.age) // Prints 32!

Reference values in javascript are stored such that we have one object stored in memory and what’s stored in the const/variable doesn’t matter is a pointer at this object in memory so the address of that object in memory you could say the reference to it that’s stored in a constant and when we create a new constant here we just copied that pointer and store it in a new constant as well but if we then use that pointer to manipulate the value we work on one and the same value in memory because that vale in memory was never copied or cloned or anyting like that it’s one of the same object with one pointer and just that pointer was copied and thats why we manipulate the object stored in copied constant (me) when we assign a new age to the person object because its not two different objects its one object in memory that’s also why we can manipulate a Const , this is a const (person) so we can not change the value stored in there right why can we then assign a new age well ? because we are not assigning a new value to person with that we’re changing the value the pointer point set but whats stored in this const is not that object but the pointer and the pointer donesn’t change we wouldn’t be allowed to assign a new value to person let’s say a new object this throw (person = {name: ‘Max’}) an error because here we really would create a new object a new pointer and try to store it in person but what we do here is perfectly fine because we’re just changing an existing object in memory now there are techniques how you can copy an object so how you can not just copy the pointer but the full object and i do dive

Online Editor

QA : Window or document which one will execute first ?


$(document).ready(function() {

    // Executes when the HTML document is loaded and the DOM is ready
    alert("Document is ready");
});

// .load() method deprecated from jQuery 1.8 onward
$(window).on("load", function() {

     // Executes when complete page is fully loaded, including
     // all frames, objects and images
     alert("Window is loaded");
});

Ref : https://www.tutorialspoint.com/What-is-the-difference-between-window-load-and-document-ready-functions-in-jQuery

Plain js file read :

AJAX (Asynchronous JavaScript and XML) requests are by default asynchronous, The XMLHttpRequest object is used to exchange data with a server behind the scenes. When the browser makes server requests. The response could take a little time. So you set up a function that will wait for the response to be sent back by the server, and react to it once the response is available. This whole process does not comes in the way of other functions.

synchronous-and-asynchronous


var xhttp;
  console.log('First Line');
      if (window.XMLHttpRequest) {
          console.log('XMLHttpRequest')
        // code for modern browsers
        xhttp = new XMLHttpRequest();
      } else {
        // code for old browsers (IE6, IE5)
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xhttp.onreadystatechange = function() {
        console.log('onreadystatechange', this)
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("ajax_demo").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "note.txt", true);
      xhttp.send();
      xhttp.onload = function(){
        console.log('onload')
        document.write(this.response);
      }; 
console.log('End of Line');

QA : Call, Apply, Bind

I want to call a function, i want to set a specific object as a context to the function. I can do it using call method.
Ex : add.call(val, 1,1)

Apply : Pass arguments as array.
Ex : add.apply(val, [1,1])

Call & Apply : will call the function immediately.
apply and call are similar functions which set this (context of a function).

Bind – You can create variable of bind and can call it latter
var addBind = add.bind(val)
addBind(3,3);

javascript-call-apply-vs-bind

Use .bind() when you want that function to later be called with a certain context, useful in events.
Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

Javascript is synchronous and Single Threaded

Single threaded can not be asynchronous, but through the event loop and stack it will behave like asynchronous.

Example :

console.log('first time : ', new Date())
setTimeout(()=>{
console.log('Second time : ', new Date())
}, 2000)

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

var oldTime = new Date().getTime();
var newTime = new Date().getDate();
while((newTime - oldTime)/1000 < 5){
newTime = new Date().getTime();
}

setTimeout(), setInterval()

Example :


setTimeout(function(name){
console.log('test', name)
}, 1000, 'Prabha')

if we want to execute this code repeatedly for every second

setTnterval(function(name){
console.log('test', name)
}, 1000, 'Prabha')

ClearInterval :

let count = 0;

const intervalId = setInterval(function(name){
count++;
if(count > 5){
	clearInterval(intervalId);
} else {
	clearTimeout(timeoutId);
	x();
}
console.log(count);
}, 1000, 'Rahul')

let timeoutId = null;
var x = function(){
	timeoutId = setTimeout(function(){
	console.log('timeout')
},2000)
}
x();

Leave a Reply

Your email address will not be published. Required fields are marked *