JavaScript Functions - CodingTute https://codingtute.com/tag/javascript-functions/ Learn to code in an easier way Tue, 20 Dec 2022 11:08:25 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://codingtute.com/wp-content/uploads/2021/06/cropped-codingtute_favicon-32x32.png JavaScript Functions - CodingTute https://codingtute.com/tag/javascript-functions/ 32 32 187525380 JavaScript splice() method https://codingtute.com/javascript-splice-method/ Tue, 20 Dec 2022 11:08:22 +0000 https://codingtute.com/?p=4839 The splice() method is a method in JavaScript that allows you to modify an array by removing or replacing elements, or adding new elements in place. It works by specifying the index at which to start making changes, and the number of elements to remove (if any). You can also specify one or more elements ... Read more

The post JavaScript splice() method appeared first on CodingTute.

]]>
The splice() method is a method in JavaScript that allows you to modify an array by removing or replacing elements, or adding new elements in place. It works by specifying the index at which to start making changes, and the number of elements to remove (if any). You can also specify one or more elements to add to the array in place of the removed elements.

Here is the syntax for the splice() method:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  • start: The index at which to start making changes to the array.
  • deleteCount: The number of elements to remove from the array, starting at the start index. If this parameter is omitted, the splice() method will remove all the elements from the start index to the end of the array.
  • item1, item2, ...: The elements to add to the array, starting at the start index. These elements will replace the removed elements.

Here are some examples of how you can use the splice() method:

// Remove the first element of the array
let fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(0, 1);  // ['apple'] is removed
console.log(fruits);  // ['banana', 'mango', 'orange']

// Remove the last two elements of the array
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(-2);  // ['mango', 'orange'] are removed
console.log(fruits);  // ['apple', 'banana']

// Insert a new element at the beginning of the array
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(0, 0, 'pear');  // no elements are removed
console.log(fruits);  // ['pear', 'apple', 'banana', 'mango', 'orange']

// Replace the second element with two new elements
fruits = ['apple', 'banana', 'mango', 'orange'];
fruits.splice(1, 1, 'strawberry', 'kiwi');  // ['banana'] is removed
console.log(fruits);  // ['apple', 'strawberry', 'kiwi', 'mango', 'orange']

It’s important to note that the splice() method modifies the original array in place and returns an array containing the removed elements. If you don’t want to modify the original array, you can use the slice() method instead, which returns a new array without modifying the original array.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post JavaScript splice() method appeared first on CodingTute.

]]>
4839
JavaScript sort() method https://codingtute.com/javascript-sort-method/ Tue, 20 Dec 2022 11:07:32 +0000 https://codingtute.com/?p=4844 The sort() method in JavaScript works by comparing the elements of an array using a given comparison function, and rearranges the elements in ascending order based on the returned value. If no comparison function is provided, the sort() method uses the default comparison function, which sorts the elements in ascending order based on their Unicode ... Read more

The post JavaScript sort() method appeared first on CodingTute.

]]>
The sort() method in JavaScript works by comparing the elements of an array using a given comparison function, and rearranges the elements in ascending order based on the returned value. If no comparison function is provided, the sort() method uses the default comparison function, which sorts the elements in ascending order based on their Unicode code points.

In simpler terms before comparison each element of the array is converted into string and compared.

Here is the syntax for the sort() method:

array.sort([compareFunction])

compareFunction: An optional comparison function that determines the order of the elements. If this parameter is omitted, the sort() method will use the default comparison function, which sorts the elements in ascending order based on their Unicode code points.

// Sort an array of strings in descending order
let words = ['cat', 'dog', 'bird', 'ant', 'bee'];
words.sort((a, b) => b.localeCompare(a));
console.log(words);  // ['dog', 'cat', 'bee', 'ant', 'bird']

// Sort an array of objects by a property
let cars = [  { make: 'Ford', model: 'Focus' },  { make: 'Toyota', model: 'Corolla' },  { make: 'Honda', model: 'Civic' }];
cars.sort((a, b) => a.make.localeCompare(b.make));
console.log(cars);  // [{ make: 'Ford', model: 'Focus' }, 
{ make: 'Honda', model: 'Civic' }, 
{ make: 'Toyota', model: 'Corolla' }]

Here is an example of how the sort() method works with the default comparison function:

let words = ['cat', 'dog', 'bird', 'ant', 'bee'];
words.sort();
console.log(words);  // ['ant', 'bee', 'bird', 'cat', 'dog']

In this example, the sort() method compares the elements of the words array using the default comparison function, which sorts the elements in ascending order based on their Unicode code points. As a result, the elements are rearranged in the following order: ‘ant’, ‘bee’, ‘bird’, ‘cat’, ‘dog’.

