Menu

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

update a JSON object using JavaScript

JSON objects are frequently used as a data format in the web world. Many times, we encounter situations where we need to update the JSON object or a part of the JSON object (JSON object property). In this blog, we will discuss how to update a part of a JSON object using JavaScript.

For example, we have a json object that have dimentions.

let dimensions = [

    {"height": 100, "width": 50},

    {"height": 200, "width": 150},

    {"height": 300, "width": 250},

    {"height": 400, "width": 350}

  ]

Supoose we now need to update the first width of the first diemension in the object. First check the current value with below statement.

dimensions[0].width

This will return 50. Since, the width of first diemnsion index is 50.  

Now update the value of width from index 0.

dimensions[0].width = '90'

For example, we have update the value with 90. Now, when you access the width value from index 0, it will return 90. Try accessing the first object from dimentions array object.

dimensions[0]

This will retun first object which is now updated width value. 

{

    "height": 100,

    "width": "90"

}

 

Below is the screenshot of the updating JSON object property use-case.

Update JSON object using JS
Update JSON object using JS


let, var and const variables in JavaScript or ReactJS

In ReactJS, the differences between let, var, and const variables are the same as in JavaScript. Here's a brief explanation of each:  

   

1. let: The let keyword declares a block-scoped variable that can be reassigned. It allows you to define variables that are limited in scope to the block, statement, or expression in which they are used. For example, you can use let variables inside loops or conditional statements.  

   Examples:


let lx;

jsvariables(lx)

function jsvariables(lx) {
    
    console.log(lx)
}

console.log(lx);


//Output

undefined
undefined


let lx = 5;

jsvariables(lx)

function jsvariables(lx) {
    lx = 7;
    console.log(lx)
}

console.log(lx);


//Output

7
5


let lx = 5;

jsvariables(lx)

function jsvariables(lx) {
    let lx = 7;
    console.log(lx)
}

console.log(lx);


//Output

let lx = 7;
        ^

SyntaxError: Identifier 'lx' has already been declared


jsvariables()

function jsvariables() {
    let lx = 7;
    console.log(lx)
}

console.log(lx);


//Output

7

console.log(lx);
            ^

ReferenceError: lx is not defined

2. var: The var keyword declares a function-scoped variable that can be reassigned. It is the older way of declaring variables in JavaScript before the introduction of let and const. Unlike let, var declarations are not limited to the block scope but rather to the function scope. This means that var variables are accessible anywhere within the function in which they are declared.  

   Examples:

var vx =12;

jsvariables(vx)

function jsvariables(vx) {
    console.log(vx)
}

console.log(vx);


//Output

12
12


var vx = 12;

jsvariables(vx)

function jsvariables(vx) {
    var vx = 13;
    console.log(vx)
}

console.log(vx);


//Output

13
12


var vx = 12;

jsvariables(vx)

function jsvariables(vx) {
    vx = 13;
    console.log(vx)
}

console.log(vx);


//Output

13
12


var vx;

jsvariables(vx)

function jsvariables(vx) {
    var vy = 12;
    console.log(vy)
}

console.log(vx);


//Output

12
undefined


var vx;

jsvariables(vx)

function jsvariables(vx) {
    vx = 12;
    console.log(vx)
}

console.log(vx);


//Output

12
undefined


var vx;

jsvariables(vx)

function jsvariables(vx) {
    vx = 12;
    console.log(vx)
}
vx = 16;
console.log(vx);


//Output

12
16

3. const: The const keyword declares a block-scoped variable that cannot be reassigned. It is used to declare constants, which are variables that cannot be changed after they are declared. const variables must be initialized with a value at the time of declaration, and you cannot reassign them later.  

   Examples:

const cx = 12;

jsvariables(cx)

function jsvariables(cx) {
    console.log(cx)
}

console.log(cx);


//Output

12
12

const cx;

jsvariables(cx)

function jsvariables(cx) {
    console.log(cx)
}

console.log(cx);


//Output

const cx;
      ^^

SyntaxError: Missing initializer in const declaration


const cx;
cx = 12;
jsvariables(cx)

function jsvariables(cx) {
    
    console.log(cx)
}

console.log(cx);


//Output

const cx;
      ^^

SyntaxError: Missing initializer in const declaration

In general, it is recommended to use const for variables that will not be reassigned, let for variables that will be reassigned within their scope, and avoid using var as it has some potential issues related to scoping and hoisting. However, the choice between let and const ultimately depends on your specific use case and requirements.

Callback function JavaScript and NodeJS

