Showing posts with label JavaScript. Show all posts

Difference between .some(), .includes(), and .findIndex()

Let’s compare .some(), .includes(), and .findIndex() to see why .some() is the best choice in this case.


  1. Why Not .includes()?

How .includes() Works

  • .includes(value) only works for exact matches in an array.

  • It checks if the array contains the exact string or number.

Why It Won’t Work Here

Your case needs partial matching (window.location.hostname.includes(host)), but .includes() only checks for exact matches.

🔴 Example: Doesn't Work for Partial Matching

const hosts = ["localhost", "127.0.0.1"];

const isLocal = hosts.includes(window.location.hostname);

console.log(isLocal);

❌ This only works if window.location.hostname is exactly "localhost" or "127.0.0.1", but it fails if the hostname is "localhost:4200" (which is common in Angular development).

ES6 Methods in JavaScript

ES6 (ECMAScript 2015) introduced several new methods for working with arrays, strings, objects, and more. These methods enhance the functionality of JavaScript, making it more efficient and readable. Here’s a summary of some key ES6 methods:

1. Array Methods

Array.from(): Creates a new array from an array-like or iterable object.
javascript
Copy code
const str = 'hello';

const arr = Array.from(str); // ['h', 'e', 'l', 'l', 'o']



Array.of(): Creates a new array with the given arguments.
javascript
Copy code
const arr = Array.of(1, 2, 3); // [1, 2, 3]



Array.prototype.find(): Returns the first element in an array that satisfies the provided testing function.

javascript
Copy code
const arr = [5, 12, 8, 130, 44];

const found = arr.find(element => element > 10); // 12

Comprehensive Guide to JavaScript Array Methods: Manipulation, Access, and Iteration Techniques

 JavaScript provides a wide variety of array methods that make working with arrays more convenient and efficient. Here's an overview of the most commonly used JavaScript array methods:

1. Mutator Methods

These methods modify the array they are called on.

  • push(element): Adds one or more elements to the end of an array and returns the new length.
  • pop(): Removes the last element from an array and returns that element.
  • shift(): Removes the first element from an array and returns that element.
  • unshift(element): Adds one or more elements to the beginning of an array and returns the new length.
  • splice(start, deleteCount, item1, item2, ...): Adds, removes, or replaces elements in an array. Returns an array of the removed elements.
  • reverse(): Reverses the order of the elements in an array in place.
  • sort(compareFunction): Sorts the elements of an array in place and returns the sorted array.
  • fill(value, start, end): Fills all the elements from a start index to an end index with a static value.

How to load multiple JavaScript files in the given order using jQuery?

By using this method we can load multiple JavaScript files in the same order


Example

In the above example  js files are loaded in the given oder
First loaded 1.js then 2.js and finally 3.js

jQuery Inline Message Box Plugin

Inline Message Box plugin is a light weight (4.26 KB) jQuery plugin. Features include 6 types of message box, no additional css required, closable, auto closable, option parameters for full control of message box functionality etc.. You can use it very easily.

How to use it
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="inline-message-box.min.js"></script>
Configuration

Option Default Value Description
messageBoxType null Define the message box type here. 6 types of message box type is available. if this option is null, then it is the default message box. Other types are success, error, fatalerror, warning & info.
message null Set your message here.
closeButton true If you don't need 'close' button, set to false.
enabled false If you want to close message box automatically, then it set to true.
milliseconds 30000 This value is used for automatically close this message within '30' sec.

Solved: Object doesn’t support property or method ‘assign’

Object.assign() method is not supported in IE, but there is a polyfill available

Put the below line of code to your <head> for solving this issue.

Highlight non matching words in a string using JavaScript



Demo

How to declare an array in javascript?

JavaScript arrays are used to store multiple values in a single variable. An array is a special variable, which can hold more than one value at a time.

Method 1:

var cars = new Array("Saab", "Volvo", "BMW");

Access the Elements of an Array
var name = cars[0];//Saab
This statement modifies the first element in cars:
cars[0] = "Opel";

'Saab' is replaced by 'Opel'.

Method 2:

var cars = ["Saab", "Volvo", "BMW"];

Method 3:

var person = [];

Eg:
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length;         // person.length will return 3
var y = person[0];             // person[0] will return "John"

Method 4:

var person = {firstName:"John", lastName:"Doe", age:46};

In this example, person.firstName returns 'John'

How do I know if a variable is an array?

Creating a sample array.
var fruits = ["Banana", "Orange", "Apple", "Mango"];

Method 1:

Array.isArray(fruits);     // returns true

NB: THis method not supported in older browsers.

Method 2:

To overcome the method 1, Cretae an isArray() function
function isArray(x)
{
    return x.constructor.toString().indexOf("Array") > -1;
}

The function above always returns true if the argument is an array.

Or more precisely: it returns true if the object prototype contains the word "Array".

Method 3:

The instanceof operator returns true if an object is created by a given constructor:
fruits instanceof Array     // returns true

How to perform a case-insensitive search in JavaScript?

The search() method searches a string for a specified value, and returns the position of the first occurrence of the specified searchvalue, or -1 if no match is founds.
The search value can be string or a regular expression.

Eg:
Case sensitive search
var str = "WELCOME to WebSpeckle.com";
var n = str.search("COM");
Output is: 3 //Found in third position
var str = "Welcome to WebSpeckle.com";
var n = str.search("COM");
Output is: -1 //Not found
Case insensitive search
var str = "Welcome to WebSpeckle.com";
var n = str.search(/COM/i); Output is: 3 //Found in third position

How do i get the current URL in JavaScript?

The window.location object can be used to get the current page URL and also we can use to redirect the browser to a new page.

