JavaScript
Tags: javascript, beginners
Published: 2023-05-30 05:13:27


##  Loops:

###  `for`: 
* It is a basic for loop used to iterate through iterable

__example__:
```javascript
let arr = [1,2,3,3,4,5,6,7];
for(let i = 0; i < arr.length; i++ ){
	console.log(arr[i]);
	}
// Output: prints all the elements of array we can use same loop for strings also
```

### `forEach`:
* It is a higher order function in javascript which takes in another function as a reference

__example__:
```javascript
let arr = [1,2,3,4,5,6];
arr.forEach((num)=> num * 2);
console.log(arr);
//Output: Array of elements which are doubled
```

### `for .. in`:

* It is a looping technique majorly used to iterate over object

__example__:
```javascript

let person = {
	fname : "raj",
	lname : "kailash",
	age : 23
	location : "banglore";
}

for(let key in person){
	console.log(`${key} : ${person[key]}`);
}
```

### `for .. of`:

* This will return the each element of a array

__example__:
```javascript
let arr = [1,2,3,3,4,5,6,7];
for(let ele of arr){
	console.log(ele)
}
//Output: prints all the elements of array
```

### `while` :

* It is one of the most basic technique to loop through elements

__example__:

```javascript

let arr = [1,2,3,3,4,5,6,7];
let index = 0;
while(index < arr.length){
	console.log(arr[index]);
}

//Output: prints all the elements of array
```

## Mutable vs Immutable

* Mutable are those whose value can be changed without creating a entire new object

__example__: Objects , arrays.

* Immutable: Value can't be changed unless you create a new object
 __example__: Strings, Primitive datatypes etc.

## Pass by Reference and Pass by Value

__Pass by Value__ : 

* System will create it's own copy and value of variable will not change outside of block

__example__:
```javascript

let num = 10;
function multiply(num , n){	
	num = num*n;
	return num;
} 
 const res = multiply(num,2);
 console.log(num); // 10
 console.log(res); // 20
``` 
* In the above example num value have not changed even though we pass the same variable to the function, because system will create seperate copy of num and modify that


__Pass by Reference__:

* All the objects in javascript are passed by reference
* Even if you change it's value inside a function it will change the object

```javascript
let  person  = {
fname :  "raj",
lname :  "kailash",
age :  23,
location :  "banglore"
}

function  locationUpdate(person){
person["location"] =  'Vizag';
}
locationUpdate(person);
console.log(person);
// You will see location changed to vizag
```

* Here the person object is passed by refernce hence it is changing it's property value inside function


## Array Methods


### `Array.pop()`:

* removes the last element of a array and returns it's value

```javascript
let arr = [1,2,3,3,4,5,6,7];
console.log(arr.pop()); // 7
```
### `Array.push()`:

* Appends the elements at the end of array

```javascript
let arr = [1,2,3,3,4,5,6,7];
arr.push(10);
console.log(arr) // 10 is added at the end
``` 

### `Array.concat()`:

* Addes two arrays and returns the new array 
```javascript
let arr1 = [1,2,3,3,4,5,6,7];
let arr2 = [1,2,3,3,4,5,6,7];
const new_arr = arr1.concat(arr2); 
console.log(new_arr) // [1,2,3,4,5,6,7,1,2,3,4,5,6,7]
```

### `Array.slice()`

* It takes two values start,end indexes
* returns new array with values between specified indexes.

```javascript
let arr = [1,2,3,3,4,5,6,7];
const new_arr = arr.slice(0,3);
console.log(new_arr); // [1,2,3]
```

### `Array.splice()`

* It will remove elements from the given array
* Takes two values index and number of elements you want to delete

```javascript

let arr = [1,2,3,4,5,6,7];
arr.splice(0,3);
console.log(arr); // [4,5,6,7]
```
### `Array.join()`

* returns a string joining each element by given argument

```javascript

let arr = [1,2,3,4,5,6,7];
const str = arr.join(" ");
console.log(str) // 1 2 3 4 5 6 7
```

### `Array.flat()`:

* It will unbox all the elements inside a array which are nested elements

```javascript\
const arr = [1, 2, [3, [4, 5, 6], 7], 8];
const new_arr = myArr.flat();
console.log(new_arr) // [1,2,3,4,5,6,7,8]
```

### Finding:

### `Arrays.find()`:

* This will take boolean function reference as a argument and returns the first value in it's array which passes the function
* If no element is found it will return undefined

```javascript
let arr = [1,2,3,4,5,6,7];

const res  = arr.find((ele)=>{
	return ele > 5; 
});
console.log(res); // 6 since it is the first element which is greater than 5
```

### `Arrays.indexOf()`:

* It will return the index of first element that it find

```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let index = fruits.indexOf("Apple");
console.log(index); // 2
```

### `Array.includes()`:

* returns true if the element is present else returns false
* we can also optionly give another parameter as a start value which by default is zero

```javascript
const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let bool = fruits.includes("Apple");
console.log(bool) ;// true
```

### `Arrays.findIndex()`:

* takes the reference of a boolean returning function and returns the index of element that first passes the constion
* returns -1 if no element passes the test

```javascript
let arr = [1,2,3,4,5,6,7];

const res  = arr.findIndex((ele)=>{
	return ele > 4; 
});
console.log(res); // 4  
```

### Higher Order Functions

### `Arrays.forEach()`:

* This takes in the function as a argument and changes the existing array according to the argument function

```javascript
let arr = [1,2,3,4,5,6,7];

arr.forEach((ele)=>{
ele = ele*2;
});

console.log(arr) // [2,4,6,8,10,12,14]
```

### `Array.map()`:

* This takes in the function and will not modify the array and returns new array with modified values
* It will apply given function on each element of array

