DEV Community

Yaswanth K N
Yaswanth K N

Posted on • Edited on

JavaScript

Loops:

for:

  • It is a basic for loop used to iterate through iterable

example:

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
Enter fullscreen mode Exit fullscreen mode

forEach:

  • It is a higher order function in javascript which takes in another function as a reference

example:

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

for .. in:

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

example:


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

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

for .. of:

  • This will return the each element of a array

example:

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
Enter fullscreen mode Exit fullscreen mode

while :

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

example:


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
Enter fullscreen mode Exit fullscreen mode

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:


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
Enter fullscreen mode Exit fullscreen mode
  • 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
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
Enter fullscreen mode Exit fullscreen mode
  • 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
let arr = [1,2,3,3,4,5,6,7];
console.log(arr.pop()); // 7
Enter fullscreen mode Exit fullscreen mode

Array.push():

  • Appends the elements at the end of array
let arr = [1,2,3,3,4,5,6,7];
arr.push(10);
console.log(arr) // 10 is added at the end
Enter fullscreen mode Exit fullscreen mode

Array.concat():

  • Addes two arrays and returns the new array
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]
Enter fullscreen mode Exit fullscreen mode

Array.slice()

  • It takes two values start,end indexes
  • returns new array with values between specified indexes.
let arr = [1,2,3,3,4,5,6,7];
const new_arr = arr.slice(0,3);
console.log(new_arr); // [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Array.splice()

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

let arr = [1,2,3,4,5,6,7];
arr.splice(0,3);
console.log(arr); // [4,5,6,7]
Enter fullscreen mode Exit fullscreen mode

Array.join()

  • returns a string joining each element by given argument

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

Array.flat():

  • It will unbox all the elements inside a array which are nested elements
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]
Enter fullscreen mode Exit fullscreen mode

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
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
Enter fullscreen mode Exit fullscreen mode

Arrays.indexOf():

  • It will return the index of first element that it find
const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let index = fruits.indexOf("Apple");
console.log(index); // 2
Enter fullscreen mode Exit fullscreen mode

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
const fruits = ["Banana", "Orange", "Apple", "Mango"];  
let bool = fruits.includes("Apple");
console.log(bool) ;// true
Enter fullscreen mode Exit fullscreen mode

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
let arr = [1,2,3,4,5,6,7];

const res  = arr.findIndex((ele)=>{
    return ele > 4; 
});
console.log(res); // 4  
Enter fullscreen mode Exit fullscreen mode

Higher Order Functions

Arrays.forEach():

  • This takes in the function as a argument and changes the existing array according to the argument function
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]
Enter fullscreen mode Exit fullscreen mode

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

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]
Enter fullscreen mode Exit fullscreen mode

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
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
Enter fullscreen mode Exit fullscreen mode

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
let arr = [1,2,3,4,5,6,7];
const sum = arr.reduce((acc,curr)=>{
    acc += curr;
    return acc;
},0)

console.log(sum); // 28
Enter fullscreen mode Exit fullscreen mode

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
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
});
Enter fullscreen mode Exit fullscreen mode
  • 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
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;
},[]))
Enter fullscreen mode Exit fullscreen mode
  • 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
let str = "abcd efg hij"
console.log(str.charAt(0)) // a
Enter fullscreen mode Exit fullscreen mode

string.concat():

  • appends two strings
let str1 = "abcd";
let str2 = "efgh";

let new_str = str1.concat(str2);
console.log(new_str);
Enter fullscreen mode Exit fullscreen mode

string.length:

  • returns the length of string as integer
let str = "abcdef"
console.log(str.length); // 6
Enter fullscreen mode Exit fullscreen mode

string.toUpperCase():

  • returns the new string in upper case letters
let str = 'abcdef';
console.log(str.toUpperCase()) // ' ABCDEF'
Enter fullscreen mode Exit fullscreen mode

string.toLowerCase():

  • returns the new string in lower case letters
let str = 'ABCDEF';
console.log(str.toLowerCase()) // 'abcdef'
Enter fullscreen mode Exit fullscreen mode

string.split():

  • splits the string at given argument and returns array of strings
let arr = 'abcd efgh'.split(' ');
console.log(arr) // ["abcd", "efgh"]
Enter fullscreen mode Exit fullscreen mode

string.substring():

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

let str = 'abcdefg';
console.log(str.substring(1,5)) // "bcde"
Enter fullscreen mode Exit fullscreen mode

Object Methods

Assigning:

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

person["location"] = "banglore"; // Assigning a new property to a object
Enter fullscreen mode Exit fullscreen mode

Checking:

  • in key word is used to check if property is present or not
let  person  = {
    fname :  "raj",
    lname :  "kailash",
    age :  23,
    location : "banglore"
}

console.log("fname" in person) // true
Enter fullscreen mode Exit fullscreen mode

Object.keys():

  • returns the keys array iterable object
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
}
Enter fullscreen mode Exit fullscreen mode

Object.values():

  • returns the all the values of a object as a array
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
}
Enter fullscreen mode Exit fullscreen mode

delete object[key]:

  • it will remove the entire property and it's value from object
let  person  = {
    fname :  "raj",
    lname :  "kailash",
    age :  23,
    location : "banglore"
}

delete person["location"];
console.log(person) //prson object will not have location property
Enter fullscreen mode Exit fullscreen mode

Object.entries():

  • This will return a array of key, value pairs as a array
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]
}

Enter fullscreen mode Exit fullscreen mode

Hoisting

  • It is special property of javscript where we can use the variables or functions without declaring first
console.log(b); //It will print undefined not error
var b 
Enter fullscreen mode Exit fullscreen mode
  • 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
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
Enter fullscreen mode Exit fullscreen mode

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)
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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)