JavaScript String indexOf() Method

JavaScript String indexOf() Method

The indexOf javascript () method returns the position of the first occurrence of an element of a string or arrays. This method returns -1 if the value is not found or NULL. It is a case-sensitive method.

SYNTAX – string.indexOf(searchValue, start)

Where,

The string represents the given string to be checked on.

searchValue – required value to search for

start – The position from where to start. It is an optional field. If start<0, the search starts from the back of the string i.e. start+string length is used.

The method returns the first position where the value exists. It returns -1 if the value never occurs. The method compares the search Value with elements of the array or string using strict equality. In arrays, if the slots are empty, it skips them.

indexOf() is an ESI feature and it is supported by all browsers.

For Example –

const arr = [1,4,5,6,7];

arr.indexOf(1); // 0

arr.indexOf(8); // -1

arr.indexOf(6,1); // 3

JavaScript setTimeout() Method

JavaScript setTimeout() Method

The ‘setTimeout()’ function in JavaScript is used to execute a function or evaluate an expression after a specified number of milliseconds have passed. It returns a timer ID, which can be used to clear the timeout using the ‘clearTimeout()’ function.

Syntax: ‘setTimeout(function, delay, [arg1, arg2, …])’

For example:

setTimeout(function() {

  console.log("Hello World!");

}, 1000);

This will execute the function ‘console.log(“Hello World!”);’ after 1000 milliseconds (1 second) has passed.

‘setTimeout()’ is a JavaScript function that allows you to schedule a function to be executed after a certain amount of time has passed. The function takes two parameters: the function you want to execute, and the amount of time in milliseconds that should pass before the function is executed. The function returns a timer ID, which can be used to cancel the scheduled function execution using the ‘clearTimeout()’ function. It’s important to note that ‘setTimeout()’ only triggers the function once, whereas ‘setInterval()’ will execute the function repeatedly at the specified interval. ‘setTimeout()’ can be useful for things like showing a message or animation after a certain amount of time, delaying the execution of a function for a smoother user experience, or for scheduling a function to be executed at a specific time in the future. You can use setTimeout() in conjunction with other JavaScript functions and methods to create complex interactions and behaviors on your website or web application.

In addition to scheduling function execution, ‘setTimeout()’ can also be used to evaluate an expression after a certain amount of time. This can be done by passing a string containing the expression as the first parameter instead of a function. For example:

setTimeout("console.log('Hello World!')", 1000);

This will evaluate the expression “console.log(‘Hello World!’)” after 1000 milliseconds (1 second) have passed.

It’s also important to note that ‘setTimeout()’ uses a single thread, so multiple ‘setTimeout()’ calls will be executed in the order in which they were scheduled, and not simultaneously. This means that if you schedule multiple timeouts with different delays, the function with the shortest delay will be executed first. ‘setTimeout()’ is a widely used function in JavaScript, and it can be useful in many different types of web applications and projects, such as creating a countdown timer, creating a slideshow, or creating a game.

Another use case for ‘setTimeout()’ is to delay the execution of a function or expression until a certain condition is met. For example, you can use ‘setTimeout()’ in combination with a ‘while’ loop to repeatedly check for a condition and only execute the function or expression once the condition is true. ‘setTimeout()’ can also be used with event handlers to delay the execution of a function or expression until an event has occurred. For example, you can use ‘setTimeout()’ to delay the execution of a function or expression until a button is clicked, or until a page has finished loading. It’s also worth noting that ‘setTimeout()’ is a client-side function and it only runs in the browser. It doesn’t execute on the server side.

Conclusion:- ‘setTimeout()’ can be a powerful tool for creating interactive and dynamic web pages and web applications. It is widely used in JavaScript development to create animations, games, and other types of interactive features.

JavaScript String split() Method

JavaScript split  – The split() method takes a pattern as input and divides a given String into an ordered list of substrings by finding the pattern, putting these substrings into an array, and returning the array. It does not change the original string. If (” “) is used as the separator, the string is split between the words.

SYNTAX – str.split(separator, upto)

separator – A string or any expression which is used for splitting. It is optional. If in any case omitted, it will return an array of original strings.

  • upto – It is a non-negative integer that decides the number of splits. Items after upto are excluded. An array may contain lesser entries than upto if the end of the string is reached before the limit is reached. If upto is 0 return [].

 

For example – 

Split a string into characters 

const arr = str.split(“”);

Use any letter as a separator:

const arr = str.split(“o”);

If the separator parameter is omitted/not given

const arr = str.split();

JavaScript addEventListener() with Examples

JavaScript addEventListener()

AddEventListener javascript is a method in JavaScript that allows developers to attach an event handler to a specific element on a webpage. This method is commonly used to add functionality to a website or application, such as responding to user interactions like clicks or key presses.

 

