Explain the difference between == and ===

  •  We all know that == is equality operator is used to compare two values in JavaScript.
  • === operator is strict equality operator
  • Both == & === are used to compare values in JavaScript. then what is the difference between == and === lets discuss in detail
  • == compares two values by converting them to same data types, 10 == ''10" will be true because string type of 10 converted in to number.
  • === compares two values without converting them to same data type. 10 === "10"
  • Use our JavaScript compiler to test your snippets
== vs === in JavaScript


1.  == ( loose Equality)
  • Checks value equality after type conversion

  • Converts operands to same type before conversion (ex: 10 == '10' here string 10 will be converted in to number) 

2. === Strict equality
  • checks value and type without conversion.
  • return false if types are different.
ScenarioLoose ==)Strict (===)
5 vs. "5truefalse
0 vs. falsetrue false
null vs. undefinedtruefalse
NaN vs NaNfalsefalse
{} vs {}falsefalse


Explanation:

1. 5 == "5" → true(loose)  
   - JavaScript converts "5" (string) to 5 (number) before comparison.  
  5 === "5" → false(strict)  
   - Different types: number vs. string.  

2. 0 == false → true(loose)  
   false is converted to 0, so 0 == 0 is true.  
  0 === false → false(strict)  
   - Number vs. boolean, so different types.  

3. null == undefined → true(loose)  
   - Special case:null andundefined are only loosely equal to each other.  
  null === undefined → false(strict)  
   - Different types:null vs.undefined.  

4. NaN == NaN → false(loose)  
   NaN is  not equal to itselfin JavaScript.  
  NaN === NaN → false(strict)  
   Same reason here: NaN is never equal to anything, including itself.  

5. {} == {} → false(loose)  
   - Objects are compared by **reference**, not by value.  
   - Different objects in memory, so alwaysfalse.  
  {} === {} → false (strict)  
   - Still different object references. 

  • "5" === "5" returns true
Remember these special cases:
  • NaN == NaN will be false even with == operator ,Use Number.isNaN(x) to check for NaN.
  • null == undefined will be true
When to use which operator:
  • always use === as it is recommended way and which avoids unexpected type conversion
  • use == for null/undefined check
  • if (x == null) { ... } // Catches both `null` and `undefined`.

splice vs slice in javascript

 'splice()' and 'slice()' are two array techniques in JavaScript that are often confused with each other. In order to resolve these ambiguities, we will compare the two methods below step by step.

splice vs slice javascript


1. Creating a Slice: The Simple Version

Purpose

Evaluates only a small part of an array without changing it.

Usage

array.slice(startIndex, endIndex);

Main Points

  • Produces a new array consisting of the elements from startIndex to endIndex (not inclusive).
  • Changes made to the original array are not visible.
  • If indexes are negative, they count from the end.
  • If no arguments are given, then array.slice() makes a shallow copy of the entire array.

Example

const fruits = ['apple', 'banana', 'cherry', 'date'];

const sliced = fruits.slice(1, 3);

console.log(sliced); // ['banana', 'cherry']

console.log(fruits); // ['apple', 'banana', 'cherry', 'date'] (that's how it remained)

2. splice(): Add/Remove Elements from an Array

Purpose

Alters the original array, inserts or deletes elements.

Syntax

array.splice(startIndex, deleteCount, item1, item2,...);

Key Points

  • Changes the original array.
  • Returns an array followed by the removed elements (if any).
  • Deleting, adding or changing elements on the spot are all possible.

Examples

a. Deleting Elements

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

const removed = numbers.splice(1, 2); // Start removing from position 1 and remove 2 from that

console.log(removed); // [2, 3]

console.log(numbers); // [1, 4, 5]

b. Adding Elements

const colors = ['red', 'blue'];

colors.splice(1, 0, 'green'); // Add 'green' after index 1 without deleting anything

console.log(colors); // ['red', 'green', 'blue']

c. Replacing Elements

const letters = ['a', 'b', 'c'];

letters.splice(1, 1, 'x'); // Replace 'b' with 'x' at index 1

console.log(letters); // ['a', 'x', 'c']

3. The Key Differences

Featureslice()splice()
Mutates OriginalNoYes
Return ValueNew array of extracted elementsArray of removed elements (if any)
Parameters(start, end)(start, deleteCount, items...)
Use CaseCopy a piece of an arrayAdd/remove elements in place

  • Slice Use it when you need to take a part from the array out without changing the original.
  • Example: Generate a copy of an array:
  • const copy = arr.slice();
  • Splice Use it when you need to remove, add, or adjust an array.
  • Example: Update a list dynamically, such as editing a to-do list.

5. Pitfalls of Using These Two Methods