Lets understand the callback fucntion in NodeJS using the below geocode example.

Here we have created geoCode function with two paramters, first parameter will take input of the location name and second parameter the function that needs to call. Similary, we can add or pass any number of paramters in fucntion as per need.

const geoCode = (location, callback) => {
    const data = {
        location: location,
        latitude: 0,
        longitude: 0
    }
    callback(data)
}

 

When we call the geoCode function, we are here passing a city name and second paramter a fucntion itself that print the return data from callback on console.
 
geoCode('New Delhi', (callbackData) => {
    console.log(callbackData)
});

Return

{ location: 'New Delhi', latitude: 0, longitude: 0 }

Immediately Invoked Function Expression (IIFE) in JavaScript

There is a situation where we want to make a function and execute that function immediately at the same place where we have written. These function can be written in JavaScript without any function name. The approach which we follow to do so is called Immediately Invoked Function Expression (IIFE). Let's see an example of this.

(function() {

//write something in IIFE

}

Hence, if a develop come to any point where there is no need to function name then they could use Immediately Invoked Function Expression (IIFE). 

How to write JavaScript function without function name? and Write an immediate invoke function in JavaScript?

Answer of all these questions is Immediately Invoked Function Expression. 

JavaScript closest() method

JavaScript closest() method of the Element interface traverses the element until it finds a node that matches the specified CSS selector. 
Syntax of JavaScript closest method syntax is element.closest(css selector).

HTML code snippet


<article>
  <div id="article">
    This is article 
    <div id="title">
      Here is article title
      <div id="description">Here is article description</div>
    </div>
  </div>
</article>

JavaScript closest example

const desElement = document.getElementById("description");

// the closest ancestor with the id of "title"
console.log(desElement.closest("#title")); //this will return <div id="title">

// the closest ancestor which is a div in a div
console.log(desElement.closest("div div")); //this will return <div id="description">

// the closest ancestor which is a div and has a parent article
console.log(desElement.closest("article > div")); //this will return <div id="article">

// the closest ancestor which is not a div
console.log(desElement.closest(":not(div)")); //this will return <article>


Reference

-- https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

Decimal number check using JavaScript

While working with numbers specially decimal number or price or balance. A developer may face an issue where number is not coming in decimal format, and just appearing in round figure or only with one digit after decimal. like 12.2, 20, and 5.5

In this situation how to handle this on frond-end and show balance or price always in two decimal digits. Below is the code sample. 


if (cardBalanceData) {
	console.log('card balance '+cardBalanceData.balance);
	var gcBalance = cardBalanceData.balance;
	gcBalance = (gcBalance.toString().indexOf('.') >= 0) ? gcBalance : gcBalance+'.00';
	console.log("card balance in 2 decimal value:: "+ gcBalance);
}

Here in above JavaScript code, line #4 checking the gcBalance has decimal (.) into this, in case gcBalance doesn't have decimal value then append .00 into gcBalance otherwise print gcBalance as it is. 

How to get query string values in JavaScript?

Using JavaScript now its very easy to get the URL parameters or query parameters or query string using window object. Below is the sample code snippet of reading the URL parameters.

For example we are accessing the below URL where we have two URL parameters present, and we want to read the source and location values from given or any URL.

https://javascript.jorvee.com/geturlparams.html?source=blog&location=javadeveloper

const urlParams = Object.fromEntries(new URLSearchParams(window.location.search).entries());

 

All the URL parameters are now present as an object in urlParams constant. Now to access any url parameter, just access using urlParams.<name of the parameter>. 
e.g. var urlSource = urlParams.source;

Here, source is a url parameter and it will return "blog" as source value.


Learn JavaScript Free | URL parameters and query String
JavaScript


Module not found error in ReactJS application

Issue:

ModuleNotFoundError: Module not found: Error: Can't resolve '../../../public/page-data/sq/d/3428351200.json' in 'C:\git\gatsby-starter-hello-world\src\components\City'


failed Re-building development bundle - 0.215s

ERROR in ./src/pages/index.js?export=default 6:0-44

Module not found: Error: Can't resolve '/components/City/City.js' in 

'C:\git\gatsby-starter-hello-world\src\pages'


Resolution: 

The import statement for City component is not correct, please put the correct path of the React component.  

Select only one checkbox from a group of checkboxes

Create a group of checkboxes and allow only one selection. Here is the sample code for of creating checkbox using simple HTML and JavaScript.


HTML code

<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
  <script>
  var checkboxChecked;
  document.addEventListener('input',(e)=> {
    if(e.target.getAttribute('name')=="termsCondition") {
      if(checkboxChecked)
        checkboxChecked.checked=false;
      }
      e.target.checked=true;
      checkboxChecked=e.target;
  })
  </script>
</head>
<body>
  <p>Select only one checkbox from a group of checkboxes.</p>
  <input type="checkbox" name="termsCondition" value="1" /> 1
  <input type="checkbox" name="termsCondition" value="2" /> 2
  <input type="checkbox" name="termsCondition" value="3" /> 3
  <input type="checkbox" name="termsCondition" value="4" /> 4
</body>
</html>

Output



Learn JavaScript and HTML

Cannot set properties of undefined (setting 'display')

In a scenario, I was trying to hide some HTML elements from the DOM at the runtime using the plain Javascript display property. When I was running the below JavaScript code to set the display=none for a particular element I was getting the error "Cannot set properties of undefined (setting 'display')".


document.getElementsByClassName("Feedback").style.display = "none";


This error I was seeing because the getElementsByClassName function was returning a list and hence system was unable to set the property because of ambiguity between list items. So to fix this we have to specify the index number next to getElementsByClassName function like below to set the style display=none.


document.getElementsByClassName('Feedback')[0].style.display = 'none';


The above statement will hide the first occurrence of an element that has class "Feedback".

Check and replace the attribute value using JS

 We can use JQuery to find the element and then we can replace the attribute value of an HTML element. Below is a JS code snippet to find and replace an attribute value.


$this.next().attr('aria-expanded', function(index, attr){

    return attr == 'false' ? 'true' : 'false';

});

Unchecked runtime.lastError: The message port closed before a response was received.

 While working with any JS framework we may encounter the error Unchecked runtime.lastError: The message port closed before a response was received. on the console of Chrome browser but not on any other browser.

Cause of Issue:

This we may experience if we have an extension installed in the Chrome browser. That extension is triggering events and looking for some information from the web page.

Resolution:

Remove the extensions from the Chrome browser.


Reference


Uncaught SyntaxError: Unexpected token const

const may already be written in your code which is not terminated. Please terminate that first using a semicolon(;) and then declare a const again.

OR

Use the same first const and for the second constant declaration simply write the constant name and assign value without using the const keyword.  




Create a calculator using JavaScript callback function.

In this post we are going to create a calculator using simple HTML and JavaScript callback function. Using callback functions we have to write less code in compare to writing huge line of code using simple JavaScript functions. Callback and promises are the very useful and fastest way to write the code.

Without any further delay, lets start the coding to create a web based simple calculator using the javaScript callback functions. We will discuss the theory part of callback function and promises other article.

Create a html page with name calculator.html. copy the below code snippet and paste in calculator.html file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<html>
<title>Calculator</title>
    <head>
        <script src="js/calculator.js"></script>
    </head>
<body>
<h3>Calculator</h3>
Number 1: <input id="number1" type="number"/><br /><br />
Number 2: <input id="number2" type="number"/><br /><br />
<input type="button" onclick="calc(addNum)" value="Add" id="add" />
<input type="button" value="Multiply" onclick="calc(multiplyNum)" id="multiply" />
<input type="button" value="Divide" id="divide" onclick="calc(divideNum)" />
<br /><br />
Result: <input id="result" type="number"/><br />
</body>

</html>

Now create a folder with name js in the same directory where you have created your html page, this js folder is to separate the js file from other files.

Now open the js folder and create a calculator.js file.

Copy the below js code snippet the paste it in your calculator.js file.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function calc(callback) {
    var n1 = parseFloat(document.getElementById("number1").value);
    var n2 = parseFloat(document.getElementById("number2").value);
    var result = callback(n1, n2);
    document.getElementById("result").value = result;
}

function multiplyNum(n1, n2) {
    return n1 * n2;
}
function divideNum(n1, n2) {
    return n1 / n2;
}
function addNum(n1, n2) {
    return n1 + n2;
}

Now open your calculator.html file in browser and see the result. below is the screen shot of the calculator.

callback function calculator-rashidjorvee
callback function calculator

You may download the complete exercise from GitHub https://github.com/RashidJorvee/callbackFunctionJS

Create JS Object from JSON text

How to traverse on JSON (JavaScript object notation) object using JavaScript and how to traverse JSON array using JavaScript?

Below is the simple HTML and JavaScript based program, which have a JSON data object and further that json object have json array. Using JavaScript we will read that json data one by one and generate output for end user, and later that output we will show on html page.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<html>
<body>
<h2>Create JS Object from JSON String</h2>
 <p id="output">
 </p>
<script>
var txt = '{"employees":[' +
'{"firstName":"Rashid","lastName":"Jorvee" },' +
'{"firstName":"Java","lastName":"Script" },' +
'{"firstName":"Node","lastName":"JS" }]}';


var jsonData = JSON.parse(txt);
var output="";
for (var i = 0; i < jsonData.employees.length; i++) {
    var counter = jsonData.employees[i];
    console.log(counter.firstName);
    output += "First name: " +  counter.firstName +  ", Last Name: " +counter.lastName +"<br />";
 document.getElementById("output").innerHTML = output;
   
}

</script>
</body>
</html>

Output:

Create JS Object from JSON String

First name: Rashid, Last Name: Jorvee
First name: Java, Last Name: Script
First name: Node, Last Name: JS

Output on browser console: 

console output on browser debugger console
console output on browser debugger console

Difference between == and === in JavaScript

In this post we will see what is the difference between double equals(==) and triple equals(===) compare operator in JavaScript program. 

Double equals (==) 

Double equals compare two values and return true when those values have exactly same text and should be in same case. Please note values are case sensitive in javascript. 
e.g. var a = "Rashid";

       var b = "rashid";
       a==b // It will return false since both the values are not in the same case.

Triple equals (===) 

Triple equals compare two values as well as it also compare the datatype of those value, and return true when both the things (text and datatype) of those values get matched with other value.
e.g. var c = 7;

       var d = "7";
       c===d // it will return false; since c stored a numeric value and d stored a string value hence datatype didn't match for those values.

Compare values ignoring case 

You can also compare the values in javascript by ignoring the case sensitive. To do that first we have to convert given values in either lowerCase or upperCase by using the toUpperCase() or toLowerCase function.
e.g. var a = "Rashid";

       var b = "rashid";
       a.toUpperCase()==b.toUpperCase() // It will return true 

Code snippet

Below is the complete code snippet which you could refer to practice double equals(==) and triple equals(===) in javaScript.

If you face any issue please fill free to ask your question in comment section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
<head>
    <title>Cpmpare values using == and ===</title>
    <script type="text/javascript">
     var a = "Rashid";
     var b = "rashid";
     var c = 7;
     var d = "7";
     document.writeln("Result of a==b, where a="+a +" b="+b +"::  ");
     document.write(a==b);
     document.write("<br />")
     document.writeln("Result of a===b, where a="+a +" b="+b +"::  ");
     document.writeln(a===b);
     document.write("<br />")
     document.writeln("Result of a===b with toUpperCase, where a="+a +" b="+b +"::  ");
     document.writeln(a.toUpperCase() === b.toUpperCase());
     document.write("<br />")
     document.writeln("Result of c==d, where a="+c +" b="+c +"::  ");
     document.writeln(c==d);
     document.write("<br />")
     document.writeln("Result of c===d, where a="+c +" b="+c +"::  ");
     document.writeln(c===d);
     document.write("<br />")
    </script>
</head>
<body>
<span>This code snippet is copyright with rashidjorvee.blogspot.com.</span>    
</body>
</html>

Output

Result of a==b, where a=Rashid b=rashid:: false
Result of a===b, where a=Rashid b=rashid:: false
Result of a===b with toUpperCase, where a=Rashid b=rashid:: true
Result of c==d, where a=7 b=7:: true
Result of c===d, where a=7 b=7:: false 

AJAX call with GET method and request data

In his article, we are going to look at how to call an endpoint and read the JSON response using AJAX call. Also, we will see how we append and pass URL parameters to that endpoint URL. Below is the code snippet.

var data is a type of object, that holds all the URL parameters that get appended with endpoint URL when AJAX calls the endpoint.

<script>
	function myFunction() {
    var amount = document.getElementById("tuition-amount").value;

    var startDate = document.getElementById("start-date").value;
    var endDate = document.getElementById("end-date").value;

    var data = { startDate:"01/25/2022",
    	endDate:"03/12/2022",
        paymentDate:"01/02/2022",
        campus:"delhi"};

        $.ajax({
  	    type: "GET", 
            url: "https://rashidjorvee/services/latefine.cfm", 
            data: data,
            success: function(response) {
                document.getElementById("late-fine-amount").innerHTML = response.amount;
            },
            dataType: "json"
          })
		}
</script>

How to read any attribute value using the element class name using JS?

Using the DOM function we could find the element using class name and then from that search list go to first index and get the required attribute.

document.getElementsByClassName('class_name')[0].getAttribute('id');