# JavaScript Program to identify Prime Number

The blog provides the step by step solution for writing JavaScript program to find the Prime Number from the given number.  The user should have knowledge on below topics Control Statements in JavaScript

##### What is a prime number ?

The prime number is the number which is only divisible by 1 or itself. Example : 2,3,5,7,11

##### Steps to write Prime Number Program
• Prompt user to enter the number
• Create temporary variable isNumberPrime = true;
• Check if the enter number is equal to 1 or less than 1 , then display “1 cannot be Prime Number”
• Check if Number is greater than 1, then iterate each number till it reaches to the given Number
• If Number divided with iteration Value =0, then display “Number cannot be Prime Number”
• else display ” Number is Prime Number”
``` <script>
let userValue = parseInt(prompt("Enter the number: "));
let isNumberPrime  = true;

if (userValue == 1) {
document.writeln("1 is neither prime nor composite number.");
}
else if (userValue < 1) {
document.writeln("Negative number cannot be a prime number");
}
else if (userValue > 1) {
for (let i = 2; i < userValue; i++) {
if (userValue % i == 0) {
isNumberPrime = false;
break;
}
}

if (isNumberPrime) {
document.writeln(`\${userValue} is a prime number`);
} else {
document.writeln(`\${userValue} is a not prime number`);
}
}

</script>```

Output:

```Enter the number: 7
7 is a prime number

Enter the number: 1
1 is neither prime nor composite number.

Enter the number: -11
Negative number cannot be a prime number```

# JavaScript Program to Convert Celsius to Fahrenheit

The blog provides the step by step solution to write a JavaScript program to convert Celsius to Fahrenheit. To understand the below given program , user should have knowledge on below given topics

##### Celsius to Fahrenheit formula

The below given is the Formula to convert Celsius value to Fahrenheit

``fahrenheit = celsius * 1.8 + 32``
##### Steps to convert Celsius to Fahrenheit
• Prompt user to get the Celsius Number
• Compute Fahrenheit by using the above formula
• Display final value for Fahrenheit

## Fahrenheit to Celsius formula

The below given is the Formula to convert Fahrenheit to Celsius value

``celsius = (fahrenheit - 32) / 1.8``
##### Steps to convert Fahrenheit to Celsius
• Prompt user to get the Fahrenheit Number
• Compute Celsius by using the above formula
• Display final value for Celsius
``` <script>

let X = prompt('Enter the Celsius  number: ');
let Y = prompt('Enter the Fahrenheit number: ');

let output1 ;
let output2;

document.writeln(` Input for Celsius': \${X}` +"<br>");
document.writeln(` Input for  Fahrenheit ': \${Y}` +"<br>");

output1 = (X * 1.8) + 32; // calculates fahrenheit
output2 = (Y - 32) / 1.8  // calcluates celsius

document.writeln("----Calcualte Celsius to Fahrenheit --------"  +"<br>");
document.writeln(`Fahrenheit ': \${output1}` +"<br>");

document.writeln("----Calcualte Fahrenheit to Celsius --------"  +"<br>");
document.writeln(`celsius ': \${output2}` +"<br>");

</script>```

Output:

```Input for Celsius': 5
Input for Fahrenheit ': 1
----Calcualte Celsius to Fahrenheit --------
Fahrenheit ': 41
----Calcualte Fahrenheit to Celsius --------
celsius ': -17.22222222222222```

# Program to find the Square Root in JavaScript

The blog provides the step by step solution to find the square root of the given number. The square root is applicable for the numeric number. If string is passed to calculate square root, NaN (Not a Number) is returned.

##### Steps to write square root program
• Prompt user to enter the number
• Use Math.sqrt(number) to calculate the square root of the given number
``` <script>

let X = prompt('Enter the first number: ');
let Y = prompt('Enter the second number: ');

let output1 ;
let output2;

document.writeln(`Value for X ': \${X}` +"<br>");
document.writeln(`Value for Y ': \${Y}` +"<br>");

output1 = Math.sqrt(X);
output2 = Math.sqrt(Y);