When using addEventListener, the first argument is the type of event you want to listen for, such as “click” or “keydown”. The second argument is the function you want to run when the event occurs, known as the event handler. This function can take in an event object as a parameter, which contains information about the event that occurred.

 

For example, if you want to attach a click event to a button element, you could use the following code:

const button = document.querySelector('#my-button');
button.addEventListener('click', function() { // On clicking,
    // the message inside the console.log() will be shown
    console.log('Clicked');
});

Another useful feature of addEventListener is that it can be used to attach multiple event handlers to the same element. This allows you to add multiple functionality to a single element, without overwriting any existing event handlers.

button.addEventListener('click', function() { // On clicking,
    //the message inside the console.log() will be shown
    console.log('Button was clicked'); 
});
// Now adding a second eventListener to the same button
button.addEventListener('click', function() { // On clicking,
    //the message inside the console.log() will be shown
    console.log('Button was clicked again'); 
});

JavaScript Hoisting (with Examples)

Javascript Hoisting

JavaScript hoisting is a behavior of variable and function declarations in JavaScript where variable and function declarations are moved to the top of the scope. In other words, variable and function declarations are hoisted to the top of the code, and are accessible throughout the entire scope.

For example, consider the piece of code given below:

console.log(variable_1); // undefined
var variable_1 = 5;

Here, the variable ‘variable_1’ is declared after it is accessed. However, due to hoisting, JavaScript will interpret this code as if it were written as:

var variable_1;
console.log(variable_1); // undefined
variable_1 = 5;

This behavior applies to function declarations as well. For example, consider the following code:

testing(); // "Testing this"


function testing() {
  console.log("Testing this");
}

Here, the function ‘testing’ is declared after it is called. However, due to hoisting, JavaScript will interpret this code as if it were written as:

function testing() {
    console.log("Testing this");
  }
  
  testing(); // "Testing this"

In summary, JavaScript hoisting is a behavior of variable and function declarations in JavaScript where variable and function declarations are moved to the top of the scope. It is important to understand this behavior and the difference between variable and function declarations and assignments in order to write more robust and maintainable code

JavaScript Frameworks: What Are and How Do They Work?

Javascript frameworks

JavaScript is a versatile and powerful programming language that has become the backbone of modern web development. One of the most important aspects of JavaScript development is the use of frameworks. Frameworks are collections of pre-written code that provide a structure and set of tools for developers to build web applications quickly and efficiently.

There are many different Javascript frameworks available, each with its own strengths and weaknesses. Some of the most popular frameworks include Angular, React, and Vue.js.

Angular is a comprehensive framework developed by Google. It is often used for large-scale enterprise applications and is known for its powerful two-way data binding and dependency injection features. Angular also has a large community and many resources available for developers.

React, on the other hand, is a JavaScript library developed by Facebook. It is primarily used for building user interfaces and is known for its efficient handling of updates and changes to the DOM (Document Object Model). React also has a large community and many resources available for developers.

React Native is a framework that allows developers to build mobile apps using JavaScript and the React library. It provides a way for developers to write code that can run on both iOS and Android platforms, using the same codebase. This can save a significant amount of time and resources compared to building a separate app for each platform. React Native also offers a more efficient way of building mobile apps, as it uses native components rather than WebViews, resulting in better performance and a more native user experience. It is widely popular among developers and has a large community and many resources available for developers.

Vue.js is a progressive JavaScript framework that is known for its simplicity and flexibility. It is often used for building small to medium-sized web applications and has a smaller learning curve than Angular or React. Vue.js also has a large community and many resources available for developers.

In addition to these major Javascript frameworks, there are also many other frameworks and libraries available for specific purposes, such as Ember.js for building ambitious web applications, and Backbone.js for building single-page web applications.

Ember.js is built around the concepts of conventions over configuration and provides a set of conventions and best practices for building scalable and maintainable web applications. Ember.js also provides a set of powerful tools and features such as Ember CLI, Ember Data, and Ember Inspector, which make it easier for developers to build web applications quickly and efficiently. Ember.js also has a strong focus on developer productivity and offers a productive development environment with its Ember CLI, Ember Inspector, and Ember Twiddle tools. Ember.js is widely used by companies like LinkedIn, Microsoft, Netflix and many other. Ember.js has a strong and active community and many resources available for developers.

When choosing a framework, it’s important to consider the specific needs of your project and the skills of your development team. For example, if you’re building a large-scale enterprise application, Angular may be the best choice. On the other hand, if you’re building a small to medium-sized web application, Vue.js may be a better choice.