If you want to specify a custom comparison function, you can pass a function as an argument to the sort() method. The comparison function should take two arguments, a and b, and return a negative value if a should be sorted before b, a positive value if a should be sorted after b, or 0 if a and b are equal.

Here is an example of how to use a custom comparison function with the sort() method:

let numbers = [5, 2, 7, 1, 3, 8, 6, 4];
numbers.sort((a, b) => b - a);
console.log(numbers);  // [8, 7, 6, 5, 4, 3, 2, 1]

In this example, the comparison function compares the elements a and b and returns the difference between them, which causes the sort() method to sort the elements in descending order.

let arr = [ 1, 2, 17 ];
// the method reorders the content of arr
arr.sort();
console.log( arr );  // 1, 17, 2

The output of the above code snippet is strange because it converted the elements of the array to string and applied string comparison on it.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post JavaScript sort() method appeared first on CodingTute.

]]>
4844
JavaScript slice() method https://codingtute.com/javascript-slice-method/ Tue, 20 Dec 2022 11:06:23 +0000 https://codingtute.com/?p=4842 The slice() method is a method in JavaScript that returns a new array that is a shallow copy of a portion of an existing array. It works by specifying the start and end indices of the portion of the array you want to copy, and it returns a new array that includes the elements from ... Read more

The post JavaScript slice() method appeared first on CodingTute.

]]>
The slice() method is a method in JavaScript that returns a new array that is a shallow copy of a portion of an existing array. It works by specifying the start and end indices of the portion of the array you want to copy, and it returns a new array that includes the elements from the start index up to but not including the end index. If the end index is omitted, the slice() method will copy all the elements from the start index to the end of the array.

Here is the syntax for the slice() method:

array.slice(start[, end])
  • start: The index at which to start copying elements from the array.
  • end: The index at which to end copying elements from the array (the element at the end index is not included in the new array). If this parameter is omitted, the slice() method will copy all the elements from the start index to the end of the array.

Here are some examples of how you can use the slice() method:

let fruits = ['apple', 'banana', 'mango', 'orange'];

// Copy the first two elements of the array
let firstTwo = fruits.slice(0, 2);  // ['apple', 'banana']
console.log(firstTwo);

// Copy all the elements of the array
let all = fruits.slice();  // ['apple', 'banana', 'mango', 'orange']
console.log(all);

// Copy the last two elements of the array
let lastTwo = fruits.slice(-2);  // ['mango', 'orange']
console.log(lastTwo);

// Copy the elements from the second to the third (inclusive)
let secondToThird = fruits.slice(1, 3);  // ['banana', 'mango']
console.log(secondToThird);

It’s important to note that the slice() method does not modify the original array. It creates a new array with the selected elements, so you can use it to create a copy of an array without modifying the original array.

You can find the complete JavaScript Tutorials here.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post JavaScript slice() method appeared first on CodingTute.

]]>
4842
JavaScript forEach() Method https://codingtute.com/javascript-foreach-method/ Tue, 03 May 2022 16:57:27 +0000 https://codingtute.com/?p=3126 The JavaScript forEach() method iterates through the array provided and executes the function passed to it for every element of the array. Javascript Developers mostly use forEach() to iterate through an array till the last element instead of using for loop. The forEach() loop will not break in middle, if you have a requirement to ... Read more

The post JavaScript forEach() Method appeared first on CodingTute.

]]>
The JavaScript forEach() method iterates through the array provided and executes the function passed to it for every element of the array.

Javascript Developers mostly use forEach() to iterate through an array till the last element instead of using for loop. The forEach() loop will not break in middle, if you have a requirement to break the loop, then forEach() is not a best option for you.

forEach() Method Example

const arr = ['a', 'b', 'c'];
arr.forEach(x => console.log(x));

// expected output: "a"
// expected output: "b"
// expected output: "c"

Syntax


forEach(callbackFn)

forEach((element) => { /* ... */ })
forEach((element, index) => { /* ... */ })
forEach((element, index, array) => { /* ... */ })

Explanation

forEach() calls the provided function once for each element in the ascending order of index.

  • callbackFn – call back function.
  • element – array element
  • index – array current index
  • array – array object which is processing.

forEach() doesn’t mutate the elements of the array until explicitly defined in the function passed. It always returns undefined.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post JavaScript forEach() Method appeared first on CodingTute.

]]>
3126
JavaScript map() function https://codingtute.com/javascript-map-function/ Sun, 01 May 2022 07:38:09 +0000 https://codingtute.com/?p=3119 In this article, you will learn about the Javascript map() function. The map() function is an array function that iterates through a given array and produces a new array base on the function passed to it. The map() method iterates the array, for every element of the array the map method calls the function passed ... Read more

The post JavaScript map() function appeared first on CodingTute.

]]>
In this article, you will learn about the Javascript map() function. The map() function is an array function that iterates through a given array and produces a new array base on the function passed to it.

