Skip to content

javascript code snippets

Vijay Pratap edited this page Jul 20, 2024 · 1 revision

1. Create custom prototype in javascript

const users = [{
    id: 1,
    name: 'Manjusha Kalla',
    phone: '02225429789'
},
{
    id: 2,
    name: 'Sai Prashad',
    phone: '07922748183'
}]  
      
function User() {
	this.users = [];
};
      
User.prototype.setUser = function(){
  	return this.users = users
};
  
User.prototype.getUser = function(id){
    let users = [...this.users]
    const filteredUsers = users.filter((item) => item.id === id);
	return filteredUsers
};

User.prototype.getUsers = function(){
    return this.users
};

User.prototype.addUser = function(data){
	let users = [...this.users]
    users.push(data)
	return this.users = users
}; 

User.prototype.removeUser = function(id){
	let users = [...this.users]
    const filteredUsers = users.filter((item) => item.id !== id);
	return this.users = filteredUsers
};
    
var authobj = new User();

authobj.setUser()
authobj.addUser({id: 3, name: 'Aalia Bhasin', phone: '02228092081'})
authobj.removeUser(1)
const updatedUsers = authobj.getUsers()
const userDetails = authobj.getUser(2)

console.log({updatedUsers, userDetails})

2. Add custom method in Array.prototype in javascript

const contacts = [
    {
        latter: 'M',
        name: 'Manjusha Kalla',
        phone: '02225429789'
    },
    {
        latter: 'S',
        name: 'Sai Prashad',
        phone: '07922748183'
    },
    {
        latter: 'A',
        name: 'Aalia Bhasin',
        phone: '02228092082'
    },
    {
        latter: 'T',
        name: 'Talika Dugal',
        phone: '02225386500'
    },
    {
        latter: 'M',
        name: 'Mukul Atwal',
        phone: '02227454631'
    },
    {
        latter: 'R',
        name: 'Rajni Pradhan',
        phone: '04027892419'
    },
    {
        latter: 'S',
        name: 'Sanjana Kakar',
        phone: '02224146428'
    },
    {
        latter: 'P',
        name: 'Priya Dhillon',
        phone: '02223841925'
    },
    {
        latter: 'A',
        name: 'Aparajita Edwin',
        phone: '02224092856'
    },
    {
        latter: 'L',
        name: 'Lata Khosla',
        phone: '02228321292'
    },
    {
        latter: 'L',
        name: 'Lata Khosla',
        phone: '02228321292'
    }
]

Array.prototype.groupBy = function(key) {
  let updatedItem = this.reduce((item, { ...rest }) => {
      item[rest[key]] = item[rest[key]] || { key: rest[key], items: [] };
      item[rest[key]]["items"].push(rest)
      return item;
  }, {})
  return Object.values(updatedItem)
}

const data = contacts.groupBy('latter')

console.log(data)

3. What is the purpose of the array slice and splice in javascript.

The slice and splice array methods might seem similar to each other, but there are a few key differences.

Slice():

The slice() method can be used to create a copy of an array or return a portion of an array.

the slice() method does not alter the original array but instead creates a shallow copy.

slice() method can take 2 arguments:

Argument 1 : Required, Start index

Argument 2 : Optional, End index

Note Use negative numbers to select from the end of an array.

Example

const array = [1,2,3,4,5];

console.log(array.slice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.

console.log(array);
// shows [1,2,3,4,5], original array not altered.

console.log(array.slice(-1));
// shows [5], returned removed item(s) as a new array object.

console.log(array);
// shows [1,2,3,4,5], original array not altered.

Splice():

The splice() method can be used to add or remove elements of an existing array and the return value will be the removed items from the array.

splice() method can take n number of arguments:

Argument 1 : Required, Index.

Argument 2 : Optional, The number of items to be removed. If set to 0, no items will be removed. And if not passed, all item(s) from provided index will be removed.

Argument 3 : Optional, The new item(s) to be added to the array.

Example

const array = [1,2,3,4,5];

console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.

console.log(array);
// shows [1, 2], original array altered.

console.log(array.splice(2, 1, 8));
// shows [3], returned removed item(s) as a new array object.

console.log(array);
// shows [1, 2, 8], original array altered.

4. What is the difference between slice and splice

Some of the major difference in a tabular form

Slice Splice
Doesn't modify the original array(immutable) Modifies the original array(mutable)
Returns the subset of original array Returns the deleted elements as array
Used to pick the elements from array Used to insert or delete elements to/from array

5. Convert array to string using javascript method

Join():

The join() method can be used to creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

Export vs Default Export in ES6

Export

The export allow multiple exports in a single file.

Example

export const MyFunction1 = () => {};

export const MyFunction2 = () => {};

export const MyFunction3 = () => {};

Export Default

The export default allow one export default in single file.

Example

const MyFunction1 = () => {};

export default MyFunction1

export const MyFunction2 = () => {};

export const MyFunction3 = () => {};

6. Explain setTimeout & setInterval in javascript.

setTimeout():

The setTimeout() method can be used to call a function after a certain period of time.

The setTimeout() method is executed only once.

The setTimeout() method is cancelled by clearTimeout() method.

Parameters

Func: Required

Delay: Optional

Params: Optional

const intervalID = setInterval(myCallback, 500, "Parameter 1", "Parameter 2");

function myCallback(a, b) {
  console.log(a);
  console.log(b);
}

setInterval():

The setInterval() method can be used to call a function repeatedly at a specified interval of time.

The setInterval() method is cancelled by clearInterval() method.

The setInterval() method is continues calling the function until clearInterval() is called, or the window is closed.

Parameters

Func: Required

Delay: Optional

Params: Optional

const intervalID = setInterval(myCallback, 500, "Parameter 1", "Parameter 2");

function myCallback(a, b) {
  console.log(a);
  console.log(b);
}