In addition to the framework itself, developers also have access to a wide range of tools and libraries that can help them build web applications quickly and efficiently. Some popular tools include webpack for bundling and building applications, and npm (Node Package Manager) for managing dependencies and downloading packages.

Overall,  Javascript  frameworks are an essential part of modern JavaScript development. They provide a structure and set of tools that make it easier for developers to build web applications quickly and efficiently. With so many different  Javascript  frameworks available, it’s important to choose the one that best fits the needs of your project and the skills of your development team. In addition to the frameworks themselves, developers also have access to a wide range of tools and libraries that can help them build web applications quickly and efficiently.

JavaScript Events: Understand with Examples

JAVASCRIPT EVENTS

JavaScript events are actions or occurrences that happen in the browser, such as a button click or a page load. These events can be used to trigger JavaScript functions, allowing developers to create interactive and dynamic websites. In this article, we’ll take a closer look at how events work in JavaScript and how you can use them to improve the user experience on your website.

Event Listeners

The first step in working with events in JavaScript is to set up an event listener. An event listener is a function that waits for a specific event to occur, and then runs a specific code when that event happens. For example, you can use an event listener to listen for a button click, and then run a function when the button is clicked.

To set up an event listener, you use the addEventListener() method. The method takes two arguments: the type of event to listen for, and the function to run when the event occurs. For example, this code sets up an event listener for a button click:

var button = document.querySelector("button");

button.addEventListener("click", function() {

    alert("Button was clicked!");

});

This code selects a button element on the page and assigns it to the variable “button”. The addEventListener() method is then called on the button variable, with “click” as the first argument (to listen for a click event) and an anonymous function as the second argument (to run when the button is clicked).

Event Bubbling and Capturing

When an event occurs, it doesn’t just trigger the event listener on the element that was directly interacted with, but also on all its parent elements. This behavior is known as event bubbling.

An event first triggers on the innermost element, then on the direct parent element, then on the grandparent element, and so on, all the way up to the <html> element. This is the default behavior of events in JavaScript.

You can also use the event.stopPropagation() method to stop the event from bubbling up to the parent elements.

On the other hand, event capturing is the opposite of event bubbling. It starts from the outermost element and works its way down to the innermost element.

You can specify the capturing phase by passing true as the third parameter to the addEventListener() method.

document.querySelector("html").addEventListener("click", function() {

    console.log("html clicked!");

}, true);

Event Delegation

Event delegation is a technique that allows you to add a single event listener to a parent element, rather than adding multiple event listeners to individual child elements.

This can be useful when you have a large number of elements that need to handle the same event, as it allows you to avoid adding an event listener to each element individually.

For example, this code adds a click event listener to a parent <ul> element that listens for clicks on any of its child <li> elements:

var list = document.querySelector("ul");

list.addEventListener("click", function(event) {

    if (event.target.tagName === "LI") {

        console.log("List item clicked!");

    }

});

In this example, the event listener is added to the <ul> element, and the event.target property is used to check which child element was actually clicked. This way, the same event listener can handle clicks on any of the child <li> elements, without having to add a separate event listener to each one individually.

Event Types

JavaScript provides a wide variety of event types that you can listen for, including:

  • click: fired when an element is clicked
  • submit: fired when a form is submitted
  • load: fired when a page finishes loading
  • mouseover: fired when the mouse pointer moves over an element
  • keydown: fired when a key is pressed down
  • resize: fired when the browser window is resized

These are just a few examples of the many events that are available in JavaScript. You can find a full list of event types in the official JavaScript documentation.

Conclusion

In this article, we’ve covered the basics of working with events in JavaScript, including how to set up event listeners, the difference between event bubbling and capturing, and event delegation. We also looked at some of the common event types that you can listen for, and how you can use them to create interactive and dynamic websites. With this knowledge, you should be well on your way to creating engaging and responsive user interfaces using JavaScript.

JavaScript Arrow Function

Arrow functions in JavaScript

arrow function javascript, also known as “fat arrow” functions, is a new way to write JavaScript functions that were introduced in ECMAScript 6. These functions are a shorthand way of writing anonymous functions and have become a popular choice among developers due to their concise syntax and improved readability.

One of the biggest benefits of arrow functions is that they allow developers to write shorter, more concise code. For example, the traditional way of writing a function to return the square of a number would look like this:

function square(x) {

  return x * x;

}

With arrow functions, the same function can be written like this:

const square = x => x * x;

As you can see, the arrow function version is much shorter and easier to read. This is because the keyword “function” and the curly braces are not needed when using arrow functions.

Another benefit of arrow functions is that they automatically bind the value of “this” to the surrounding context. In traditional JavaScript functions, “this” can be a tricky concept to understand and often requires the use of the “bind” function to ensure that “this” is referencing the correct object. With arrow functions, “this” is always bound to the context in which the function was defined, making it much easier to understand and use.