Mixed Parameters Puzzle

  • Slice (1, 3) obtains elements from indices 1 and 2 (excluding index 3).
  • Splice (1, 3) starts at index 1 and removes three elements.

Splice's Mutability

  • Splice() changes the original array, so always make sure you don't need to preserve the original data before using it.

Summary

  • Slice: copy parts of an array without changing the original.
  • Splice: can edit an array directly, deleting, introducing or replacing parts.

prime number program in javascript

  • JavaScript prime number program
  • In this example will learn about how to find the number is prime or not.
  • WHATS IS PRIME NUMBER
  • A number greater than 1 with exactly two factors is called prime number.
  • Number which is divisible by 1 and itself is prime number. If it is divisible by any other number(other than 1 and itself) then it's not a prime number.
    • Consider an example of number 5 ,Which has only two factors  1 and 5. This means 5 is a prime number. Lets take one more example Number 6, which has more than two factors, i.e 1,2,3. This means 6 is not a prime number.
    • The first ten prime numbers are 2,3,5,7,11,13,17,19,23,29.
    • Note: It should be noted that 1 is non-prime number, because in the above defination already mentioned A number greater than 1 with 2 factors called prime number..

  • Here we have simple program to print the prime numbers in java script.
JavaScript program to check a number is prime number or not.

  1. <html>
  2.     <head>
  3. <script>
  4.     // javascript program to check the number is prime or not.
  5.     // prime number program in javascript
  6.     // javascript prime number program
  7.     // take input from the user
  8. const x = parseInt(prompt("Enter a number to check prime or not: "));
  9. let isPrimeNumber=true;

  10. // check if number is equal to 1
  11. if (x  === 1) {
  12.     alert("1 is neither prime nor composite number.");
  13. }

  14. // checking  if  number is greater than one or not

  15. else if (x  > 1) {

  16.     // iterating from 2 to number -1 (leaving 1 and itself )
  17.     for (let i = 2; i < x ; i++) {
  18.         if (x  % i == 0) {
  19.             isPrimeNumber = false;
  20.             break;
  21.         }
  22.     }

  23.     if (isPrimeNumber) {
  24.         alert(`${x } is a prime number`);
  25.     } else {
  26.         alert(`${x } is not a prime number`);
  27.     }
  28. }

  29. // check if number is less than 1
  30. else {
  31.     console.log("The number is not a prime number.");
  32. }
  33. </script>
  34.     </head>
  35.     <body>

  36.     </body>
  37. </html>




Output:
javascript prime number
javascript prime number program


Remove whitespace from string javascript

  • To remove white space in a string in JavaScript at the starting and ending. i.e both sides of a string we have trim() method in JavaScript.
  •  By Using .trim() method we can remove white spaces at both sides of a string.
  • var str = "       instanceofjava.com        ";
    alert(str.trim());
  • Will alert a popup with instanceofjava.com.
Javascript remove last character if comma 
  • If  we want to remove last character of a string then we need to use replace method in JavaScript.
  • str = str.replace(/,\s*$/, "");
  • We can also use slice method to remove last character.
remove white spaces in javascript

Remove specific characters from a string in Javascript


  • To remove specific character from string in java script we can use

  1. var string = 'www.Instanceofjava.com'; 
  2. string.replace(/^www.+/i, ''); 'Instanceofjava.com'

How to use Javascript confirm dialogue box

  • Confirm dialogue box in java script used to display a message for an action weather its is required to perform or not.
  • JavaScript confirm dialogue box contains two buttons "Ok" and "Cancel".
  • If user clicks on OK button confirm dialogue box returns true. If user clicks on cancel button it returns false.
  • So based on the user entered option we can continue our program. So confirm dialogue box used to test an action is required or not from user.



  • Its not possible to change values of confirm dialogue box buttons from "Ok" and "Cancel"to "Yes" and "No".
  • We need to use custom popups or jquery popups to use "Yes" and "No".
  •   var res= confirm("Are you sure to continue?");

How to use Javascript  confirm dialogue box:

  1. function myFunction() {
  2.     var text;
  3.     var res= confirm("Are you sure to continue?");
  4.     if (res == true) {
  5.         text= "You clicked OK!";
  6.     } else {
  7.         text= "You clicked Cancel!";
  8.     }
  9.     document.getElementById("demo").innerHTML = txt
  10. }
  11. </script>

Javascript confirm delete onclick:

  • If we are deleting a record from database then we need to ask user  to confirm deletion if ye really want to delete record then user checks Ok otherwise cancel based on this we can proceed furthur.
  • To implement this functionality we need to call a JavaScript function onClick()  whenever user clicks on delete record button.