document.writeln("----Calcualte Square Root--------"  +"<br>");
document.writeln(`Square Root  for X ': \${output1}` +"<br>");
document.writeln(`Square Root  for Y ': \${output2}` +"<br>");

</script>```

Output:

```Value for X ': 5
Value for Y ': -21
----Calcualte Square Root--------
Square Root for X ': 2.23606797749979
Square Root for Y ': NaN```

# program to swap two numbers in JavaScript

The blog provides the step by step solution to write a JavaScript program to swap two numbers. To understand the below given program , user should have knowledge on below given topics

##### Steps to be swap two numbers

The below given are the steps to write number swapping program in JavaScript

• Prompt user to enter the first number (X)
• Prompt user to enter the Second number (Y)
• Create a Temporary variable (Z) to store the value of first number (X)
• Assign first number (X) with the value of Second number (Y)
• Assign Second number (Y) with the value of Temporary variable Z
``` <script>

let X = prompt('Enter the first number: ');
let Y = prompt('Enter the second number: ');
let Z;
document.writeln(`Value for X ': \${X}` +"<br>");
document.writeln(`Value for Y ': \${Y}` +"<br>");

//swap variables
Z = X;
X = Y;
Y = Z;
document.writeln("Swap Values for X and Y "  +"<br>");
document.writeln(`Value for X ': \${X}` +"<br>");
document.writeln(`Value for Y ': \${Y}` +"<br>");
</script>```

Output:

```Value for X ': 5
Value for Y ': 7
Swap Values for X and Y
Value for X ': 7
Value for Y ': 5```

# String Method example in JavaScript

The blog provides the JavaScript String method examples. The blog helps you understand the available JavaScript String methods and how to be used in your programming.

##### JavaScript String charAt()

The JavaScript String charAt() method returns the character at specified position /index
Integer range : between 0 and 65535
Parameters : index which indicates the index value of the character. Default value is 0

`Syntax: String.CharAt(index)`
##### JavaScript String charCodeAt()

The JavaScript String charCodeAt() method returns the UTF-16 code for the integer value.
Integer range : between 0 and 65535
Parameters : index which indicates the character position. Default value is 0.

`Syntax: String.CharCodeAt(index)`
##### JavaScript String codePointAt()

The JavaScript String codePointAt() method returns an integer denoting the Unicode point value
Parameters : index which indicates the character position

Return Value: Number when processed else undefined value

`Syntax: String.codePointAt(index)`
##### JavaScript String fromCodePoint()

The JavaScript String codePointAt() method returns the string created from given sequence of code points

`Syntax: `String.fromCodePoint(num1, ..., numN)``
```<script>
let name = "Mohit Sharma!";

let utf16Value1 = name.charCodeAt(0);
document.writeln(`Converted UTF-16 code for '\${name.charAt(0)}': \${utf16Value1}` +"<br>");

let utf16Value2 = name.charCodeAt(1);
document.writeln(`Converted UTF-16 code for '\${name.charAt(1)}': \${utf16Value2}` +"<br>");

let utf16Value3 = name.charCodeAt(2);
document.writeln(`Converted UTF-16 code for '\${name.charAt(2)}': \${utf16Value3}` +"<br>");

let utf16Value4 = name.charCodeAt(3);
document.writeln(`Converted UTF-16 code for '\${name.charAt(3)}': \${utf16Value4}` +"<br>");

let utf16Value5 = name.charCodeAt(4);
document.writeln(`Converted UTF-16 code for '\${name.charAt(4)}': \${utf16Value5}` +"<br>");

let utf16Value6 = name.charCodeAt(name.length - 1);
document.writeln(`Converted UTF-16 code for '\${name.charAt(name.length - 1)}': \${utf16Value6}` +"<br>");

document.writeln("String codePointAt() example"+"<br>");

let codepointValue7 = name.codePointAt(6);
document.writeln(`CodePoint value for '\${name.charAt(6)}': \${codepointValue7}` +"<br>");

document.writeln("String fromCodePoint() example" + "<br>");
let StringFromCodePoint = String.fromCodePoint(77, 111, 104, 105, 116);
document.writeln(`String fromCodePoint()value is  : \${StringFromCodePoint}` +"<br>");

</script>```