The map() method iterates the array, for every element of the array the map method calls the function passed to it and produces the values for the new array based on the results it returned.

map() Method Example

const arr = [1, 2, 3, 4];
// pass a function to map
const newArr = arr.map(x => x * 2);
console.log(map);
// expected output: Array [2, 4, 6, 8]

Note: map() doesn’t change the values in the array arr. It only generates the new array based on the function passed to it.

Syntax

map(callbackFn)
map((element) => { /* ... */ })
map((element, index) => { /* ... */ })
map((element, index, array) => { /* ... */ })

Explanation

map() calls the provided function once for each element in the ascending order of index.

  • callbackFn – call back function.
  • element – array element
  • index – array current index
  • array – array object which is processing.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

Related Queries:

  • javascript map
  • map javascript
  • map in javascript
  • .map javascript
  • javascript map function

The post JavaScript map() function appeared first on CodingTute.

]]>
3119
How to Make API Calls in JavaScript https://codingtute.com/how-to-make-api-calls-in-javascript/ Fri, 19 Nov 2021 13:47:45 +0000 https://codingtute.com/?p=2922 In this tutorial, you will learn how to make API calls in javascript in 4 different ways. XMLHttpRequest JQuery Fetch API Axios XML HTTP Request XMLHttpRequest is one of the javascript global window objects. Before ES6, it is the only way of making API calls. It works in both old and new browsers and it ... Read more

The post How to Make API Calls in JavaScript appeared first on CodingTute.

]]>
In this tutorial, you will learn how to make API calls in javascript in 4 different ways.

  1. XMLHttpRequest
  2. JQuery
  3. Fetch API
  4. Axios

XML HTTP Request

XMLHttpRequest is one of the javascript global window objects. Before ES6, it is the only way of making API calls. It works in both old and new browsers and it is deprecated in ES6 but still widely used.

var request = new XMLHttpRequest();
request.open('GET', 'https://jsonplaceholder.typicode.com/todos')
request.send();
request.onload = ()=>{
    console.log(JSON.parse(request.response));
}

jQuery Ajax

ajax method in jQuery is used to perform asyncronous API calls. To use jQuery, we need to include the jQuery script file to access its methods.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

$(document).ready(function(){
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/todos",
        type: "GET",
        success: function(result){
            console.log(result);
        }
    })
})

Fetch

fetch is similar to XMLHttpRequest but here we can make async calls in a simpler way. It returns the promise and .then() method is used to perform the action on the response. Fetch is only supported in modern browsers and doesn’t work in old browsers.

fetch('https://jsonplaceholder.typicode.com/todos').then(response =>{
    return response.json();
}).then(data =>{
    console.log(data);
})

Axios

Axios is one of the popular open-source libraries to make API calls. We can also include it as a script in an HTML file to make API calls. It also returns a promise as fetch API.

It is one of the modern and preferred by most developers to make HTTP requests.

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

axios.get("https://jsonplaceholder.typicode.com/todos")
.then(response =>{
    console.log(response.data)
})

JavaScript API Calls Cheatsheet

JavaScript API Calls
JavaScript API Cheat Sheet

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.

The post How to Make API Calls in JavaScript appeared first on CodingTute.

]]>
2922
JavaScript replaceWith function https://codingtute.com/javascript-replacewith-function/ Sun, 14 Nov 2021 20:53:11 +0000 https://codingtute.com/?p=2919 The replaceWith() function in javascript is used to replace an Element in the child list of the parent with a set of Node or DOMString objects. In simpler terms, the javascript replaceWith() method will replace an Element or Node with other. Example of using replaceWith() Output Explanation At the first, we created a parent element ... Read more

The post JavaScript replaceWith function appeared first on CodingTute.

]]>
The replaceWith() function in javascript is used to replace an Element in the child list of the parent with a set of Node or DOMString objects.

In simpler terms, the javascript replaceWith() method will replace an Element or Node with other.

Example of using replaceWith()

const div = document.createElement("div");
const p = document.createElement("p");
const txt = document.createTextNode("Text Content");
p.appendChild(txt);
div.appendChild(p);

console.log(div.outerHTML);
// "<div><p>Text Content</p></div>"

const span = document.createElement("span");
const newTxt = document.createTextNode("New Text Content");
span.appendChild(newTxt);
p.replaceWith(span);

console.log(div.outerHTML);
// "<div><span>New Text Content</span></div>"

Output

<div><p>Text Content</p></div>

<div><span>New Text Content</span></div>

Explanation

At the first, we created a parent element div. We created another element p with some text content in it, then append the p element as child element to div.

Now we will create another span element and add some text to it. With the help of the replaceWith() method, we will replace the p element with the span element in the div.

The post JavaScript replaceWith function appeared first on CodingTute.

]]>
2919