Program#1: JavaScript program to show confirm dialogue box on clicking delete student record.

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <p>Click the button to delete student record</p>
  6.  
  7. <button onclick="toConfirm()">Delete student record </button>
  8.  
  9. <p id="student"></p>
  10. <script>
  11. function toConfirm() {
  12.     var text;
  13.     var r = confirm("You clicked on a button to delete student recored. Clik ok ro proceed");
  14.     if (r == true) {
  15.        //code to delete student record.
  16.         text = "You clikced on ok. Student record deleted";
  17.     } else {
  18.         text = "You clicked on cancel. transaction cancelled.";
  19.     }
  20.     document.getElementById("student").innerHTML = text;
  21. }
  22. </script>
  23.  
  24. </body>
  25. </html>

javascript confirm delete yes no

  • If we click on Ok then it will delete student record. otherwise it wont.

javascript onclick confirm dialog

Validate email address using javascript

  • One of the famous interview question in JavaScript : how to validate email address in JavaScript.
  • In order to validate a text field of HTML we need a JavaScript function.
  • On submit form we need to call a java script function to validate all fields in the form also known as client side validation.
  • Now on form submit we need to check email text field and validate it whether entered email is in correct format or not for ex: instanceofjava@gmail.com. 



JavaScript program for email validation:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var x = document.forms["Form_Name"]["txt_email"].value;
  7.     var atpos = x.indexOf("@");
  8.     var dotpos = x.lastIndexOf(".");
  9.     if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
  10.         alert("Not a valid e-mail address");
  11.         return false;
  12.     }
  13. }
  14. </script>
  15. </head>
  16.  
  17. <body>
  18. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  19. validateEmailForm();" method="post">
  20. Email: <input type="text" name="txt_email">
  21. <input type="submit" value="Submit">
  22. </form>
  23. </body>
  24.  
  25. </html>

Validate email in java-script using regular expression: on submit form validation

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var email = document.forms["Form_Name"]["txt_email"].value;
  7.   
  8.  var re = /\S+@\S+\.\S+/;
  9.     return re.test(email);
  10.   
  11.     }
  12. }
  13. </script>
  14. </head>
  15.  
  16. <body>
  17. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  18. validateEmailForm();" method="post">
  19. Email: <input type="text" name="txt_email">
  20. <input type="submit" value="Submit">
  21. </form>
  22. </body>
  23.  
  24. </html>


javascript program for email validation


HTML 5 Email validation:



  1. <form>
  2. <input type="email" placeholder="Enter your email">
  3. <input type="submit" value="Submit">
  4. </form>
email address validation code in java script

How to get table cell data using JavaScript

How to get table row data in javascript:

  • When we are working with HTML tables we will get a scenario like to get whole table rows data, or table td values , table cell value in JavaScript.
  • For that we need to read the table by using JavaScript.
  • lets see example on get table cell data using java script.
  • Before that lets see how to read the data of table using JavaScript
  • To find number of rows of a table by using table id in JavaScript.



  1. var numberOfrows=document.getElementById("tableData").rows.length;

  • Get number of cells or number of tds inside each tr (table row)

  1. var numberoftds = document.getElementById("tableData").rows[0].cells.length;


  • JavaScript get table row values get table td data

  1. var numberoftds = document.getElementById("tableData").rows[0].cells.item(0).innerHTML;


Example on get table each row data using javascript:



  1. <script type="text/javascript">
  2. function checkFun() {

  3. var n1 = document.getElementById("tableData").rows.length;

  4. var i=0,j=0;
  5. var str="";
  6.  
  7. for(i=0; i<n1;i++){
  8.  
  9. var n2 = document.getElementById("tableData").rows[i].cells.length;
  10.  
  11. for(j=0; j<n2;j++){
  12.  
  13. var x=document.getElementById("tableData").rows[i].cells.item(j).innerHTML;\
  14.  
  15.     str=str+x+":";
  16.  
  17. }
  18. str=str+"#";
  19.    
  20. }
  21.    document.getElementById("tablecontent").innerHTML=str;

  22.    
  23. }
  24. </script>




  1. <body onload="checkFun()">
  2.  
  3. <table id="tableData" border="1">
  4.     <tr>
  5.         <td >37</td>
  6.         <td >46</td>
  7.         <td >3</td>
  8.         <td >64</td>
  9.     </tr>
  10.     <tr>
  11.         <td >10</td>
  12.         <td >4</td>
  13.         <td >7</td>
  14.         <td >21</td>
  15.     </tr>
  16.     
  17. </table>
  18. <p id="tablecontent" ></p>
  19.  </body>


get table cell row td data value javascript

  • Here in this example on page loading we called the JavaScript function
  • For that used body onload="func()" .
  • Practice this example in your System.

Select Menu