Output:

```Converted UTF-16 code for 'M': 77
Converted UTF-16 code for 'o': 111
Converted UTF-16 code for 'h': 104
Converted UTF-16 code for 'i': 105
Converted UTF-16 code for 't': 116
Converted UTF-16 code for '!': 33

String codePointAt() example
CodePoint value for 'S': 83

String fromCodePoint() example
String fromCodePoint()value is : Mohit```
##### JavaScript String toLowerCase(), toUpperCase()

The JavaScript String toLowerCase() method returns the string in Lower Case

`Sytax: String.toLowerCase()`

The JavaScript String toUpperCase() method returns the string in Upper Case

`Sytax: String.toUpperCase()`
##### JavaScript String startWith() , endsWith()

The JavaScript String startsWith() method validates if the given string starts with the specified characters

`Syntax: String.startsWith(searchString, position)`

The JavaScript String endsWith() method validates if the given string ends with the specified characters

`Syntax: String.endsWith(searchString, position)`
##### JavaScript String replace()

The JavaScript replace() method replaces the first occurrence of the pattern with the specified string and returns the modified string. The pattern could be the string value or the Regex value which is considered for replacement.

```Syntax: String.replace(pattern, replacement)
pattern: string which is to be considered for replacement
replacement: actual string value to be used for replacement```
##### JavaScript String replaceAll()

The JavaScript replaceAll() method replaces all the occurrences of the pattern with the specified string and returns the modified string. The pattern could be the string value or the Regex value which is considered for replacement.

```Syntax: String.replace(pattern, replacement)
pattern: string which is to be considered for replacement
replacement: actual string value to be used for replacement```

`Syntax: String.padStart(StringLength, padString)`

`Syntax: String.padEnd(StringLength, padString)`
``` <script>
let name = "  Mohit Sharma!  ";
let title =" This is JavaScript String Example. String is easy to understand";
let pattern = "String";
document.writeln("------- String trim() example -------" +"<br>");
document.writeln(`Name after trim()': \${name.trim()}` +"<br>");

document.writeln(" ------- String UPPERCASE example -------" +"<br>");
document.writeln(`Name after toUpperCase()': \${name.toUpperCase()}` +"<br>");

document.writeln(" -------String lowercase example -------" +"<br>");
document.writeln(`Name after toLowerCase()': \${name.toLowerCase()}` +"<br>");

document.writeln("------- String replace example ------- " +"<br>");
let replaced_text = title.replace(pattern, "Replace String" );
document.writeln(`Modified Title': \${replaced_text}` +"<br>");

document.writeln("------- String replaceAll example -------" +"<br>");
let replaceAll_text = title.replaceAll(pattern, "Replace String");
document.writeln(`Modified Title': \${replaceAll_text}` +"<br>");

document.writeln("-------String padStart example ------- " +"<br>");

document.writeln(" -------String padEnd Example -------" +"<br>");

</script>```

Output:

```------- String trim() example -------
Name after trim()': Mohit Sharma!
------- String UPPERCASE example -------
Name after toUpperCase()': MOHIT SHARMA!
-------String lowercase example -------
Name after toLowerCase()': mohit sharma!
------- String replace example -------
Modified Title': This is JavaScript Replace String Example. String is easy to understand
------- String replaceAll example -------
Modified Title': This is JavaScript Replace String Example. Replace String is easy to understand

# JavaScript Program to Add Two Numbers

The blog provides the step by step solution to write the JavaScript program to add two numbers and display their sum.

To understand the below given program , user should have knowledge on below given topics

##### Steps for Adding two Numbers in JavaScript
• Input user to enter the first number and store the value into variable
• Input user to enter the second number and store the value into variable
• Create another variable to store the sum of first number and second number
• Use the Operator + to sum the values
• Display the total sum
```<html>
<body>
<script>
const firstNumber = parseInt(prompt('Input first number '));
const secondNumber = parseInt(prompt('Input second number '));
const sum = firstNumber + secondNumber;

document.writeln(`The sum of \${firstNumber} and \${secondNumber} is \${sum}`);
</script>
</body>
</html> ```

