JavaScript Basic - this, closure, Math.random(), DOM...
Tags: this, closure, dom, javascript
Published: 2021-12-06 19:15:58

```js
arr2 = [2, 3, 4, 5]; // assigning to array
arr1 = [1, 2, 3, 4];

arr3 = arr1; // now arr3 and arr1 are referencing the same array
arr3[3] = 0;  // this change even the referenced array that's stored in arr1 (because they are getting the reference from the same thing)

arr1;
// [1, 2, 3, 0]
```
** Array/Object are reference type! If you assign array to new variable, it is not copying the array to the new variable but it's referencing it. 
```js
let str = 'welcome';

str;
// 'welcome'

str[0]
// 'w'

str[0] = 'v'
// 'v'

str;
// 'welcome'
```
string is primitive type. When you assign a variable that stores a primitive value to another, the value stored in the variable **_is created and copied_** into the new variable.

JavaScript uses **prototype-based** programming, which is a **_type of object_** oriented programming. Prototypes are a way of reusing behaviors by cloning existing objects instead of doing class based inheritance. (https://en.wikipedia.org/wiki/Prototype-based_programming)

Number, String, Boolean, undefined, null, Symbol are primitive type and Array, object and function are object/reference type.

#Object
- Object is **_instance_** of class in Object oriented programming. Javascript is prototype based - object oriented  language. (which doesn't need class) However, Class has adopted in ES6.
- Everything that consists of JavaScript is "Object" (except the primitive value, everything else is object)
- Object is one or more of set of properties and properties have key-value pair.

#Literal
JavaScript literals: literals are constant values that can be assigned to the variables that are called literals or constants. JavaScript literals are syntactic representations for different types of data like numeric, string, boolean, array, object, function etc data... 

#Instance
```js
let myString = new String('hello world');
```
myString is an instance that's pointing String here. myString here is also called as 'Object'
Object is called instance and instance also can be called object. Because when the Function constructor is creating object, object at that point is called instance. 
Instance is a created result of Function constructor. 
'hello world' from above code can be called as  object literal/string/primitive value/instance...etc


# Function constructor
```js
function User(name) {
    this.name = name;
    this.isAdmin = false;
}
let user = new User('Violet');
console.log(user.name); // Violet
console.log(user.isAdmin); // false

let user = new User('Hailey');
user.name;
// 'Hailey'
```

[About function() constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function)


#this
When function or object executes the code, it points where the function or object is being executed. **`this`** points the execution context.
```js
function aboutThis() {
    console.log(this); // console.log this to see what it is
}
aboutThis();  // call function
// Window {window: Window, self: Window, document: document, name: '', location: Location, …}
undefined
// window
```

About the code above - **`this`** points window here. **`this`** points an object that calls function. window is running in global and the function aboutThis() is called in window. therefore, this points window.
```js
let myObj = {
  val1:100,
  func1: function() { 
    console.log(this)
 }
}
myObj.func1();
// { val1: 100, func1: f}
```
there is function func1 inside object called myObj. 
![this is window-1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/byvcj2ir3vss1dk6ajca.png)
Then why console.log(this) prints {val1: 100, func1: f} ? it's because  {val1: 100, func1: f}  itself is myObj.

![this is window-2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7i6hw217yq2di9a6r6k.png)
```js
/ * this */
function sayName(){
  console.log(this.name);
}

let name = 'Hero'; // globally declared variable name
// so this means window.name === "Hero"

let peter = {
  name : 'Peter Parker',
  sayName : sayName
}

let bruce = {
  name : 'Bruce Wayne',
  sayName : sayName
}

sayName();
peter.sayName(); 
// Peter Parker
bruce.sayName();
// Bruce Wayne
```
Take a look at apply(), call(), bind() as well.


#Closure
Scope is like effective range for variable(think about scope of sniper's rifle). let and const are block scoped. Global scope is like open space, you can access from anywhere.
I wrote about scope before. [check](https://dev.to/daaahailey/javascript-basic-function-function-expression-block-scope-callback-function-arrow-function-506j)

closure is like a space that's shut down/ cannot access.
```js
function myFunction() {
 var val1 ="hello"; // This area inside of function is closure space
}

function myFunction() {
 var val1 ="hello”;
return val1; 
}

function myFunction() {
var val1 ="hello";
return 10;
}

myFunction();
// 10

// If you'd like to take a value out of function, make it to return. You can take the value that's returned.

// You can also return object in function.

function myFunction() {
var val1 ="hello";
return { getVal1 : function(){} } 
}

function myFunction() {
var val1 ="hello";
return { getVal1 : function(){
          return val1; } 
  } 
}

// to access the value where it's in a place that's not allowed to access,
you can assign function to object and return

let result = myFunction();
result.getVal1();
// 'hello'
```
Why is there closure?
It's to avoid variables getting mixed and being polluted. Also, to keep it safe.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8c2cx1hw7eaf892nej5n.png)
You can return object as well.
[Something to read ](https://soeunlee.medium.com/javascript%EC%97%90%EC%84%9C-%EC%99%9C-%ED%95%A8%EC%88%98%EA%B0%80-1%EA%B8%89-%EA%B0%9D%EC%B2%B4%EC%9D%BC%EA%B9%8C%EC%9A%94-cc6bd2a9ecac) 
[More about closure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)


#DOM basic
Document Object Model - about [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction)
The Document Object Model (DOM) is the data representation of the objects that comprise the **_structure and content of a document on the web_**
The Document Object Model (DOM) is a programming interface for web documents. 
It represents the page so that programs can **<u>change the document structure, style, and content</u>**. The DOM represents the document as **nodes** and objects; that way, programming languages can interact with the page.

#How to access DOM tree
using document object, you can access to html document.

DOM practice
```js
<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        .container {
            display: flex;
            flex-direction: column;
            text-align: center;
            justify-content: center;
            align-items: center;
            margin-top: 50px;
        }

        .circle {
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background-color: black;
            margin-bottom: 50px;
        }

        .btn-cont {
            display: flex;
        }

        button {
            /* padding: 16px 0; */
            width: 90px;
            height: 42px;
            display: flex;
            margin: 10px;
            align-items: center;
            justify-content: center;
            background-color: black;
            color: white;
            font-weight: 600;
            border-radius: 14px;
            border: 1px solid black;
            box-shadow: 0px 1px 1px 1px rgba(0, 0, 0, 0.4);
            cursor: pointer;
        }

        button:active {
            transform: scale(0.98);
        }

        .circle.red-bg {
            background-color: #ff324e;
        }

        .circle.yellow-bg {
            background-color: #ffff56;
        }

        .circle.green-bg {
            background-color: #55d600;
        }
    </style>
</head>

<body>
    <div>
        <div class="container">
            <div class="circle"></div>
            <div class="btn-cont">
                <button class="red-btn">RED</button>
                <button class="yellow-btn">YELLOW</button>
                <button class="green-btn">GREEN</button>
            </div>
        </div>
    </div>
    <script>
        const circle = document.querySelector(".circle");
        const btnRed = document.querySelector(".red-btn");
        const btnYellow = document.querySelector(".yellow-btn");
        const btnGreen = document.querySelector(".green-btn");

        // refactored code
        let btnArr = [btnRed, btnYellow, btnGreen];
        btnArr.forEach((item) => {
            item.addEventListener("click", () => {
                // circle.classList.remove("red-bg", "yellow-bg", "green-bg");
                circle.classList = "circle";
                if (item.className === "red-btn") {
                    console.log("cllicke")
                    circle.classList.add("red-bg");
                } else if (item.className === "yellow-btn") {
                    circle.classList.add("yellow-bg");
                } else {
                    circle.classList.add("green-bg");
                }

            })
        })
        // btnRed.addEventListener("click", function () {
        //     circle.classList.remove("yellow-bg", "green-bg");
        //     circle.classList.add("red-bg");
        // })

        // btnYellow.addEventListener("click", function () {
        //     circle.classList.remove("red-bg", "green-bg");
        //     circle.classList.add("yellow-bg");
        // })

        // btnGreen.addEventListener("click", function () {
        //     circle.classList.add("green-bg");
        //     circle.classList.remove("red-bg", "yellow-bg");

        // })

    </script>
</body>

</html>
```