The window.location.href property returns the URL of the current page.
Eg:
<script>
Console.log("The curret page URL is: " + window.location.href);
</script>
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of the current page
window.location.protocol returns the web protocol used (http: or https:)
window.location.assign loads a new document

How to empty an array in JavaScript?

JavaScript arrays are used to store multiple values in a single variable.An array is a special variable, which can hold more than one value at a time.

Here we have an array
Eg:
var Arr = [1,2,3,4,5];
4 ways to empty this array

Method 1:

Arr = [];

Method 2:

Arr.length = 0;

Method 3:

Arr.splice(0,Arr.length)

Method 4:

while(Arr.length > 0)
    Arr.pop();
}

Clearing object array

var website = {url:"http://www.webspeckle.com", type:"blog"};
console.log(website); //{ url:"http://www.webspeckle.com", type:"blog"}
var websiteData = null;
for(websiteData in website)
{
    website[websiteData] = null;
}
console.log(website); //{ url:null, type:null}

window.location.search vs window.location.href

window.location.href
The href property sets or returns the entire URL of the current page.

window.location.search
The search property sets or returns the querystring part of a URL, including the question mark (?).

Suppose  our current page url is "http://www.example.com/p/online-html-editor?demoid=4545454545"
window.location.href is "http://www.example.com/p/online-html-editor?demoid=4545454545"
window.location.search is "?demoid=4545454545"


Demo

How to show a confirmation box in JavaScript?

In JavaScript 'confirm()' function is used for this purpose. This method displays a dialog box with a specified message, along with an OK and a Cancel button.

The confirm() method returns true if the user clicked "OK", and false otherwise.

The parameter type of this function is 'String'. This method does not accept HTML string as parameter. For 'line-breaks' please use '\n'.

var UserAction = confirm("Are you sure you want to delete?");
if (UserAction  == true)
{
    //User pressed on OK button
}
else
{
    //User pressed on CANCEL button
}
Final code and demo is here


Demo

How can i show confirmation box before page reload?

In some cases before page refresh/reload we have to show confirmation message to the user. The page reload only if the user allow. In JavaScript we can use 'onbeforeunload ' function for this case.

I have checked the below code in latest Chrome & Firefox.

<script>
window.onbeforeunload = function(event)
{
    return confirm("Confirm refresh");
};
</script>
Final code and demo is here


Demo

How to decode a URL in JavaScript?

The decodeURI() function is used to decode a URI.

Eg:
<script>
var URL = "https://www.example.com/p/online-html-editor.html?filename=How%20to%20decode%20a%20URL%20in%20JavaScript";
var EncodedURL = decodeURI(URL);
</script>
Final code and demo is here

Demo

How to encode a URL in JavaScript?

The encodeURI() function is used to encode a URI.
This function encodes special characters, except: , / ? : @ & = + $ #

Eg:
<script>
var URL = "https://www.example.com/p/online-html-editor.html?filename=How to encode a URL in JavaScript";
var EncodedURL = encodeURI(URL);
</script>
Final code and demo is here

Demo

How to add slim progress bars in JavaScript?

Use 'NProgress.js' library for nanoscopic progress bar.

NProgress.start() — shows the progress bar
NProgress.set(0.4) — sets a percentage
NProgress.inc() — increments by a little
NProgress.done() — completes the progress

<script>
NProgress.start();
$(document).ready(function ()
{
    NProgress.done();
});
</script>
Final code and demo is here

Demo

How to create Pie chart in JavaScript?

Pie chart is a type of graph in which a circle is divided into sectors that each represent a proportion of the whole. Pie charts are very widely used in the business world and the mass media.

Pie charts are probably the most commonly used charts. They are divided into segments, the arc of each segment shows the proportional value of each piece of data. They are excellent at showing the relational proportions between data.

Here i am using chartjs library for creating pie chart. 

Example Usage

var myPieChart = new Chart(ctx,{
    type: 'pie',
    data: data,
    options: options
})
;

Dataset Properties

The pie chart allows a number of properties to be specified for each dataset. These are used to set display properties for a specific dataset. For example, the colour of a the dataset's arc are generally set this way.

Name Type Description
label String The label for the dataset which appears in the legend and tooltips.
backgroundColor Color[] The fill color of the arcs in the dataset.
borderColor Color[] The border color of the arcs in the dataset.
borderWidth Number[] The border width of the arcs in the dataset.
hoverBackgroundColor Color[] The fill colour of the arcs when hovered.
hoverBorderColor Color[] The stroke colour of the arcs when hovered.
hoverBorderWidth Number[] The stroke width of the arcs when hovered.

Config Options 

These are the customisation options specific to Pie charts. These options are merged with the global chart configuration options, and form the options of the chart.

NameTypeDefaultDescription
cutoutPercentageNumber0 - for pieThe percentage of the chart that is cut out of the middle.
rotationNumber-0.5 * Math.PIStarting angle to draw arcs from.
circumferenceNumber2 * Math.PISweep to allow arcs to cover
animation.animateRotateBooleantrueIf true, the chart will animate in with a rotation animation. This property is in the options.animation object.
animation.animateScaleBooleanfalseIf true, will animate scaling the chart from the center outwards.

Data Structure 

For a pie chart, datasets need to contain an array of data points. The data points should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. You also need to specify an array of labels so that tooltips appear correctly

data = {
    datasets: [{
        data: [10, 20, 30]
    }],

    // These labels appear in the legend and in the tooltips when hovering different arcs
    labels: [
        'Red',
        'Yellow',
        'Blue'
    ]
};
You can download the latest version of Chart.js from the GitHub releases or use a Chart.js CDN.

The final code & demo is here

Demo