# Event Delegation in JavaScript

The blog provides the details on the usage of event delegation in JavaScript. The Event Delegation is most powerful event handling pattern which is implemented using the Event Capturing and Event Bubbling in JavaScript.

Read the blog to understand Event Bubbling and Capturing in JavaScript

When an event(button click) is triggered on an element, then the event bubbles up from the originating element to the top of the DOM tree (reaching to that element’s ancestors) which is known as event bubbling. The target element is the element that actually caused the event to trigger and is stored in a property of the event object.
Event Delegation allows to add an event handler to an element, wait for an event to bubble up from a child element and determines the target element which initiated the event.

##### Event Delegation example in JavaScript
```<html>
<body>
<button data-action="save">Save</button>
<button data-action="search">Search</button>
</div>
<script>
constructor(e) {
this._elem = e;
e.onclick = this.onClick.bind(this); // (*)
}
save() {
}
}
search() {
}
onClick(event) {
let action = event.target.dataset.action;
if (action) {
this[action]();
}
};
}
</script>
</body>
</html>  ```
##### Behavior pattern in event delegation

The Event Delegations also support the “behavior” pattern. The below given is the example where the event is triggered based on the attribute behavior

```<html>
<body>
Counter: <input type="button" value="1" data-counter>
<script>

if (event.target.dataset.counter != undefined) { // if the attribute exists...
event.target.value++;
}
});
</script>
</body>
</html>  ```

References:  https://javascript.info/event-delegation

# pointer events in JavaScript

The blog provides the details on the usage of pointer events in JavaScript. The pointer events are useful for capturing the events related to pointing devices, such as a mouse, a pen/stylus, a touchscreen, etc.

All the popular browsers are supported with Pointer Event Level 2 Specification

##### What are Point Event Properties ?

The below given are the pointer event properties supported by all browsers

##### What are the Pointer Event types ?

The below given are the pointer event types supported by all browsers

##### Multi-touch support in pointer event

Pointer event is useful where the user can perform multi-touch like mobile devices, touch screen monitors, etc

The below steps are performed when multiple fingers are touched

1. User First Finger Touch: The Pointer Event captures the isPrimary =true and pointerId
2. User Second Finger Touch : The Pointer Event captures the isPrimary =false and pointerId
##### pointercancel event

The pointercancel event is triggered when the ongoing pointer interaction is aborted due to some reason so that no more pointer events can be trigerred.

• The pointer device hardware was disabled
• change in device orientation ( tablet / mobile rotation)
• in case browser does not consider it as a pointer event
##### pointer event example in JavaScript
```window.addEventListener("pointerdown", detectInputType);
function detectInputType(event) {
switch(event.pointerType) {
case "mouse":
/* mouse input detected */
break;
case "pen":
/* pen/stylus input detected */
break;
case "touch":
/* touch input detected */
break;
default:
/* pointerType is empty (could not be detected)
or UA-specific custom type */
}
}```

# Event bubbling and Capturing in JavaScript

The blog provides the details on the Event Bubbling and Event Capturing in JavaScript. The JavaScript allows to invoke events based on the user action.

##### What is Event Bubbling in JavaScript ?

Let’s consider the below example where onClick event is captured and each HTML element when click performs a specific action.

The HTML Form contains <DIV> Tag , then <p> and then <button>.

When an event happens on an element, it executes the element event handlers on it, then on its parent, then traverse all the way to the ancestors which means the below hierarchy is being followed

When the user click the button

• then button onClick event is triggered
• then onClick event on the <DIV> tag is triggered
• then onClick event on the <Form> is triggered.

When the user click on the DIV

• then onClick event on the <DIV> tag is triggered
• then onClick event on the <Form> is triggered.
```<html>
<title>
JavaScript Event Propagation Example
</title>
<body>
<form onclick="alert('Event Propagation -Form')">Click on Form
<div onclick="alert('Event Propagation - Div-> Form')">Click on DIV Tag
<p onclick="alert('Event Propagation - Paragaph -> Div-> Form')">
Click on Paragragh </p>
<button onclick = "alert('Event Propagation - Button -> Div -> Form')">
Click on Button </button>
</div>
<style>
body * {
margin: 15px;
border: 1px solid blue;
background-color :lightgrey;
}
</style>
</form>
</body>
</html>```