For example, consider the following code:

const obj = {

  name: "John",

  greet: function() {

    console.log(`Hello, ${this.name}`);

  }

};

 

obj.greet(); // Output: "Hello, John"

In this example, the “greet” function is a property of the “obj” object and “this” is bound to the “obj” object. However, if we were to use a traditional function to define the “greet” function, “this” would be bound to the global object and the output would be “Hello, undefined”.

const obj = {

  name: "John",

  greet: function() {

    console.log(`Hello, ${this.name}`);

  }

};

 

const greet = obj.greet;

greet(); // Output: "Hello, undefined"

With arrow functions, we can avoid this problem altogether:

const obj = {

  name: "John",

  greet: () => {

    console.log(`Hello, ${this.name}`);

  }

};

 

const greet = obj.greet;

greet(); // Output: "Hello, John"

Arrow functions also provide a more consistent behaviour in callbacks and higher-order functions. For example, when passing a function as a callback to a higher-order function like “map”, “filter”, or “reduce”, it is often necessary to use “bind” to ensure that “this” is bound to the correct object. With arrow functions, this is not necessary as “this” is always bound to the surrounding context.

In addition, arrow functions can also be used to create shorter, more concise code when using the “new” keyword. For example, the subsequent code creates a brand-new item with the use of the “new” key-word and a conventional feature:

function Person(name) {

  this.name = name;

}

 

const john = new Person("John");

console.log(john.name); // Output: "John"

With arrow functions, the same code can be written like this:

const Person = name => ({ name });

const john = new Person("John");

console.log(john.name); // Output: "John"

As you can see, the arrow function version is much shorter and easier to read. This is because the keyword “function” and the curly braces are not needed when using arrow functions.

In conclusion, arrow functions are a powerful tool for writing concise, readable, and consistent JavaScript code. They offer a shorthand way of writing anonymous functions, automatically bind “this” to the surrounding context, and provide a more consistent behavior in callbacks and higher-order functions. If you’re not already using arrow functions in your JavaScript code, it’s definitely worth taking the time to learn about them and start incorporating them into your projects.

However, it’s also worth noting that arrow functions do have some limitations. They cannot be used as constructors, and cannot be used to add methods to an object using the “prototype” property.

So, while arrow functions are a great addition to the JavaScript language, it’s important to understand when and where they should be used to write the most efficient and effective code.

Overall, arrow functions are a powerful tool for JavaScript developers, and their concise and consistent syntax makes them a great choice for any project. So, if you’re not already using arrow functions in your code, it’s definitely worth taking the time to learn about them and start incorporating them into your projects.

Dom in Javascript | JS HTML DOM

DOM In Javascript

For HTML and XML documents, there is a programming interface known as Document Object Model, often abbreviated as DOM. DOM in javascript  allows the user to interact with the elements of a web page using  JavaScript.

When a web page is loaded into a browser, the browser creates a tree-like structure called the DOM tree that represents the different elements of the page. Each element in the DOM In the Javascript tree is called a node. The DOM In Javascript allows you to access these nodes and manipulate them.

 

Using the DOM, you can:

 

Traverse the DOM tree and access individual nodes.

Modify the content and attributes of elements.

Add and remove elements from the page.

Change the styles of elements.

 

You can use JavaScript to access the DOM In Javascript using various properties and methods such as querySelector(), getElementById(), getElementsByTagName(), etc. Once you have access to a specific element, you can use its properties and methods to manipulate it. For example, you can use the textContent property to change the text inside an element, the src property to change the source of an image, or the classList property to add or remove classes from an element.

const selecth1 = document.querySelector('h1');
console.log(selecth1.textContent); // Outputs the text content of the heading
heading.textContent = 'New Heading'; // Changes the text content of the heading

JavaScript contains() – How and when to use it?

JavaScript contains() – Collect javascript is a JavaScript library that provides a set of helpful utility functions for working with arrays and objects. One of the methods provided by the library is the “contains Javascript ” method, which can be used to determine if a given array or object contains a specific value.

The contains  Javascript method can be used to check if an array contains  Javascript  a specific value. Here is an example of how to use the contains  Javascript  method to check if an array of numbers contains the number 5:

const collect = require('collect.js');
let numbers = [1, 2, 3, 4, 5];
let containsFive = collect(numbers).contains(5);
console.log(containsFive); // true

The contains method can also be used to check if an object contains a specific key. Here is an example of how to use the contains  Javascript  method to check if an object has a property named “age”:

const collect = require('collect.js');
let person = { name: "John", age: 30 };
let Age_present = collect(person).contains("age");
console.log(Age_present); // true