```javascript

let arr = [1,2,3,4,5,6,7];

const new_arr = arr.map((ele)=>{
	return ele*2
});
console.log(new_arr) // [2,4,6,8,10,12,14]
```

### `Array.filter()`:

* This will take a function as a argument which returns boolean value
* It will apply given function on each element of array
* this will return all the elements that passes the boolean constion

```javascript
let arr = [1,2,3,4,5,6,7];

const new_arr = arr.filter((ele) => {
	return ele > 3;
});
console.log(new_arr); //4,5,6,7
```

### `Arrays.reduce()`:

* This method will take two arguments one is the function and the other one is the initial value
* The argument function will further take two arguments which are accumilator and current element

```javascript
let arr = [1,2,3,4,5,6,7];
const sum = arr.reduce((acc,curr)=>{
	acc += curr;
	return acc;
},0)

console.log(sum); // 28
```

### `Arrays.sort()`:

* This method will take a function as a argument and sort depending on the result of that function
* The given function will also take two arguments which are compared to return positive, negitive or zero value

```javascript
const sorter = inventory.sort((a,b)=> {
	if (a.car_year > b.car_year){
		return 1;
	}else if (a.car_year < b.car_year){
		return -1;
	}
	return 0
});
```
* depending on the returned value array is sorted accordingly


###  Array methods chaining

* Using of higher order functions on output of other higher order function is called array method chaining
```javascript
console.log(inventory.filter((car)=>{
if(car.car_make  ===  'Audi'  ||  car.car_make  ===  'BMW'){
	return  true;
}else  return  false;
})
.reduce((acc, curr)=>{
	acc.push({id :  curr.id , car_year :  curr['car_year']});
	return  acc;
},[]))
```

* In the above code in inventory array first filters out the car_maker and pass the result to reduce function to output in given format



## String Methods

### `string.charAt()`:

* returns the character at given index
```javascript
let str = "abcd efg hij"
console.log(str.charAt(0)) // a
```

### `string.concat()`:

* appends two strings

```javascript
let str1 = "abcd";
let str2 = "efgh";

let new_str = str1.concat(str2);
console.log(new_str);
```

### `string.length`:

* returns the length of string as integer

```javascript
let str = "abcdef"
console.log(str.length); // 6
```

### `string.toUpperCase()`:

* returns the new string in upper case letters

```javascript
let str = 'abcdef';
console.log(str.toUpperCase()) // '	ABCDEF'
```

### `string.toLowerCase()`:

* returns the new string in lower case letters

```javascript
let str = 'ABCDEF';
console.log(str.toLowerCase()) // 'abcdef'
```

### `string.split()`:

* splits the string at given argument and returns array of strings

```javascript
let arr = 'abcd efgh'.split(' ');
console.log(arr) // ["abcd", "efgh"]
```

### `string.substring()`:

* returns the substring of string with given arguments
* It takes two arguments start and end(exclusive)

```javascript

let str = 'abcdefg';
console.log(str.substring(1,5)) // "bcde"
```

## Object Methods


### Assigning:

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23
}

person["location"] = "banglore"; // Assigning a new property to a object
```

### Checking:

* `in` key word is used to check if property is present or not

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23,
	location : "banglore"
}

console.log("fname" in person) // true
```


### `Object.keys()`:

* returns the keys array iterable object

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23,
	location : "banglore"
}

const keys = Object.keys(person);
for(let key of keys){
	console.log(key) // Prints all the keys of person object
}
```

###  `Object.values()`:

* returns the all the values of a object as a array

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23,
	location : "banglore"
}

const values = Object.values(person);
for(let value of values){
	console.log(value) // Prints all the values of person object
}
```

### `delete object[key]`:

* it will remove the entire property and it's value from object

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23,
	location : "banglore"
}

delete person["location"];
console.log(person) //prson object will not have location property
```

### `Object.entries()`:

* This will return a array of key, value pairs as a array

```javascript
let  person  = {
	fname :  "raj",
	lname :  "kailash",
	age :  23,
	location : "banglore"
}
const entries = Object.entries(person);

for(let pair of entries){
	console.log(pair) //[key , value]
}

```


## Hoisting

* It is special property of javscript where we can use the variables or functions without declaring first

```javascript
console.log(b); //It will print undefined not error
var b 
```
* Hoisting is posible only with variables declared using var key word


## Scopes

* There are two types of scopes of variables or functions
* Global Scope : variables which can be accessed any where in the program is called global scoped varibales
* Local Scope: The access is limited to a block 

```javascript
let a = 10; // global scope
if(a){
	let b = 5; // Local scope or block level scope
	console.log(b) // prints 5 
	console.log(a) // prints 10 
}
console.log(a) // prints 10 
console.log(b) // Throws error
```

## Closures

* It is process where fucntion is declared and returned inside another function
* It helps in improving privacy
* for example if you want to increase a variable value only inside a function not on outside(global scope)

```javascript
function sum() {
    let a = 0;
    function increaseSum() {
        // the value of a is increased by 1
        return a = a + 1;
    }
    return increaseSum;
}
let x = sum();
let a = 5;
console.log(x()); // 1
console.log(x()); // 2
console.log(a); // 5
```

### Debugging

* Debugging in javascript can be done in multiple ways

* `console.log()`: Most commonly used debugging technique
* `console.trace()`: returns the function call stack
* `console.time()  and console.timelLog()`: this gives the time taken by a program from the time() to timeLog() function.
* `developer tools`: browser provides developer tools which very handy to debugg a javascript code
* Using break points in editor etc

## References

* [w3scools](https://www.w3schools.com/js/default.asp#gsc.tab=0)
* [programiz](https://www.programiz.com/javascript/closure)
* [Hoisting](https://www.w3schools.com/js/js_hoisting.asp)