## Explain event.target

The element that actually caused the event is called target element. Thus the mostly deeply nested element ( Button Click in our example) is accessible as event.target in JavaScript

event.target = is the target element that initiated / caused the event to trigger

this = is the current element that is running the event handler, accessible as event.CurrentTarget

##### How to Stop Event Bubbling in JavaScript ?

The Event Bubbling is the event that starts from the “target element” and traverse upwards to the ancestor element which could be html or document object or windows object.

When the handler considers that the event has been processed , then it stops the bubbling by calling the method event.stopPropagation()

```<head>
<title>
JavaScript Event Stop Propagation Example
</title>

<body>
<button onclick="event.stopPropagation()">Click me</button>
</body>
</html>```

When an element has multiple event handlers and one of the event has stopped bubbling by calling the method event.stopPropagation(), the other event handlers still excutes.

In such cases, we need to call the method event.stopImmediatePropagation() which stops the bubbling for all the event handlers associated with the element.

##### What is Event Capturing in JavaScript ?

The Event Capturing is opposite to the Event Bubbling in JavaScript. In Event Capturing is the process in which the event starts from the ancestor and traversed down to the element.

When the user click the button, then it traverses from

Form -> DIV -> Button

Syntax for Event Capturing

``el.addEventListener(type, listener, useCapture)``

Parameters:
type: indicates the event type
listener: function call when the specified event type occurs
useCapture: true for capturing phase

##### What is Event Propagation in JavaScript ?

As per the Standard DOM Events, the event propagation can be classified into 3 phases

• Capturing Phase : Traverse event from ancestor to actual element
• Target Phase : Target element which caused the event
• Bubbling Phase: Traverse event from element to ancestor event

The event propagation flow phase are illustrated in the following diagram from W3C Standard DOM Events

# Event Handling in JavaScript

The blog provides the details on the Event Handling in JavaScript. The Front End application allows user to perform action on the available data like user clicks on a button, user enters the data, user press a particular key, user moves the mouse, user closes the window, etc..

The action performed by the user when the state of the object is changed, known as Event. The JavaScript captures these events and allows the execution. This process is known as Event Handling

JavaScript Libraries like React.js , Vue.js, Angular.js provides the Event and Event Handling as these libraries uses JavaScript.

The generated HTML element contains the set of events which can trigger JavaScript Code.
JavaScript Events are a part of the Document Object Model (DOM) Level 3.

The below given are the HTML Event Handlers as per the HTML 4.01 specification.

##### <form> Level Events

The below given are the events which can be triggered on the Form Level

##### <body> Level Events

The below given are the events which can be triggered on the Body or the Frameset Level

##### Keyboard Events

The below given are the events which can be triggered on the Keyboard Level

##### onClick Event Type Example in JavaScript

onClick Event Type is the most commonly used event in the UI application. Whenever the user click on the HTML elements the onClick event is triggered. The onClick event can be used to capture user input, perform form validations, displaying waning messages, etc.

```<!DOCTYPE html>
<html>
<script>
function userMsg() {
alert("The onClick Event Message is displayed when user clicks button ");
}
</script>
<body>

<h3> JavaScript - onClick Event Type Example </h3>
<button onclick = "userMsg()">Click me</button>
</body>
</html>  ```

The below given is another onClick event in the paragraph element.

```<HTML>
<BODY>
<h3> JavaScript - onClick Event Type Example </h3>
<p id = "root">Click me</p>
<script>
document.getElementById("root").onclick = function() {  userMsg()  };

function userMsg() {
document.getElementById("root").innerHTML = "The onClick Event Message is displayed when user clicks button ";
document.getElementById("root").style.color = "Blue";
document.getElementById("root").style.backgroundColor = "Grey";
document.getElementById("root").style.fontSize = "15px";
document.getElementById("root").style.border = "4px solid Grey";
}
</script>

</BODY>
</HTML>```

## onSubmit Event Type Example

