# Advanced JS topics :100: --- ## Value vs. reference types in JavaScript --- Variables contains value, but not all values the same type, lets take an example to make it clear. --- ```jsx= const a = 3; ``` Here we can see varibale `a` have the <b>value</b> `3`. --- ### Can we get more information about the <b style="color:red;">value</b> ? --- Well, yes, in JS we have a different types of values and to know their type we can simply use `typeof` function, lets take an **example** : --- ```jsx= console.log(typeof(a)); // output : "number" console.log(typeof("hello")); // output : "string" console.log(typeof([])); // output : "object" console.log(typeof({x : 3})); // output : "object" ``` "number" and "string" are primitive data types and all the primitive types in java script are stored in the stack, whereas "object" type is stored in a special place called `heap`. --- ### But wait, how can I fetch the object from the heap? --- As soon as you assign the **object** to a variable, the variable will contain the address of that object in the heap memory, in other words you can assign two variables to the same address and alter the same object fields. --- ##### lets take an example : ```jsx= const obj = {}; const newObj = obj; // now obj and newObj points // to the same location in the heap obj.a = 3; console.log(newObj.a); // output : 3; newObj.a = 4; console.log(obj.a); // output : 4; ``` --- ```jsx= const obj = {}; const newObj = obj; // now obj and newObj points // to the same location in the heap obj.a = 3; console.log(newObj.a); // output : 3; newObj.a = 4; console.log(obj.a); // output : 4; ``` <p>As you can see we declared a new field called <b style="color:red">a</b> and assign to it `3` (3 is a primitive type of type "number") and that change is also reflected in newObj. And again that is because they have the same address in the heap, so they alter the same memory location.</p> --- <img src="https://media.giphy.com/media/iHe7mA9M9SsyQ/giphy.gif" style="display:block;margin: 0 auto;"> --- #### Now lets see how <b style="color:green;">primitive</b> types behave : --- ```jsx= let a = 3; let b = a; b = 4; console.log(a); // what do you expect the output to be? ``` --- ```jsx= let a = 3; let b = a; b = 4; console.log(a); // what do you expect the output to be? ``` Answear : 3 And thats because <b style="color:purple">a</b> contains the actual value and not an address. In line 2 we are copying the value of <b style="color:purple">a</b> to <b style="color:purple">b</b>. <b style="color:purple">a</b> and <b style="color:purple">b</b> have different memory locations (in the stack) --- ### Fun question 1 :smile: ```jsx console.log("hElLo".toUpperCase()); // What is the output and why? remember that "helLo" // is primitive data type and all primitive types live // on the stack, they have no methods. // 1. helLo // 2. HELLO // 3. VM531:1 Uncaught TypeError: "HELLO".toUpperCase is // not a function ``` --- Because you wanted to access a field, the interpreter behind the scenes changes the line to ```jsx (new String("hElLo")).toUpperCase() ``` so the answear is 2 and that is <b style="color:green">HELLO</b> --- ### Fun question 2 :smile: ```jsx= const str = new String("hello"); // what is value of str and where // the object lives in memory ? // 1. "Hello" and lives in stack. // 2. "Hello" and lives in heap. // 3. some address and lives in stack. // 4. some address and lives in heap. ``` --- Because we have <b style="color:blue">new</b> keyword we can tell that its data type is object, and object lives in heap. So, in order to know where to fetch its value from the heap the <b style="color:blue">new</b> keyword return an address. In other words str contains the some address. --- ##### <b style="color:green">And where str lives?</b> --- ##### <b style="color:green">And where str lives?</b> In the stack, all variables values are stored in the stack, whether its an address or some other primitive value. --- <img src="https://media.giphy.com/media/vsC7gewdX8tfq/giphy.gif" style="margin:0 auto;display:block;"> <b style="display:block; paddin">Thanks :smile:</b> --- ### == vs. === == in JavaScript is used for comparing two variables, but it ignores the datatype of variable. === is used for comparing two variables, but this operator also checks datatype and compares two values. == is equal to, for example: if x = 5 then x == 8 false x == 5 true === is equal value and equal type: for example: if x = 5 then x ==='5' false x === 5 true == Checks the equality of two operands without considering their type. === Compares equality of two operands with their types. == Return true only if the two operands are equal. === returns true only if both values and data types are the same for the two variables. # Examples: 2 == "2" // true, auto type coercion, string converted into number. 2 === 2" // false, since both operands are not of same type. 0 == false // true, because false is equivalent of 0. 0 === false // false, because both operands are of different types. 'hello world' === 'hello world' // true (Both Strings, equal values) true === true // true (Both Booleans, equal values) 77 === '77' // false (Number v. String). 'cat' === 'dog' // false (Both are Strings, but have different values) ### Scope in JS each function create a new scope, there is two types of varibales: local and global the scope determines accessibility of these variables to be a local or global. local scope: if a varibale has been created in the function scope ,then his scope is only local varibale and cant be used outside the function. the lifetime of local var is start when the function began and end when function ends too . the name of the local var can be used more than once in different functions without overriding . global scope: when we create a var outside the function its mean this var is belong to the class and not to function (as Static var in java). this mean we could use is in all the function in our code. the life time for this var its start when we create in and end when we close the browser (in JS). global vars use only if we really need them , beacuse using them may make an overriding , this mean we can change the value of the var , so we should be carefull when we are creating them ### Closures What are closures? When we run a code in other languages for example, we can't access variables outside of a function inside of that function(this is not possible in other languages) but it is possible in JavaScript, and this is what we call a closure, example: ```javascript= var favorite=pizza; function printFavorite(){ console.log(favorite); } printFavorite(); // pizza ``` In the example above, the external global variable favorite is accessible inside the function printFavorite(). ok let's explain a little bit on How closures work in JavaScript: We have two scopes in the example above(The entire JavaScript file is one scope, and the function is anothe scope), so every scope has access to everything outside of its scope, the function printFavorite() has an outer scope so it has access to everything inside the outer file. If we change the global variable to favorite=hamburger; , the function will print hamburger, so it takes the most recent value of the variable. In other words: The closure gives you access to anything outside of the current scope. Let's understand the closures with deeper example, I will try to build a function to increase a counter: ```javascript= function add(){ let counter=0; function plus(){counter++;} plus(); return counter; } ``` according to what we've learned about closures,the inner function plus() has access to the outer scope(the outside function),but the problem is that the outer function will reset the counter everytime we call it, so to fix this we will use self invoked function. ```javascript= const add= (function(){ let counter=0; function plus(){counter++;} plus(); return counter; }))(); ``` Now, when we call the function add(), it will run once(reseting the counter to 0, and returning the function plus which increments the counter by 1), after that step, whenever we call the function add() we are accessing the inner function which still has access to the counter variable from the outer function(this is how closures works), and it will increment the counter. ### Clean code concepts: this mean to keep your code clear to read it and underestand it, for future work and other programmers Examples: give a valid name for function (the name should say what they do) give a valid name for variables dont duplicate code dont use a negative words in function names Don't add unneeded context functions should do one thing remove dead code make notes.
{"metaMigratedAt":"2023-06-15T14:03:22.310Z","metaMigratedFrom":"Content","title":"Advanced JS topics :100:","breaks":true,"contributors":"[{\"id\":\"ac7082f1-c8f9-4a63-86dd-b63c4a7e5b1a\",\"add\":5453,\"del\":1438},{\"id\":\"2aa03955-0265-4fc4-8096-297647c246f3\",\"add\":3934,\"del\":195},{\"id\":\"60667a8c-164a-4eb4-8bde-216029e5b815\",\"add\":1464,\"del\":336}]"}
    241 views
   Owned this note