When the Front End Application performs the “Submit” button, the onSubmit event type is triggered which could be used to validate the entered form details, submit request data as per the given action, displaying error and success messages, etc..

```<html>
<script type = "text/javascript">
function validateFormDetails() {
alert("Validate method executes with onSubmit Event Type ");
}
</script>

<body>
<h3> JavaScript - onSubmit Event Type Example </h3>
<form method = "POST" action = "" onsubmit = "return validateFormDetails()">
<input type = "submit" value = "Submit" />
</form>
</body>
</html>```
##### HTML5 Standard Events

The below given is the complete list of events supported as part of HTML5 specification

# static method in JavaScript

The blog provides the usage of static variables and static method in JavaScript. The static keyword is used to create a static method or static variable which indicates that the static method or static variable cannot be called on the instance of the class.

The static methods are often used as utility functions to create or clone objects.

The static variables are useful for caches, reading configurations or other related data which need to be shared across instances.

##### How Static methods are to be defined in JavaScript ?

The below given points need to be considered while creating static methods

• The keyword “static” is to be used to create static methods
• More than one static methods can be created in the class
• If two static methods are created with same name, the last one will be invoked by JavaScript
• The static methods are often used as utility functions to create or clone objects
• The static method allows to invoke another static method by using “this” keyword
• The non -static method cannot invoke static method by using “this” keyword
• The static method can be invoked from the class constructor
##### JavaScript Static Method Example

The below given is the simple static method example

1. Creates a static variable to store membership status
2. Creates static method – getMembershipStatus() to get the membership status
3. Creates another static method which internally calls static method – getMembershipStatus()
```<script>
class customerClass {
static customerType = 'Gold Membership';
static getMembershipStatus() {
return 'Customer has ' + this.customerType + ' in the system';
}
static customerStatus() {
return ' Customer Status :::' + this.getMembershipStatus() ;
}
}
document.writeln(customerClass.getMembershipStatus() +"<br>");
// invokes the static method to get customer membership status
document.writeln(customerClass.customerStatus() +"<br>");
// static method calls the static method to get customer membership status
</script> ```

Output :

```Customer has Gold Membership in the system
Customer Status :::Customer has Gold Membership in the system```
##### Static Method Example using class constructor
1. Define the Class
2. Create static method
3. Invoke the static method from constructor
```<script>
class StaticMethodConsCall {
constructor() {
document.writeln(StaticMethodConsCall.invoke()+"<br>");
document.writeln(this.constructor.invoke());
}

static invoke() {
return 'This is static method call'
}
}
var v = new StaticMethodConsCall();
</script> ```

# Enable JavaScript in browsers

JavaScript is one of the most commonly used scripting supported by all the browsers provided with built-in support for JavaScript. Sometimes it is required to know how JavaScript can be Enabled / Disabled in the browser. The blog provides the steps for enabling and disabling JavaScript support in browsers like Internet Explorer, Firefox, chrome, and Opera

##### Enable JavaScript in Internet Explorer

Perform the below steps to enable JavaScript in Internet explorer

• Tools → Internet Options from the menu
• Select Security tab from the dialog box.
• Click Custom Level button
• Search for Scripting option
• Select Enable radio button in the Active scripting
• Click OK
##### Disable JavaScript in Internet Explorer

Perform the below steps to disable JavaScript in Internet explorer

• select Disable radio button in the Active scripting
##### Enable / Disable JavaScript in Firefox

Perform the below steps to enable / disable JavaScript in Mozilla Firefox

• Search for list of configure options in the browser
• Type type javascript.enabled in the search bar
• Select option → select toggle to enable / disable the JavaScript option
##### Enable JavaScript in Chrome

Perform the below steps to enable JavaScript in Chrome

• Click Settings
• Click Privacy -> Content settings
• Select “Allow all sites to run JavaScript (recommended)”
##### Disable JavaScript in Chrome

Perform the below steps to disable JavaScript in Chrome

• lick Settings
• Click Privacy -> Content settings
• Select “Do not allow any site to run JavaScript”
##### Enable JavaScript in Opera

Perform the below steps to enable JavaScript in Opera

• Select Tools → Preferences