<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ashwani Singh</title>
    <description>The latest articles on DEV Community by Ashwani Singh (@imashwani).</description>
    <link>https://dev.to/imashwani</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1273747%2F5ccd8625-a416-4970-8cde-c85da8edcef2.png</url>
      <title>DEV Community: Ashwani Singh</title>
      <link>https://dev.to/imashwani</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/imashwani"/>
    <language>en</language>
    <item>
      <title>XMLHttpRequest has been blocked by CORS policy:</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Sun, 02 Mar 2025 19:39:18 +0000</pubDate>
      <link>https://dev.to/imashwani/xmlhttprequest-has-been-blocked-by-cors-policy-24l7</link>
      <guid>https://dev.to/imashwani/xmlhttprequest-has-been-blocked-by-cors-policy-24l7</guid>
      <description>&lt;p&gt;&lt;strong&gt;Error&lt;/strong&gt;&lt;br&gt;
"Access to XMLHttpRequest at '&lt;a href="http://localhost:5001/auth/register" rel="noopener noreferrer"&gt;http://localhost:5001/auth/register&lt;/a&gt;' from origin '&lt;a href="http://localhost:3000" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt;' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This error occurs because your backend server (localhost:5001) is not allowing requests from your frontend (localhost:3000) due to CORS (Cross-Origin Resource Sharing) policy restrictions. To fix this, you need to configure your backend to allow requests from your frontend.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fix for Node.js (Express) Backend&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If you're using Express.js, install the cors package and configure it:&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;1. Install cors&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Run this command in your backend project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install cors

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;2. Update Your Backend Code&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Modify your Express server code (index.js or server.js):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const cors = require("cors");

const app = express();

// Allow requests from frontend (localhost:3000)
app.use(cors({
    origin: "http://localhost:3000",
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"]
}));

app.use(express.json());

// Your routes here...
app.post("/auth/register", (req, res) =&amp;gt; {
    res.json({ message: "User registered successfully" });
});

app.listen(5001, () =&amp;gt; {
    console.log("Server running on port 5001");
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Alternative: Enable CORS for All Origins (Temporary)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;For debugging purposes, you can allow all origins:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(cors());

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;If Using Fetch in Frontend&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Make sure your fetch request in React includes mode: 'cors':&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch("http://localhost:5001/auth/register", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({ username: "ashwani", password: "123456" }),
    mode: "cors"
})
.then(response =&amp;gt; response.json())
.then(data =&amp;gt; console.log(data))
.catch(error =&amp;gt; console.error("Error:", error));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>webdev</category>
      <category>node</category>
      <category>react</category>
      <category>website</category>
    </item>
    <item>
      <title>Time complexity</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Fri, 03 Jan 2025 07:30:14 +0000</pubDate>
      <link>https://dev.to/imashwani/time-complexity-36l</link>
      <guid>https://dev.to/imashwani/time-complexity-36l</guid>
      <description>&lt;p&gt;O(1) (in the worst case): Given the page that a business's name is on and the business name, find the phone number.&lt;/p&gt;

&lt;p&gt;O(1) (in the average case): Given the page that a person's name is on and their name, find the phone number.&lt;/p&gt;

&lt;p&gt;O(log n): Given a person's name, find the phone number by picking a random point about halfway through the part of the book you haven't searched yet, then checking to see whether the person's name is at that point. Then repeat the process about halfway through the part of the book where the person's name lies. (This is a binary search for a person's name.)&lt;br&gt;
&lt;strong&gt;Binary search is an example with complexity O(log n).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fifu428tj3og60yj6tua8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fifu428tj3og60yj6tua8.png" alt="Image description" width="600" height="190"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;O(n): Find all people whose phone numbers contain the digit "5".&lt;/p&gt;

&lt;p&gt;O(n): Given a phone number, find the person or business with that number.&lt;/p&gt;

&lt;p&gt;O(n log n): There was a mix-up at the printer's office, and our phone book had all its pages inserted in a random order. Fix the ordering so that it's correct by looking at the first name on each page and then putting that page in the appropriate spot in a new, empty phone book.&lt;/p&gt;

&lt;p&gt;For the below examples, we're now at the printer's office. Phone books are waiting to be mailed to each resident or business, and there's a sticker on each phone book identifying where it should be mailed to. Every person or business gets one phone book.&lt;/p&gt;

&lt;p&gt;O(n log n): We want to personalize the phone book, so we're going to find each person or business's name in their designated copy, then circle their name in the book and write a short thank-you note for their patronage.&lt;/p&gt;

&lt;p&gt;O(n2): A mistake occurred at the office, and every entry in each of the phone books has an extra "0" at the end of the phone number. Take some white-out and remove each zero.&lt;/p&gt;

&lt;p&gt;O(n · n!): We're ready to load the phonebooks onto the shipping dock. Unfortunately, the robot that was supposed to load the books has gone haywire: it's putting the books onto the truck in a random order! Even worse, it loads all the books onto the truck, then checks to see if they're in the right order, and if not, it unloads them and starts over. (This is the dreaded bogo sort.)&lt;/p&gt;

&lt;p&gt;O(nn): You fix the robot so that it's loading things correctly. The next day, one of your co-workers plays a prank on you and wires the loading dock robot to the automated printing systems. Every time the robot goes to load an original book, the factory printer makes a duplicate run of all the phonebooks! Fortunately, the robot's bug-detection systems are sophisticated enough that the robot doesn't try printing even more copies when it encounters a duplicate book for loading, but it still has to load every original and duplicate book that's been printed.&lt;/p&gt;

&lt;p&gt;Simple Code Examples Of Various Big O Categories:&lt;/p&gt;

&lt;p&gt;O(1) - Constant Time Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 1:&lt;br&gt;
Algorithm 1 prints hello once and it doesn't depend on n, so it will always run in constant time, so it is O(1).&lt;/p&gt;

&lt;p&gt;print "hello";&lt;br&gt;
Algorithm 2:&lt;br&gt;
Algorithm 2 prints hello 3 times, however it does not depend on an input size. Even as n grows, this algorithm will always only print hello 3 times. That being said 3, is a constant, so this algorithm is also O(1).&lt;/p&gt;

&lt;p&gt;print "hello";&lt;br&gt;
print "hello";&lt;br&gt;
print "hello";&lt;br&gt;
O(log(n)) - Logarithmic Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 3 - This acts like "log_2"&lt;br&gt;
Algorithm 3 demonstrates an algorithm that runs in log_2(n). Notice the post operation of the for loop multiples the current value of i by 2, so i goes from 1 to 2 to 4 to 8 to 16 to 32 ...&lt;/p&gt;

&lt;p&gt;for(int i = 1; i &amp;lt;= n; i = i * 2)&lt;br&gt;
  print "hello";&lt;br&gt;
Algorithm 4 - This acts like "log_3"&lt;br&gt;
Algorithm 4 demonstrates log_3. Notice i goes from 1 to 3 to 9 to 27...&lt;/p&gt;

&lt;p&gt;for(int i = 1; i &amp;lt;= n; i = i * 3)&lt;br&gt;
  print "hello";&lt;br&gt;
Algorithm 5 - This acts like "log_1.02"&lt;br&gt;
Algorithm 5 is important, as it helps show that as long as the number is greater than 1 and the result is repeatedly multiplied against itself, that you are looking at a logarithmic algorithm.&lt;/p&gt;

&lt;p&gt;for(double i = 1; i &amp;lt; n; i = i * 1.02)&lt;br&gt;
  print "hello";&lt;br&gt;
O(n) - Linear Time Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 6&lt;br&gt;
This algorithm is simple, which prints hello n times.&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  print "hello";&lt;br&gt;
Algorithm 7&lt;br&gt;
This algorithm shows a variation, where it will print hello n/2 times. n/2 = 1/2 * n. We ignore the 1/2 constant and see that this algorithm is O(n).&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i = i + 2)&lt;br&gt;
  print "hello";&lt;br&gt;
O(n*log(n)) - nlog(n) Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 8&lt;br&gt;
Think of this as a combination of O(log(n)) and O(n). The nesting of the for loops help us obtain the O(n*log(n))&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  for(int j = 1; j &amp;lt; n; j = j * 2)&lt;br&gt;
    print "hello";&lt;br&gt;
Algorithm 9&lt;br&gt;
Algorithm 9 is like algorithm 8, but each of the loops has allowed variations, which still result in the final result being O(n*log(n))&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i = i + 2)&lt;br&gt;
  for(int j = 1; j &amp;lt; n; j = j * 3)&lt;br&gt;
    print "hello";&lt;br&gt;
O(n^2) - n squared Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 10&lt;br&gt;
O(n^2) is obtained easily by nesting standard for loops.&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  for(int j = 0; j &amp;lt; n; j++)&lt;br&gt;
    print "hello";&lt;br&gt;
Algorithm 11&lt;br&gt;
Like algorithm 10, but with some variations.&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  for(int j = 0; j &amp;lt; n; j = j + 2)&lt;br&gt;
    print "hello";&lt;br&gt;
O(n^3) - n cubed Examples:&lt;/p&gt;

&lt;p&gt;Algorithm 12&lt;br&gt;
This is like algorithm 10, but with 3 loops instead of 2.&lt;/p&gt;

&lt;p&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  for(int j = 0; j &amp;lt; n; j++)&lt;br&gt;
    for(int k = 0; k &amp;lt; n; k++)&lt;br&gt;
      print "hello";&lt;/p&gt;

&lt;p&gt;Algorithm 13&lt;br&gt;
Like algorithm 12, but with some variations that still yield O(n^3).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;for(int i = 0; i &amp;lt; n; i++)&lt;br&gt;
  for(int j = 0; j &amp;lt; n + 5; j = j + 2)&lt;br&gt;
    for(int k = 0; k &amp;lt; n; k = k + 3)&lt;br&gt;
      print "hello";&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The above give several straight forward examples, and variations to help demonstrate what subtle changes can be introduced that really don't change the analysis. Hopefully it gives you enough insight&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0dicbbcsuxmtbyhb2pqg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0dicbbcsuxmtbyhb2pqg.png" alt="Image description" width="800" height="554"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>LeetCode Solutions (DSA)</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Fri, 03 Jan 2025 07:23:11 +0000</pubDate>
      <link>https://dev.to/imashwani/leetcode-solutions-dsa-1ad1</link>
      <guid>https://dev.to/imashwani/leetcode-solutions-dsa-1ad1</guid>
      <description>&lt;h2&gt;
  
  
  &lt;a href="https://dev.to/imashwani/two-sum-46fh-temp-slug-538795?preview=805fa29770efb271fd1420e8c9764ff0eb22dd623e22b2ceac235b500028f432dc7e21acd42c2c679d4f080c9c09f4b4dc6bcba195460c7c22ab5d55"&gt;&lt;strong&gt;1. LeetCode Solutions (DSA) - Two Sum&lt;/strong&gt;&lt;/a&gt;
&lt;/h2&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1. Two Sum&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.&lt;/p&gt;

&lt;p&gt;You may assume that each input would have exactly one solution, and you may not use the same element twice.&lt;/p&gt;

&lt;p&gt;You can return the answer in any order.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [2,7,11,15], target = 9&lt;br&gt;
Output: [0,1]&lt;br&gt;
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [3,2,4],**** target = 6&lt;br&gt;
Output: [1,2]&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [3,3], target = 6&lt;br&gt;
Output: [0,1]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result -&amp;gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let nums = [2,7,11,15];
let target = 9
let index = [];

function twoSum(nums, target){
  for(let i = 0; i&amp;lt;nums.length; i++){
    for (let j = i+1; j &amp;lt; nums.length; j++) {
      if((nums[i] + nums[j]) === target){
        index.push(i)
        index.push(j)
      }
    }
  }
}
twoSum(nums, target)
console.log(index)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums = [8,9, 4, 6, 2,7,11,15], target = 9;

function addTwoNumbers(nums){
  const numsToIndex = new Map();

  for (var i = 0; i &amp;lt; nums.length; i++) {
    const val = nums[i];
    const subs = target - val; 

    if(numsToIndex.has(subs)){
      return [numsToIndex.get(subs), i]
    }

    numsToIndex.set(val, i)

  }
}

console.log(addTwoNumbers(nums))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;2. Add Two Numbers&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.&lt;/p&gt;

&lt;p&gt;You may assume the two numbers do not contain any leading zero, except the number 0 itself.&lt;/p&gt;

&lt;p&gt;Input: l1 = [2,4,3], l2 = [5,6,4]&lt;br&gt;
Output: [7,0,8]&lt;br&gt;
Explanation: 342 + 465 = 807.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: l1 = [0], l2 = [0]&lt;br&gt;
Output: [0]&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]&lt;br&gt;
Output: [8,9,9,9,0,0,0,1]&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result 1. -&amp;gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function AddTwoNumber(l1, l2){
  let arr = []
  let sum = Number(l1.join('')) + Number(l2.join(''));
  let str = String(sum).split('').reverse();
  for(let i=0; i&amp;lt;str.length; i++){
    arr.push(Number(str[i]))
  }
  return arr;
}

console.log(AddTwoNumber(l1, l2))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result 2. -&amp;gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function AddTwoNumbers(l1, l2){
if(l1.length != l2.length){
  let length = (l1.length &amp;gt; l2.length) ? l1.length - l2.length : l2.length - l1.length;
  for(let j = 0 ; j &amp;lt; length; j++){
  (l1.length &amp;gt; l2.length) ? l2.push(0) : l1.push(0)
  }
}
  let carry = 0;
  let final = []
  for(let i = 0; i &amp;lt; l1.length; i++){
    let sum = l1[i] + l2[i] + carry;
    if(sum &amp;gt; 9){
      final.push(Math.floor(sum % 10));
      carry = Math.floor(sum/10);
    } else {
      final.push(sum)
      carry = 0;
    }
  }
  if(carry &amp;gt;= 1){
    final.push(carry)
  }
  return final;
};
AddTwoNumbers(l1, l2)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;3. Palindrome Number&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given an integer x, return true if x is a palindrome, and false otherwise.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Input: x = 121&lt;br&gt;
Output: true&lt;br&gt;
Explanation: 121 reads as 121 from left to right and from right to left.&lt;br&gt;
&lt;strong&gt;Example 2:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Input: x = -121&lt;br&gt;
Output: false&lt;br&gt;
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.&lt;br&gt;
&lt;strong&gt;Example 3:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Input: x = 10&lt;br&gt;
Output: false&lt;br&gt;
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result 1. -&amp;gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 121;
var isPalindrome = function (x) {
 return x &amp;lt; 0 ? false : x === +x.toString().split("").reverse().join('')
};
isPalindrome(x)
--------------------------xxxxxxxxxxxxxxxx-----------------------


let val = 121;
function isPalindrome(val){
  let str = Number(String(val).split('').reverse().join(''));
  if(str === val){
    return true;
  } else return false;
}
console.log(isPalindrome(val))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result 2. -&amp;gt;&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isPalindrome(val){
let data = Array.from(String(val));
let arr = []
for(let i = data.length-1; i &amp;gt;= 0; i--){
  if(Number(data[i])){
  arr.push(Number(data[i]));
  } else {
    arr.push((data[i]));
  }
}
let out = arr.join('');
  if(out == val){
    return true;
  } else return false;
}
console.log(isPalindrome(val))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;4. Roman to Integer&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.&lt;/p&gt;

&lt;p&gt;Symbol       Value&lt;br&gt;
I             1&lt;br&gt;
V             5&lt;br&gt;
X             10&lt;br&gt;
L             50&lt;br&gt;
C             100&lt;br&gt;
D             500&lt;br&gt;
M             1000&lt;br&gt;
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.&lt;/p&gt;

&lt;p&gt;Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:&lt;/p&gt;

&lt;p&gt;I can be placed before V (5) and X (10) to make 4 and 9. &lt;br&gt;
X can be placed before L (50) and C (100) to make 40 and 90. &lt;br&gt;
C can be placed before D (500) and M (1000) to make 400 and 900.&lt;br&gt;
Given a roman numeral, convert it to an integer.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: s = "III"&lt;br&gt;
Output: 3&lt;br&gt;
Explanation: III = 3.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: s = "LVIII"&lt;br&gt;
Output: 58&lt;br&gt;
Explanation: L = 50, V= 5, III = 3.&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: s = "MCMXCIV"&lt;br&gt;
Output: 1994&lt;br&gt;
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result :&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
var romanToInt = function (rom) {
    let modRoman = rom;
    let sum = 0;
    if (rom.includes('IV')) {
        modRoman = rom.replace('IV', '');
        sum = sum + 4;
    } if (rom.includes('IX')) {
        modRoman = modRoman.replace('IX', '');
        sum = sum + 9
    } if (rom.includes('XL')) {
        modRoman = modRoman.replace('XL', '')
        sum = sum + 40;
    } if (rom.includes('XC')) {
        modRoman = modRoman.replace('XC', '')
        sum = sum + 90;
    } if (rom.includes('CD')) {
        modRoman = modRoman.replace('CD', '')
        sum = sum + 400;
    } if (rom.includes('CM')) {
        modRoman = modRoman.replace('CM', '')
        sum = sum + 900;
    };
    let value = modRoman.split('');
    for (let i = 0; i &amp;lt; value.length; i++) {
        if (value[i] === 'I') {
            sum = sum + 1;
        } else if (value[i] === 'I') {
            sum = sum + 1;
        } else if (value[i] === 'V') {
            sum = sum + 5;
        } else if (value[i] === 'X') {
            sum = sum + 10;
        } else if (value[i] === 'L') {
            sum = sum + 50;
        } else if (value[i] === 'C') {
            sum = sum + 100;
        } else if (value[i] === 'D') {
            sum = sum + 500;
        } else if (value[i] === 'M') {
            sum = sum + 1000;
        }
    };
    return sum
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result.2&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; let findInt = (Roman) =&amp;gt;{
    switch(Roman){
        case 'I': return 1;
        case 'V': return 5;
        case 'X': return 10;
        case 'L': return 50;
        case 'C': return 100;
        case 'D': return 500;
        case 'M': return 1000;

    }
 }
var romanToInt = function(s) {
    let result = 0;
    for(i = 0;i &amp;lt; s.length;i++){
        console.log(result, s[i], s[i+1])

        if(findInt(s[i]) &amp;lt; findInt(s[i+1])){
            result -= findInt(s[i]);
        }else{
            result +=findInt(s[i]);
        }
    }
       return result

};
console.log(romanToInt("MCMXCIV"))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result - 4&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function romanToInt(rom){
  let obj = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
  };
  let count = 0;
  for (var i = 0; i &amp;lt; rom.length; i++) {
    if(rom[i] + rom[i+1] === 'IV'){
      count += 4
      i++
    } else if(rom[i] + rom[i+1] === 'IX'){
      count += 9;
      i++
    } else if(rom[i] + rom[i+1] === 'XL'){
      count += 40;
      i++
    } else if(rom[i] + rom[i+1] === 'XC'){
      count += 90;
      i++
    } else if(rom[i] + rom[i+1] === 'CD'){
      count += 400;
      i++
    } else if(rom[i] + rom[i+1] === 'CM'){
      count += 900;
      i++
    } else if (obj.hasOwnProperty(rom[i])) {
      count = count + obj[rom[i]]
    }
    }
    return count;
  }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let obj = {
  'I': 1,
  'IV': 4,
  'V' : 5,
  'IX': 9,
  'X': 10,
  'XL': 40,
  'L': 50,
  'XC': 90,
  'C': 100,
  'CD': 400,
  'D': 500,
  'CM': 900,
  'M': 1000
}

function romanToIntegers(s){
    let count = 0;
  for (var i = 0; i &amp;lt; s.length; i++) {
    if(s[i] + s[i+1] === 'IV'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'IX'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'XL'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'XC'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'CD'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    } else if(s[i] + s[i+1] === 'CM'){
      count = count + obj[s[i] + s[i+1]]; 
      i++
    }
    else {
      count = count + obj[s[i]]
    }
  }
    return count;
}
console.log(romanToIntegers(s))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;5. Count Characters&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Javascript Practice Problems: Count Characters in String;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Results :&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function findCountOfOcc(str){
  let obj = {};
  for(let i = 0; i &amp;lt; str.length; i++){
    let key = str[i]
    obj[key] = (obj[key] || 0) + 1;
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findCountOfOcc(str){
  let obj = {};
  for(let i in str){
    let key = str[i]
    obj[key] = (obj[key] || 0) + 1;
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function findCountOfOcc(str){
  let obj = {};
  for(let key of str){
    if(obj[key]){
      obj[key] = obj[key] + 1
    } else obj[key] = 1
  }
  return obj
}

console.log(findCountOfOcc("HelloWorld"));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;6. Longest Common Prefix&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Write a function to find the longest common prefix string amongst an array of strings.&lt;/p&gt;

&lt;p&gt;If there is no common prefix, return an empty string "".&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: strs = ["flower","flow","flight"]&lt;br&gt;
Output: "fl"&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: strs = ["dog","racecar","car"]&lt;br&gt;
Output: ""&lt;br&gt;
Explanation: There is no common prefix among the input strings.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
let strs = ["flower","flow","flight"];

function toFindPrefix(strs){
  let srt = strs.sort();
  let firstEle = srt[0];
  let lastEle = srt[srt.length-1];
  let data = ''
  for(let i = 0; i &amp;lt; lastEle.length; i++){
    if(lastEle[0] === firstEle[0]){
      if(lastEle[i] === firstEle[i]){
      data = `${data + firstEle[i]}`
    } else break;
    }
  }
  return data;
}
toFindPrefix(strs);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;7 Valid Parentheses&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;iven a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.&lt;/p&gt;

&lt;p&gt;Open brackets must be closed by the same type of brackets.&lt;br&gt;
Open brackets must be closed in the correct order.&lt;br&gt;
Every close bracket has a corresponding open bracket of the same type.&lt;/p&gt;

&lt;p&gt;Example 1: Input: s = "()" Output: true&lt;/p&gt;

&lt;p&gt;Example 2: Input: s = "()[]{}" Output: true&lt;/p&gt;

&lt;p&gt;Example 3: Input: s = "(]" Output: false&lt;/p&gt;

&lt;p&gt;Example 4: Input: s = "([])" Output: true&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isValid(s){
  let arr = [];
  for(char of s){
    if(char === '(' || char === '{' || char === '['){
      arr.push(char)
    } else if(
      char === ')' &amp;amp;&amp;amp; arr[arr.length - 1] === '(' ||
      char === '}' &amp;amp;&amp;amp; arr[arr.length - 1] === '{' ||
      char === ']' &amp;amp;&amp;amp; arr[arr.length - 1] === '['
      ) {
        arr.pop()
      } else {
        return false
      }
  }
  return arr.length === 0;
}
console.log(isValid(str))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var isValid = function (s) {
let obj = {
    '(': ')',
    '{': '}',
    '[':']'
  };
  if(
    s[0] === '(' &amp;amp;&amp;amp; !s.includes(')') || 
    s[0] === '{' &amp;amp;&amp;amp; !s.includes('}') || 
    s[0] === '[' &amp;amp;&amp;amp; !s.includes(']') 
  ){
    return false;
  };
  let stack = [];
  for (var i = 0; i &amp;lt; s.length; i++) {
    if(obj[s[i]]){
      stack.push(s[i])
    } else {
      let pop = stack.pop();
      if(obj[pop] !== s[i]){
        return false
      }
    }
  }
  return stack.length === 0;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isValid(str){
  let obj = {
  ')':'(',
  '}':'{',
  ']':'['
};

  let strVal = str.split("");
  let stack = [];

  if(obj[strVal[0]]) return false;

  for (var i = 0; i &amp;lt; strVal.length; i++) {
    if(strVal[i])

    if(!obj[strVal[i]]){
      stack.push(strVal[i])

    } else {
     // If it's a closing bracket, check if it matches the last 
        opened bracket.

      if (stack.length === 0 || stack[stack.length - 1] !== obj[strVal[i]]) {
        return false;
      }
      stack.pop()
    }
  }
    return (stack.length === 0) ? true : false

}
console.log(isValid(str))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Search Insert Position (binary search)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.&lt;br&gt;
You must write an algorithm with O(log n) runtime complexity.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 5&lt;br&gt;
Output: 2&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 2&lt;br&gt;
Output: 1&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 7&lt;br&gt;
Output: 4&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Result - 1&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums = [1,3,5,6], target = 2

function searchInsert(nums, target){
  let start = 0;
  let end = nums.length - 1;
  while(start &amp;lt;= end){
  let middle = Math.floor((start+end)/2);
    if(nums[middle] === target){
      return middle;
    } else if(nums[middle] &amp;lt; target){
      start = middle + 1;
    } else if (nums[middle] &amp;gt; target){
      end = middle - 1;
    }
  }
  return start
};

console.log(searchInsert(nums, target))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Result-2&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let nums = [1,3,5,6], target = 5

function searchInsert(nums, target, start, end){
  if (start &amp;gt; end){
    return start;
  }
  let middle = Math.floor((start+end)/2);
  if(nums[middle] === target){
    return middle;
  } else if(nums[middle] &amp;lt; target){
    return searchInsert(nums, target, middle + 1, end)
  } else if (nums[middle] &amp;gt; target){
    return searchInsert(nums, target, start, middle-1)
  }
};

console.log(searchInsert(nums, target, 0, nums.length-1))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Kaprekar Number&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Input :  n = 45&lt;br&gt;&lt;br&gt;
Output : Yes&lt;br&gt;
Explanation : 452 = 2025 and 20 + 25 is 45&lt;/p&gt;

&lt;p&gt;Input : n = 13&lt;br&gt;
Output : No&lt;br&gt;
Explanation : 132 = 169. Neither 16 + 9 nor 1 + 69 is equal to 13&lt;/p&gt;

&lt;p&gt;Input  : n = 297&lt;br&gt;&lt;br&gt;
Output : Yes&lt;br&gt;
Explanation:  2972 = 88209 and 88 + 209 is 297&lt;/p&gt;

&lt;p&gt;Input  : n = 10 &lt;br&gt;
Output : No&lt;br&gt;
Explanation:  102 = 100. It is not a Kaprekar number even if&lt;br&gt;
sum of 100 + 0 is 100. This is because of the condition that &lt;br&gt;
none of the parts should have value 0.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let num = 9999 
// 9, 45, 55 99 297 703 999 2223 2728 4879 4950 5050 5292 7272 7777 9999 

function tocheckKarpekarNumber(num){
  let sq = num*num;
  let val = sq.toString().split("")
  let n = ''
  for(let i = 0; i &amp;lt; 5; i++){
    n = n + val[i];
    if((Number(n) + Number(val.slice(i+1).join("")) == num)){
      return true
    }
  }
  return false
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Reverse String&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Input&lt;/strong&gt;&lt;br&gt;
let str = "I Am Not String"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;output&lt;/strong&gt; = "g ni rtS toNmAI";&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function reverseString(val){
  let arr = val.split(" ");
  console.log(arr)
  let newVal= [];
  let data = val.split("").reverse().join("").split(" ").join("").split("");
  for (var i = 0; i &amp;lt; data.length; i++) {
    let d = data.splice(0, arr[i].length).join("")
    newVal.push(d)
  }
  return newVal.join(" ")
}
console.log(reverseString(str))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Remove Duplicates from Sorted Array&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given an integer array nums sorted in non-decreasing order, remove the duplicates &lt;strong&gt;in-place&lt;/strong&gt; such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,1,2]&lt;br&gt;
Output: 2, nums = [1,2,_]&lt;br&gt;
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.&lt;br&gt;
It does not matter what you leave beyond the returned k (hence they are underscores).&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [0,0,1,1,1,2,2,3,3,4]&lt;br&gt;
Output: 5, nums = [0,1,2,3,4,&lt;em&gt;,&lt;/em&gt;,&lt;em&gt;,&lt;/em&gt;,_]&lt;br&gt;
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.&lt;br&gt;
It does not matter what you leave beyond the returned k (hence they are underscores).&lt;/p&gt;

&lt;p&gt;✅ What does “in-place” mean?&lt;br&gt;
It means you cannot use another array to store results. You must modify the given nums array directly, using constant extra memory (O(1)).&lt;/p&gt;

&lt;p&gt;🧠 Approach (Two-pointer technique)&lt;br&gt;
Use two pointers:&lt;/p&gt;

&lt;p&gt;i → last index where a unique number was placed.&lt;/p&gt;

&lt;p&gt;j → current index scanning the array.&lt;/p&gt;

&lt;p&gt;Compare nums[j] with nums[i]:&lt;/p&gt;

&lt;p&gt;If different: it’s a unique value → move i forward and assign nums[i] = nums[j].&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function removeDuplicates(nums){
  if (nums.length === 0) return 0;
    let j = 0;
    for (var i = 0; i &amp;lt; nums.length; i++) {
    if(nums[i] !== nums[j]){
      j++
      nums[j] = nums[i]
      console.log(nums[j])
    }
  }
  return j+1
}
console.log(removeDuplicates(nums))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Find the Index of the First Occurrence in a String&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: haystack = "sadbutsad", needle = "sad"&lt;br&gt;
Output: 0&lt;br&gt;
Explanation: "sad" occurs at index 0 and 6.&lt;br&gt;
The first occurrence is at index 0, so we return 0.&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: haystack = "leetcode", needle = "leeto"&lt;br&gt;
Output: -1&lt;br&gt;
Explanation: "leeto" did not occur in "leetcode", so we return -1.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let haystack = "sadbutsad", needle = "sad";

function strStr(haystack,needle){
  let arr = []
  let index = 0;
  let l = needle.length;
  for (var i = 0; i &amp;lt; haystack.length; i+=l) {
    let val = haystack.slice(i, i+l);
    arr.push(val);
  };
  return arr.indexOf(needle);
}

  console.log(strStr(haystack,needle));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function strStr(haystack,needle){
if (!haystack.length) return -1
    let val = haystack.indexOf(needle);
    return val
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Remove Element&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given an integer array nums and an integer val, remove all occurrences of val in nums *&lt;em&gt;in-place *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [3,2,2,3], val = 3&lt;br&gt;
Output: 2, nums = [2,2,&lt;em&gt;,&lt;/em&gt;]&lt;br&gt;
Explanation: Your function should return k = 2, with the first two elements of nums being 2.&lt;br&gt;
It does not matter what you leave beyond the returned k (hence they are underscores).&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [0,1,2,2,3,0,4,2], val = 2&lt;br&gt;
Output: 5, nums = [0,1,4,0,3,&lt;em&gt;,&lt;/em&gt;,_]&lt;br&gt;
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.&lt;br&gt;
Note that the five elements can be returned in any order.&lt;br&gt;
It does not matter what you leave beyond the returned k (hence they are underscores).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var removeElement = function(nums, val) {
    if(nums.length &amp;lt;= 0 ) return;
    let k = 0;
    for(let i = 0; i &amp;lt; nums.length; i++){
        if(nums[i] !== val){
            nums[k] = nums[i]
            k++
        }
    }
    return k;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Search Insert Position (Binary Search)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.&lt;/p&gt;

&lt;p&gt;You must write an algorithm with &lt;strong&gt;O(log n)&lt;/strong&gt; runtime complexity.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 5&lt;br&gt;
Output: 2&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 2&lt;br&gt;
Output: 1&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: nums = [1,3,5,6], target = 7&lt;br&gt;
Output: 4&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var searchInsert = function(nums, target) {
      let start = 0;
  let end = nums.length - 1;
  while(start &amp;lt;= end){
  let middle = Math.floor((start+end)/2);
    if(nums[middle] === target){
      return middle;
    } else if(nums[middle] &amp;lt; target){
      start = middle + 1;
    } else if (nums[middle] &amp;gt; target){
      end = middle - 1;
    }
  }
  return start
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Plus One&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Increment the large integer by one and return the resulting array of digits.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: digits = [1,2,3]&lt;br&gt;
Output: [1,2,4]&lt;br&gt;
Explanation: The array represents the integer 123.&lt;br&gt;
Incrementing by one gives 123 + 1 = 124.&lt;br&gt;
Thus, the result should be [1,2,4].&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: digits = [4,3,2,1]&lt;br&gt;
Output: [4,3,2,2]&lt;br&gt;
Explanation: The array represents the integer 4321.&lt;br&gt;
Incrementing by one gives 4321 + 1 = 4322.&lt;br&gt;
Thus, the result should be [4,3,2,2].&lt;br&gt;
Example 3:&lt;/p&gt;

&lt;p&gt;Input: digits = [9]&lt;br&gt;
Output: [1,0]&lt;br&gt;
Explanation: The array represents the integer 9.&lt;br&gt;
Incrementing by one gives 9 + 1 = 10.&lt;br&gt;
Thus, the result should be [1,0].&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let digits = [4,3,2,9];

function addOnes(){
  for(let i = digits.length-1; i &amp;gt;= 0; i--){
  // check if the didgits is less then 9 then just add 1 and return

        if(digits[i] &amp;lt; 9){
            digits[i]++;
            return digits;
        };

  // If the digit is 9, set it to 0 (and carry over to the next)

        digits[i] = 0;
        console.log(digits,"pppp")

    }

  // If we finished the loop, it means all digits were 9 (e.g., 999)
  // So we need to add a 1 at the beginning

    digits.unshift(1);
    return digits;
}

console.log(addOnes(digits))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Add Binary&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Given two binary strings a and b, return their sum as a binary string.&lt;/p&gt;

&lt;p&gt;Example 1:&lt;/p&gt;

&lt;p&gt;Input: a = "11", b = "1"&lt;br&gt;
Output: "100"&lt;br&gt;
Example 2:&lt;/p&gt;

&lt;p&gt;Input: a = "1010", b = "1011"&lt;br&gt;
Output: "10101"&lt;/p&gt;

&lt;p&gt;Constraints:&lt;/p&gt;

&lt;p&gt;1 &amp;lt;= a.length, b.length &amp;lt;= 104&lt;br&gt;
a and b consist only of '0' or '1' characters.&lt;br&gt;
Each string does not contain leading zeros except for the zero itself.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let a = "1010", b = "11111";

var addBinary = function(a, b) {
  a = a.split('').reverse().join("");
  b = b.split('').reverse().join("");

  let obj = {
    '0': 0,
    '1': 1,
    '2': 0,
    '3': 1
  };
  console.log(a, b)
  let carry = 0;
  let ans = '';



  let lenA = a.length, lenB = b.length;
  for (var i = 0; i &amp;lt; Math.max(lenA, lenB); i++) {

    let numA = i &amp;lt; lenA ? Number(a[i]) : 0
    let numB = i &amp;lt; lenB ? Number(b[i]) : 0

    let sum = numA + numB + carry;
    sum &amp;gt;= 2 ? carry = 1 : carry = 0;
    let c = `${sum}`;
    ans = ans + obj[c];
  }
  if(carry) return (ans + carry).split('').reverse().join('');
  return ans.split('').reverse().join('');
};

console.log(addBinary(a,b))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var addBinary = function(a, b) {
    let val1 = parseInt(a, 2);
    let val2 = parseInt(b, 2);

    let final = val1 + val2;
    return final.toString(2);
}
    console.log(addBinary(a,b))

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Let’s solve the error of GROUP BY clause and contains nonaggregated column in MySQL</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Fri, 28 Jun 2024 14:38:03 +0000</pubDate>
      <link>https://dev.to/imashwani/lets-solve-the-error-of-group-by-clause-and-contains-nonaggregated-column-in-mysql-1l6m</link>
      <guid>https://dev.to/imashwani/lets-solve-the-error-of-group-by-clause-and-contains-nonaggregated-column-in-mysql-1l6m</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqbp2sei1njr1levl64md.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fqbp2sei1njr1levl64md.png" alt="Image description" width="743" height="287"&gt;&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>Higher Order Components (HOC) in React js</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Fri, 07 Jun 2024 08:02:04 +0000</pubDate>
      <link>https://dev.to/imashwani/higher-order-components-hoc-in-react-js-d8a</link>
      <guid>https://dev.to/imashwani/higher-order-components-hoc-in-react-js-d8a</guid>
      <description>&lt;p&gt;A Higher-Order Component (HOC) is an advanced technique for reusing component logic. HOCs are not part of the React API, but rather a pattern that emerges from React’s compositional nature.&lt;/p&gt;

&lt;p&gt;A higher-order component is a function that takes a component as an argument and returns a new component that wraps the original component &lt;br&gt;
This allows you to add additional functionality to the component without modifying its original code. HOCs are commonly used to share common functionality between multiple components, such as state modification or props change.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;1. Creating a Higher-Order Component:&lt;/strong&gt;
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

// This is the HOC function
function withCounter(WrappedComponent) {
  class WithCounter extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        count: 0,
      };
    }

    handleIncrement = () =&amp;gt; {
      this.setState((prevState) =&amp;gt; {
        return { count: prevState.count + incremntNuber };
      });
    };
    render() {
      return (
        &amp;lt;WrappedComponent
          count={count}
          incrementHandler={this.handleIncrement}
          {...this.props}
        /&amp;gt;
      );
    }
  }
return WithCounter;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2. Using the HOC:&lt;/strong&gt;
&lt;/h2&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// A simple component
function MyComponent(props) {
  return (
      &amp;lt;button onClick={props.incrementHandler}&amp;gt;
        {props.name} Click {props.count} times
      &amp;lt;/button&amp;gt;
    );
}

// Wrap the component with the HOC
const EnhancedComponent = withCounter(MyComponent);

// Usage
function App() {
  return &amp;lt;EnhancedComponent name="Hello World!" /&amp;gt;;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;blockquote&gt;
&lt;p&gt;In this example, withCounter is the &lt;strong&gt;HOC&lt;/strong&gt; that adds some extra information to the &lt;strong&gt;MyComponent&lt;/strong&gt; component. When &lt;strong&gt;EnhancedComponent&lt;/strong&gt; is used, it renders MyComponent with the original props along with the additional paragraph containing "Some extra information".&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;3. Key Points About HOCs:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pure Functions:&lt;/strong&gt; HOCs should be pure, meaning they should not modify the original component. Instead, they should create a new component that wraps the original one.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Props Proxy:&lt;/strong&gt; HOCs can pass props to the wrapped component. This pattern is useful for injecting additional props or modifying existing ones before passing them down.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Composability:&lt;/strong&gt; HOCs can be composed. You can create multiple HOCs and apply them to a component sequentially.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Convention:&lt;/strong&gt; It's a common convention to name HOCs with a prefix like with, such as withRouter or withUser, to indicate that it's an HOC.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Static Methods:&lt;/strong&gt; HOCs do not copy static methods from the wrapped component. If the wrapped component has static methods that need to be accessed, you’ll need to manually copy them.&lt;/p&gt;

&lt;p&gt;Here’s an example of ensuring static methods are preserved:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

// Helper function to copy static methods
function hoistStatics(targetComponent, sourceComponent) {
  const keys = Object.getOwnPropertyNames(sourceComponent);
  keys.forEach(key =&amp;gt; {
    if (!targetComponent.hasOwnProperty(key)) {
      targetComponent[key] = sourceComponent[key];
    }
  });
  return targetComponent;
}

function withExtraInfo(WrappedComponent) {
  class HOC extends React.Component {
    render() {
      return (
        &amp;lt;div&amp;gt;
          &amp;lt;WrappedComponent {...this.props} /&amp;gt;
          &amp;lt;p&amp;gt;Some extra information&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
      );
    }
  }

  // Copy static methods
  hoistStatics(HOC, WrappedComponent);

  return HOC;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;HOCs are a powerful pattern in React for reusing component logic, but they should be used judiciously to avoid overly complex component hierarchies.&lt;/p&gt;

</description>
      <category>react</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>hoc</category>
    </item>
    <item>
      <title>Error Boundary in React js</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Sat, 01 Jun 2024 20:16:13 +0000</pubDate>
      <link>https://dev.to/imashwani/error-boundary-in-react-js-1n5o</link>
      <guid>https://dev.to/imashwani/error-boundary-in-react-js-1n5o</guid>
      <description>&lt;p&gt;In React, an Error Boundary is a component that helps catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. This feature is particularly useful for improving the user experience by gracefully handling unexpected errors.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Key Concepts of Error Boundaries&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Definition and Use:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Error boundaries are React components that catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.&lt;/p&gt;

&lt;p&gt;They do not catch errors for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Event handlers (use try-catch in the event handler).&lt;/li&gt;
&lt;li&gt;Asynchronous code (e.g., setTimeout or requestAnimationFrame 
callbacks).&lt;/li&gt;
&lt;li&gt;Server-side rendering.&lt;/li&gt;
&lt;li&gt;Errors thrown in the error boundary itself (e.g., inside componentDidCatch).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. How to Create an Error Boundary:&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;An error boundary is any React component that implements either componentDidCatch lifecycle method or the static getDerivedStateFromError method.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.error("Error caught by ErrorBoundary:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return &amp;lt;h1&amp;gt;Something went wrong.&amp;lt;/h1&amp;gt;;
    }

    return this.props.children; 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3. Using an Error Boundary:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ErrorBoundary&amp;gt;
  &amp;lt;AppComponet /&amp;gt;
&amp;lt;/ErrorBoundary&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Best Practices&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Granularity:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It's better to place error boundaries at the top level of your application to catch all errors, but you can also place them around specific components to isolate errors within specific parts of your app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Logging:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Implement logging in componentDidCatch to send error details to an error monitoring service (e.g., Sentry, LogRocket).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Fallback UI:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Make sure the fallback UI is user-friendly and provides a way to recover from the error if possible (like a "Try Again" button).&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Limitations.&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Event Handlers:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Error boundaries do not catch errors inside event handlers. You need to handle those manually using try-catch blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Async Code:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Errors in asynchronous code should be handled within the async functions using try-catch blocks.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Example in Functional Components&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;With the introduction of hooks, you might wonder about using error boundaries in functional components. As of now, React does not provide hooks for error boundaries. You must use class components for creating error boundaries.&lt;/p&gt;

&lt;p&gt;In summary, React's Error Boundaries are a robust way to handle errors gracefully in your application, ensuring that users have a smooth experience even when something goes wrong.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
    </item>
    <item>
      <title>What are portals in React and when do we need them ?</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Fri, 31 May 2024 07:06:29 +0000</pubDate>
      <link>https://dev.to/imashwani/what-are-portals-in-react-and-when-do-we-need-them--4dp4</link>
      <guid>https://dev.to/imashwani/what-are-portals-in-react-and-when-do-we-need-them--4dp4</guid>
      <description>&lt;p&gt;In React 16.0 version, React portals were introduced. Portals in React come up with a way to render children components into a DOM node which typically occurs outside the DOM hierarchy of the parent component.&lt;/p&gt;

&lt;p&gt;Before React Portals, It was very difficult to render the child component outside the hierarchy of its parent component. Every single React component in the React application falls under the root element.&lt;/p&gt;

&lt;p&gt;But, the &lt;strong&gt;React portal concept provides us the ability to break out of this dom tree and render a component onto a dom node that is not under this root element&lt;/strong&gt;. Doing so breaks the convention where a component needs to be rendered as a new element and follows a parent-child hierarchy. Portals are commonly used in modal dialog boxes, hover cards, loaders, and popup messages.  Below is the syntax of React portals. &lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Syntax:&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import ReactDOM from "react-dom";

// createPortal is a function of ReactDom, always import ReactDom 
// before using their property.

ReactDOM.createPortal(child, container)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Parameters:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;child:&lt;/strong&gt; It can be a React element, string, or fragment&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;container:&lt;/strong&gt; It is a DOM node.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;In the syntax above, we have two parameters the first parameter is a child that can be a React element, string, or fragment and the second one is a container which is the DOM node (or location) lying outside the DOM hierarchy of the parent component at which our portal is to be inserted.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Advantages of React Portals:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Event Bubbling inside a portal&lt;/strong&gt;: Although we don’t render a portal inside the parent DOM element, its behavior is still similar to a regular React component inside the application. It can access the props and state as it resides inside the DOM tree hierarchy.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;React portals can use Context API to transfer the data in components.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;index.html&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;!-- Filename - public/index.html --&amp;gt;

&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;

&amp;lt;head&amp;gt;
    &amp;lt;meta charset="utf-8" /&amp;gt;
    &amp;lt;link rel="icon"
        href="%PUBLIC_URL%/favicon.ico" /&amp;gt;

    &amp;lt;title&amp;gt;React App&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body
    style="text-align: center; margin: auto;"&amp;gt;

    &amp;lt;div id="root"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;div id="portal"&amp;gt;&amp;lt;/div&amp;gt;
   &amp;lt;!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty 
      page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the &amp;lt;body&amp;gt; 
      tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn 
      build`.
    --&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;App.js&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Filname - App.js

import React, { Component } from "react";
import ReactDOM from "react-dom";

class Portal extends Component {
    render() {
        // Creating portal
        return ReactDOM.createPortal(
            &amp;lt;button&amp;gt;Click&amp;lt;/button&amp;gt;,
            document.getElementById("portal")
        );
    }
}

class App extends Component {
    constructor(props) {
        super(props);

        // Set initial state
        this.state = { click: "" };

        // Binding this keyword
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        // This will trigger when the button
        // inside Portal is clicked, It updates
        // Parent's state, even though it is not
        // rendered inside the parent DOM element
        if (this.state.click == "")
            this.setState((prevState) =&amp;gt; ({
                click: "Welcome to Portal demo",
            }));
        else {
            this.setState({ click: "" });
        }
    }

    render() {
        return (
            &amp;lt;div onClick={this.handleClick}&amp;gt;
                &amp;lt;h1 style={{ color: "green" }}&amp;gt;
                    component which have id 
                                        "root"
                &amp;lt;/h1&amp;gt;
                &amp;lt;h2 style={{ color: "Green" }}&amp;gt;
                    {this.state.click}
                &amp;lt;/h2&amp;gt;
                &amp;lt;Portal /&amp;gt;
            &amp;lt;/div&amp;gt;
        );
    }
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;When do we need React Portals ?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We mainly need portals when a React parent component has a hidden value of overflow property(overflow: hidden) or z-index style, and we need a child component to openly come out of the current tree hierarchy. &lt;/p&gt;

&lt;p&gt;Following are the examples when we need the react portals:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Dialogs&lt;/li&gt;
&lt;li&gt;Modals&lt;/li&gt;
&lt;li&gt;Tooltips&lt;/li&gt;
&lt;li&gt;Hovercards&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In all these cases, we’re rendering elements outside of the parent components in the DOM tree.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Extract Array of object data in MySql DB</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Wed, 29 May 2024 10:23:50 +0000</pubDate>
      <link>https://dev.to/imashwani/extract-array-of-object-data-in-mysql-db-3472</link>
      <guid>https://dev.to/imashwani/extract-array-of-object-data-in-mysql-db-3472</guid>
      <description>&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// your_column = [{id: 1, name: "Tom", age: 30}];

SELECT * FROM your_table 
WHERE json_contains(your_column-&amp;gt;'$[*].id', json_array("your_id_to_match"));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>JavaScript Data Types</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Tue, 02 Apr 2024 07:14:52 +0000</pubDate>
      <link>https://dev.to/imashwani/javascript-data-types-189g</link>
      <guid>https://dev.to/imashwani/javascript-data-types-189g</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;1. Introduction&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Computer programs generally deal with a lot of data. This data can be one of several types. Each type has its own purpose, utilities, and underlying mechanism of implementation.&lt;/p&gt;

&lt;p&gt;In this chapter, we shall get an overview of the data types that JavaScript comes equipped with, out of the box.&lt;/p&gt;

&lt;p&gt;We'll understand the distinction between &lt;strong&gt;primitive&lt;/strong&gt; and &lt;strong&gt;object (non-primitive)&lt;/strong&gt; types before moving on to explore the six most common primitive types and the three most common object types. Moreover, we'll also consider the typeof operator, used to inpsect the type of a given value.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2. What are data types?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A data type describes a set of values and the operations possible on those values.&lt;/p&gt;

&lt;p&gt;JavaScript divides data essentially into two main categories: &lt;strong&gt;primitives&lt;/strong&gt; and &lt;strong&gt;objects (non-primitives)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;2.1 Primitive data types&lt;/strong&gt;:&lt;/u&gt;&lt;br&gt;
Primitive data types in JavaScript are &lt;strong&gt;predefined&lt;/strong&gt; and built-in data types. They are simple and represent fundamental values. The primitive data types in JavaScript include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;String&lt;/strong&gt;: Represents textual data and is enclosed in single quotes ('') or double quotes ("").&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Number&lt;/strong&gt;: Represents numeric values, including integers and floating-point numbers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;BigInt&lt;/strong&gt;: Represents integers with arbitrary precision, allowing for the representation of extremely large numbers.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Boolean&lt;/strong&gt;: Represents a logical value, either true or false.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Undefined&lt;/strong&gt;: Represents a variable that has been declared but has not been assigned a value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Null&lt;/strong&gt;: Represents the intentional absence of any object value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Symbol&lt;/strong&gt;: Represents a unique and immutable value that can be used as an identifier for object properties.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;2.2 Non-primitive data types&lt;/strong&gt;:&lt;/u&gt;&lt;br&gt;
On the other hand, &lt;strong&gt;non-primitive&lt;/strong&gt; data types in JavaScript are derived from primitive data types. They are also known as reference data types or derived data types. Non-primitive data types include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Object&lt;/strong&gt;: Represents a collection of key-value pairs and can hold complex data structures.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Array&lt;/strong&gt;: Represents an ordered list of values, accessible by their index.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Function&lt;/strong&gt;: Represents a reusable block of code that performs a specific task.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Date&lt;/strong&gt;: Represents a specific moment in time.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;RegExp&lt;/strong&gt;: Represents a regular expression, used for pattern matching within strings.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Error&lt;/strong&gt;: Represents an error object that contains information about an error that occurred during the execution of code.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;The main difference between &lt;strong&gt;primitive&lt;/strong&gt; and &lt;strong&gt;non-primitive&lt;/strong&gt; data types is that primitive data types are &lt;strong&gt;immutable&lt;/strong&gt;, meaning their values cannot be changed, while non-primitive data types are &lt;strong&gt;mutable&lt;/strong&gt; and can be modified.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's understand what is mutable and immutable meaning?&lt;/p&gt;

&lt;p&gt;&lt;u&gt;&lt;strong&gt;2.3 Mutable :&lt;/strong&gt; &lt;/u&gt;&lt;br&gt;
Mutable objects or variables can be modified or changed after they are created. This means that their state or value can be altered without creating a new object. Examples of mutable objects in JavaScript include arrays and objects.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let mutableArray = [1, 2, 3];
mutableArray.push(4); // Modifying the array by adding an element
console.log(mutableArray); // Output: [1, 2, 3, 4]

let mutableObject = { name: "John", age: 25 };
mutableObject.age = 26; // Modifying the object by changing the age property
console.log(mutableObject); // Output: { name: "John", age: 26 }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;u&gt;2.4 &lt;strong&gt;Immutable&lt;/strong&gt;:&lt;/u&gt;&lt;/p&gt;

&lt;p&gt;Immutable objects or variables, on the other hand, cannot be changed once they are created. Any attempt to modify their value will result in the creation of a new object with the updated value, while the original object remains unchanged. Examples of immutable objects in JavaScript include strings and numbers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let immutableString = "Hello";
let newString = immutableString.toUpperCase(); // Creating a new string with modified value
console.log(immutableString); // Output: "Hello"
console.log(newString); // Output: "HELLO"

let immutableNumber = 5;
let newNumber = immutableNumber + 1; // Creating a new number with modified value
console.log(immutableNumber); // Output: 5
console.log(newNumber); // Output: 6

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;It's important to note that while primitive data types (such as strings and numbers) are immutable, objects (including arrays and custom objects) are mutable by default in JavaScript. However, you can use techniques like object freezing or immutability libraries to enforce immutability for objects if desired.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;&lt;u&gt;2.5 Dynamic and weak typing :&lt;/u&gt;&lt;/strong&gt;&lt;br&gt;
JavaScript is a dynamic language with dynamic types. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned) values of all types:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let foo = 42; // foo is now a number
foo = "bar"; // foo is now a string
foo = true; // foo is now a boolean

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;JavaScript is also a weakly typed language, which means it allows implicit type conversion when an operation involves mismatched types, instead of throwing type errors.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const foo = 42; // foo is a number
const result = foo + "1"; // JavaScript coerces foo to a string, so it can be concatenated with the other operand
console.log(result); // 421

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;3. Primitive data types&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In JavaScript, primitive data types are the most basic data types provided by the language. They are used to represent simple values and are not objects. Here are the primitive data types in JavaScript:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Number&lt;/strong&gt;: Represents numeric values, including integers and floating-point numbers. For example: 10, 3.14.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;String&lt;/strong&gt;: Represents a sequence of characters enclosed in single or double quotes. For example: 'Hello', "JavaScript".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Boolean&lt;/strong&gt;: Represents a logical value, either true or false. It is often used for conditional statements and comparisons.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Undefined&lt;/strong&gt;: Represents a variable that has been declared but has not been assigned a value. If a variable is declared without initialization, its value is undefined.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Null&lt;/strong&gt;: Represents the intentional absence of any object value. It is often used to indicate that a variable has no value or that an object does not exist.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Symbol&lt;/strong&gt;: Represents a unique identifier. Symbols are often used as keys in objects to avoid naming conflicts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;BigInt&lt;/strong&gt;: Represents integers with arbitrary precision. It can be used to store and perform operations on large numbers that exceed the limits of the Number type.&lt;/p&gt;

&lt;p&gt;These primitive data types are immutable, meaning their values cannot be changed once they are created. Additionally, they do not have any methods or properties associated with them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F733mdw6ux6am76cjmku0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F733mdw6ux6am76cjmku0.png" alt="Image description" width="619" height="207"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To understand more about and deep in primitive data type follow the below...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/imashwani/javascript-primitive-data-types-1l5"&gt;Full concept of Primitive data type&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;4. Non-Primitive data types&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Non-primitive data types in JavaScript are derived from the primitive data types and are also known as reference data types or derived data types. These data types are stored in the &lt;strong&gt;heap memory&lt;/strong&gt; of the system, unlike primitive data types which are stored in the &lt;strong&gt;stack space of the system&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In computer science, an object is a value in memory which is possibly referenced by an identifier. In JavaScript, objects are the only mutable values. Functions are, in fact, also objects with the additional capability of being callable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.1 Array&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript arrays are written with square brackets.&lt;/li&gt;
&lt;li&gt;Array items are separated by commas.&lt;/li&gt;
&lt;li&gt;An array is a special variable, which can hold more than one value.&lt;/li&gt;
&lt;li&gt;The following code declares (creates) an array called cars, containing three items (car names):
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = ["Saab", "Volvo", "BMW"];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Array indexes are zero-based, which means the first item is [0], second is [1], and so on.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can also create an array, and then provide the elements:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Accessing Array Elements:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You access an array element by referring to the &lt;strong&gt;index&lt;/strong&gt; &lt;strong&gt;number&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4.2 Objects&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript objects are written with curly braces {}.&lt;br&gt;
Objects are variables too. But objects can contain many values.&lt;br&gt;
Object properties are written as &lt;strong&gt;name:value&lt;/strong&gt; pairs, separated by &lt;strong&gt;commas&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Accessing Object Properties:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can access object properties in two ways:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;objectName.propertyName
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;objectName["propertyName"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How is an array an 'object'?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we know, arrays fall in the object category of JavaScript data types i.e they are stored by &lt;strong&gt;references&lt;/strong&gt; and NOT by their &lt;strong&gt;actual values&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;JavaScript simplifies the work of typeof by returning 'object' whenever the given expression is a reference to some data in memory.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An array is indeed a reference to an ordered bunch of data in memory and likewise translates to 'object' when inspected by the typeof operator.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;5. Difference between primitive and non primitive datatypes&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It's important to note that non-primitive data types are stored in the &lt;strong&gt;heap memory&lt;/strong&gt; of the system, while primitive data types are stored in &lt;strong&gt;the stack space of the system&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Primitive Data Types:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Predefined&lt;/strong&gt;: Primitive data types are predefined (already defined) in JavaScript.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Simple&lt;/strong&gt;: They are simple and basic data types.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Immutable&lt;/strong&gt;: Primitive values are immutable, meaning they cannot be changed once created.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stored by Value&lt;/strong&gt;: Primitive values are stored directly in memory and accessed by their value.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Examples&lt;/strong&gt;: Examples of primitive data types in JavaScript include numbers, strings, booleans, null, undefined, and symbols.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Non-Primitive Data Types:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Created by the Programmer&lt;/strong&gt;: Non-primitive data types are created by the programmer and are not predefined in JavaScript (except for String).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Complex&lt;/strong&gt;: They are more complex data types that can store collections or sets of data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mutable&lt;/strong&gt;: Non-primitive values are mutable, meaning they can be modified after creation.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Stored by Reference&lt;/strong&gt;: Non-primitive values are stored in memory as references and accessed by their reference.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Examples&lt;/strong&gt;: Examples of non-primitive data types in JavaScript include objects, arrays, functions, and regular expressions.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>tutorial</category>
      <category>programming</category>
    </item>
    <item>
      <title>JavaScript Non-Primitive Data Types</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Tue, 02 Apr 2024 07:01:09 +0000</pubDate>
      <link>https://dev.to/imashwani/javascript-non-primitive-data-types-2mjp</link>
      <guid>https://dev.to/imashwani/javascript-non-primitive-data-types-2mjp</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Non-Primitive data types&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Non-primitive data types in JavaScript are derived from the primitive data types and are also known as reference data types or derived data types. These data types are stored in the heap memory of the system, unlike primitive data types which are stored in the stack space of the system.&lt;/p&gt;

&lt;p&gt;In computer science, an object is a value in memory which is possibly referenced by an identifier. In JavaScript, objects are the only mutable values. Functions are, in fact, also objects with the additional capability of being callable.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const arr = [1,3,4,5];
console.log(typeof arr); // object

const obj = {name:"nick" age: 30};
console.log(typeof obj) //object
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;1. Array&lt;/strong&gt;
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript arrays are written with square brackets.&lt;/li&gt;
&lt;li&gt;Array items are separated by commas.&lt;/li&gt;
&lt;li&gt;An array is a special variable, which can hold more than one value.&lt;/li&gt;
&lt;li&gt;The following code declares (creates) an array called cars, containing three items (car names):
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = ["Saab", "Volvo", "BMW"];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Array indexes are zero-based, which means the first item is [0], second is [1], and so on.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can also create an array, and then provide the elements:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Accessing Array Elements:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You access an array element by referring to the &lt;strong&gt;index&lt;/strong&gt; &lt;strong&gt;number&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;2. Objects&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;JavaScript objects are written with curly braces {}.&lt;br&gt;
Objects are variables too. But objects can contain many values.&lt;br&gt;
Object properties are written as &lt;strong&gt;name:value&lt;/strong&gt; pairs, separated by &lt;strong&gt;commas&lt;/strong&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Accessing Object Properties:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;You can access object properties in two ways:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;objectName.propertyName
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;or&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;objectName["propertyName"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;How is an array an 'object'?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As we know, arrays fall in the object category of JavaScript data types i.e they are stored by &lt;strong&gt;references&lt;/strong&gt; and NOT by their &lt;strong&gt;actual values&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;JavaScript simplifies the work of typeof by returning 'object' whenever the given expression is a reference to some data in memory.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An array is indeed a reference to an ordered bunch of data in memory and likewise translates to 'object' when inspected by the typeof operator.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3 Difference between Array and Object Data Types in JavaScript&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In JavaScript, both arrays and objects are used to store and manipulate data, but they have some key differences. Let's explore these differences:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Arrays&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;An array is a collection of data stored in a sequence of memory locations.&lt;/li&gt;
&lt;li&gt;It can store various data types, including integers, floats, strings, and booleans .&lt;/li&gt;
&lt;li&gt;Array elements can be accessed using index numbers, starting from 0.&lt;/li&gt;
&lt;li&gt;Arrays are mutable, meaning you can add, remove, and modify elements in an array.&lt;/li&gt;
&lt;li&gt;Arrays have built-in methods and properties that allow for easy manipulation and iteration, such as push(), pop(), length, and forEach() .&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Objects:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;An object is a mutable data structure used to represent a thing or entity.&lt;/li&gt;
&lt;li&gt;It stores data in key-value pairs, where the keys can be any string or symbol except for undefined .&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>JavaScript Primitive Data Types</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Mon, 01 Apr 2024 15:01:28 +0000</pubDate>
      <link>https://dev.to/imashwani/javascript-primitive-data-types-1l5</link>
      <guid>https://dev.to/imashwani/javascript-primitive-data-types-1l5</guid>
      <description>&lt;p&gt;In JavaScript, primitive data types are the predefined data types provided by the language itself. They are also known as in-built data types. JavaScript has seven primitive data types: Number, String, Boolean, Undefined, Null, Symbol, and BigInt&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Primitive data types&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;We'll go over each of the primitive types one-by-one, starting with numbers.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F733mdw6ux6am76cjmku0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F733mdw6ux6am76cjmku0.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Null&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The null value represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as &lt;strong&gt;falsy&lt;/strong&gt; for &lt;strong&gt;boolean&lt;/strong&gt; operations.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getVowels(str) {
  const m = str.match(/[aeiou]/gi);
  if (m === null) {
    return 0;
  }
  return m.length;
}

console.log(getVowels('sky'));
// Expected output: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Syntax&lt;/strong&gt; -&amp;gt; null&lt;/p&gt;

&lt;p&gt;The value null is written with a literal: &lt;strong&gt;null&lt;/strong&gt;. null is not an identifier for a property of the global object, like undefined can be. Instead, null expresses a lack of identification, indicating that a variable points to no object. In APIs, null is often retrieved in a place where an object can be expected but no object is relevant.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// foo does not exist. It is not defined and has never been initialized:

foo; //ReferenceError: foo is not defined

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// foo is known to exist now but it has no type or value:
const foo = null;
foo; //null

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Undefined&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Undefined type is inhabited by exactly one value: undefined.&lt;/p&gt;

&lt;p&gt;Conceptually, undefined indicates the absence of a value, while null indicates the absence of an object (which could also make up an excuse for typeof null === "object"). The language usually defaults to undefined when something is devoid of a value:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A return statement with no value (return;) implicitly returns &lt;strong&gt;undefined&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Accessing a nonexistent object property (obj.iDontExist) returns &lt;strong&gt;undefined&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;A variable declaration without initialization (let x;) implicitly initializes the variable to &lt;strong&gt;undefined&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Many methods, such as Array.prototype.find() and Map.prototype.get(), return undefined when no element is found.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;null is used much less often in the core language. The most important place is the end of the prototype chain — subsequently, methods that interact with prototypes, such as Object.getPrototypeOf(), Object.create(), etc., accept or return null instead of undefined.&lt;/p&gt;

&lt;p&gt;null is a keyword, but undefined is a normal identifier that happens to be a global property. In practice, the difference is minor, since undefined should not be redefined or shadowed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Difference between null and undefined&lt;/strong&gt;:-&lt;/p&gt;

&lt;p&gt;When checking for null or undefined, beware of the differences between equality (==) and identity (===) operators, as the former performs type-conversion.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typeof null; // "object" (not "null" for legacy reasons)
typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
undefined === undefined; // true
undefined == undefined; // true
!null; // true
Number.isNaN(1 + null); // false
Number.isNaN(1 + undefined); // true

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Boolean&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The Boolean type represents a logical entity and is inhabited by two values: true and false.&lt;/p&gt;

&lt;p&gt;Boolean values are usually used for conditional operations, including ternary operators, if...else, while, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Boolean primitives and Boolean objects&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For converting non-boolean values to boolean, use Boolean as a function or use the double NOT operator. Do not use the Boolean() constructor with new.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const good = Boolean(expression);&lt;br&gt;
const good2 = !!expression; // you do use this!&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;const bad = new Boolean(expression); // don't use this!&lt;/code&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This is because all objects, including a &lt;strong&gt;Boolean object&lt;/strong&gt; whose wrapped value is false, are truthy and evaluate to true in places such as conditional statements. (See also the boolean coercion section below.)&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(typeof new Boolean()) // object

console.log(new Boolean()) // [Boolean: false]

console.log(new Boolean(true)) // [Boolean: true]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (new Boolean(true)) {
  console.log("This log is printed.");
}
// This log is printed.

if (new Boolean(false)) {
  console.log("This log is ALSO printed.");
}
//This log is ALSO printed.

if (new Boolean()) {
  console.log("This log is also printed.");
}
// This log is ALSO printed.

const myFalse = new Boolean(false); // myFalse is a Boolean object (not the primitive value false)
const g = Boolean(myFalse); // g is true
const myString = new String("Hello"); // myString is a String object
const s = Boolean(myString); // s is true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;u&gt;Boolean coercion&lt;/u&gt;&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Many built-in operations that expect booleans first coerce their arguments to booleans. The operation can be summarized as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;undefined turns into false.&lt;/li&gt;
&lt;li&gt;null turns into false.&lt;/li&gt;
&lt;li&gt;0, -0, and NaN turn into false; other numbers turn into true.&lt;/li&gt;
&lt;li&gt;0n turns into false; other BigInts turn into true.&lt;/li&gt;
&lt;li&gt;The empty string "" turns into false; other strings turn into true.&lt;/li&gt;
&lt;li&gt;Symbols turn into true.&lt;/li&gt;
&lt;li&gt;All objects become true.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Note: A legacy behavior makes document.all return false when used as a boolean, despite it being an object. This property is legacy and non-standard and should not be used.&lt;/p&gt;

&lt;p&gt;Note: Unlike other type conversions like string coercion or number coercion, boolean coercion does not attempt to convert objects to primitives.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In other words, there are only a handful of values that get coerced to false — these are called &lt;strong&gt;falsy&lt;/strong&gt; values. All other values are called &lt;strong&gt;truthy&lt;/strong&gt; values. A value's truthiness is important when used with logical operators, conditional statements, or any boolean context.&lt;/p&gt;

&lt;p&gt;There are two ways to achieve the same effect in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Double NOT:&lt;/strong&gt; !!x negates x twice, which converts x to a boolean using the same algorithm as above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Boolean() function:&lt;/strong&gt; Boolean(x) uses the same algorithm as above to convert x.&lt;/p&gt;

&lt;p&gt;Note that truthiness is not the same as being loosely equal to true or false.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if ([]) {
  console.log("[] is truthy");
}
if ([] == false) {
  console.log("[] == false");
}
// [] is truthy
// [] == false

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Creating Boolean objects with an initial value of false&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bNoParam = new Boolean(); // [Boolean: false]
const bZero = new Boolean(0); // [Boolean: false]
const bNull = new Boolean(null); // [Boolean: false]
const bEmptyString = new Boolean(""); // [Boolean: false]
const bfalse = new Boolean(false); // [Boolean: false]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Creating Boolean objects with an initial value of true&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const btrue = new Boolean(true); // [Boolean: true]
const btrueString = new Boolean("true"); // [Boolean: true]
const bfalseString = new Boolean("false"); // [Boolean: true]
const bSuLin = new Boolean("Su Lin"); // [Boolean: true]
const bArrayProto = new Boolean([]); // [Boolean: true]
const bObjProto = new Boolean({}); // [Boolean: true]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Number type&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The number type represents both integer and floating point numbers.&lt;/p&gt;

&lt;p&gt;JavaScript has only one type of number, which is a 64-bit floating-point number. This means that JavaScript numbers are always stored as double precision floating-point numbers, following the international IEEE 754 standard.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 3.14;    // A number with decimals
let y = 3;       // A number without decimals
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Extra large or extra small numbers can be written with scientific (exponent) notation:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 123e5;    // 12300000
let y = 123e-5;   // 0.00123
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Integer Precision :-&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Integers (numbers without a period or exponent notation) are accurate up to 15 digits.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 999999999999999;   
let y = 9999999999999999;   

console.log(x); // 999999999999999
console.log(y); // 10000000000000000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Floating Precision :-&lt;/strong&gt;&lt;br&gt;
Floating point arithmetic is not always 100% accurate:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 0.2 + 0.1; 
console.log(x) // 0.30000000000000004

let y = (0.2*10 + 0.1*10) / 10;
console.log(y) //0.3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Adding Numbers and Strings:-&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;-&lt;br&gt;
JavaScript uses the &lt;strong&gt;+&lt;/strong&gt; operator for both &lt;strong&gt;addition **and **concatenation&lt;/strong&gt;.&lt;br&gt;
&lt;strong&gt;Numbers are added. Strings are concatenated.&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 10;
let y = 20;
let z = x + y; // 30

let x = "10";
let y = "20";
let z = x + y;  // 1020
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you add a &lt;strong&gt;number&lt;/strong&gt; and a &lt;strong&gt;string&lt;/strong&gt;, the result will be a &lt;strong&gt;string concatenation&lt;/strong&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "10";
let y = 20;
let z = x + y; // 1020
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt; A common mistake is to expect in this below result to be 30.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 10;
let y = 20;
let z = "The result is: " + x + y; // The result is: 1020
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt; A common mistake is to expect in this below result to be 102030:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 10;
let y = 20;
let z = "30";
let result = x + y + z; // 3030
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt; &lt;br&gt;
The JavaScript &lt;strong&gt;interpreter&lt;/strong&gt; works from &lt;strong&gt;left to right&lt;/strong&gt;.&lt;br&gt;
First 10 + 20 is added because x and y are both &lt;strong&gt;numbers&lt;/strong&gt;.&lt;br&gt;
Then 30 + "30" is concatenated because z is a &lt;strong&gt;string&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Numeric Strings:-&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript strings can have numeric content:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;let x = 100;         // x is a number&lt;br&gt;
let y = "100";       // y is a string&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;JavaScript will try to &lt;strong&gt;convert strings to numbers&lt;/strong&gt; in all &lt;strong&gt;numeric operations&lt;/strong&gt;:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "100";
let y = "10";
let z = x / y;
console.log(z) // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "100";
let y = "10";
let z = x * y;
console.log(z) // 1000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "100";
let y = "10";
let z = x - y;
console.log(z) // 90
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The below will not work because JavaScript uses the &lt;strong&gt;+&lt;/strong&gt; operator to &lt;strong&gt;concatenate the strings&lt;/strong&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "100";
let y = "10";
let z = x + y; //10010
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;NaN - Not a Number:-&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;NaN&lt;/strong&gt; is a JavaScript reserved word indicating that a number is &lt;strong&gt;not a legal number&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 100 / "Apple"; 
console.log(x) // Nan

However, if the string is numeric, the result will be a number:

let x = 100 / "10";
console.log(x) // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can use the global JavaScript function &lt;strong&gt;isNaN()&lt;/strong&gt; to find out if a value is a not a number:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 100 / "Apple";
let y = isNaN(x);
console.log(y) // true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the below example, If you use NaN in a mathematical operation, the result will also be &lt;strong&gt;NaN&lt;/strong&gt;:&lt;br&gt;
Or the result might be a concatenation like &lt;strong&gt;NaN5&lt;/strong&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = NaN;
let y = 5;
let z = x + y;
console.log(z) // NaN

let x = NaN;
let y = "5";
let z = x + y;
console.log(z) // NaN5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;NaN is a number: typeof NaN returns number:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(typeof NaN) // number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Infinity :-&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myNumber = 2;
// Execute until Infinity
while (myNumber != Infinity) {
  myNumber = myNumber * myNumber;
}
console.log(myNumber) // Infinity
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Division by 0 (zero) also generates &lt;strong&gt;Infinity&lt;/strong&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x =  2 / 0;
let y = -2 / 0;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt; -Infinity is a number: &lt;strong&gt;typeof Infinity&lt;/strong&gt; returns number.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(typeof Infinity) // number
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Hexadecimal:-&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 0xFF;
console.log(x) // 255
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Never write a number with a leading zero (like 07).&lt;br&gt;
Some JavaScript versions interpret numbers as octal if they are written with a leading zero.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;By default, JavaScript displays numbers as &lt;strong&gt;base 10&lt;/strong&gt; decimals.&lt;/li&gt;
&lt;li&gt;But you can use the &lt;strong&gt;toString()&lt;/strong&gt; method to output numbers from &lt;strong&gt;base 2&lt;/strong&gt; to &lt;strong&gt;base 36&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Hexadecimal is &lt;strong&gt;base 16&lt;/strong&gt;. Decimal is &lt;strong&gt;base 10&lt;/strong&gt;. Octal is &lt;strong&gt;base 8&lt;/strong&gt;. Binary is &lt;strong&gt;base 2&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myNumber = 32;
myNumber.toString(32);
myNumber.toString(16);
myNumber.toString(12);
myNumber.toString(10);
myNumber.toString(8);
myNumber.toString(2);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;JavaScript Numbers as Objects:-&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Normally JavaScript numbers are primitive values created from literals:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 123;
let y = new Number(123);

console.log(x, y, typeof y) //123, [Number: 123], object
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;ul&gt;
&lt;li&gt;Do not create Number objects.&lt;/li&gt;
&lt;li&gt;The new keyword complicates the code and slows down execution speed.&lt;/li&gt;
&lt;li&gt;Number Objects can produce unexpected results:&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 500;
let y = new Number(500);
console.log(x == y) // true
console.log(x === y) // false

let a = new Number(500);
let b = new Number(500);

console.log(a == b) // true
console.log(a === b) // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;Comparing two JavaScript objects always returns false.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;BigInt type&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;JavaScript BigInt variables are used to store big integer values that are too big to be represented by a normal JavaScript Number.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JavaScript Integer Accuracy&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;JavaScript integers are only accurate up to 15 digits:&lt;br&gt;
let x = 999999999999999;&lt;br&gt;
let y = 9999999999999999;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In JavaScript, all numbers are stored in a 64-bit floating-point format (IEEE 754 standard).&lt;/li&gt;
&lt;li&gt;With this standard, large integer cannot be exactly represented and will be rounded.&lt;/li&gt;
&lt;li&gt;Because of this, JavaScript can only safely represent integers: Up to 9007199254740991 +(253-1) and Down to -9007199254740991 -(253-1).&lt;/li&gt;
&lt;li&gt;Integer values outside this range lose precision.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;How to Create a BigInt&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To create a BigInt, append n to the end of an integer or call BigInt():&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 9999999999999999;
let y = 9999999999999999n;

console.log(x) //10000000000000000
console.log(y) //9999999999999999n
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = 1234567890123456789012345n;
let y = BigInt(1234567890123456789012345)

console.log(x) //1234567890123456789012345n
console.log(y) //1234567890123456824475648n
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = BigInt(999999999999999);
let type = typeof x;

console.log(x) //999999999999999n
console.log(type) //bigint
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;the JavaScript &lt;strong&gt;typeof a BigInt&lt;/strong&gt; is &lt;strong&gt;"bigint"&lt;/strong&gt;:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;String type&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A string in JavaScript must be surrounded by quotes.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let str = "Hello";
let str2 = 'Single quotes are ok too';
let phrase = `can embed another ${str}`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In JavaScript, there are 3 types of quotes.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Double quotes: "Hello".&lt;/li&gt;
&lt;li&gt;Single quotes: 'Hello'.&lt;/li&gt;
&lt;li&gt;Backticks: &lt;code&gt;Hello&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Double&lt;/strong&gt; and &lt;strong&gt;single quotes&lt;/strong&gt; are “simple” quotes. There’s practically no difference between them in JavaScript.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Backticks&lt;/strong&gt; are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}, for example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = "John";

// embed a variable
alert( `Hello, ${name}!` ); // Hello, John!

// embed an expression
alert( `the result is ${1 + 2}` ); // the result is 3
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;The expression inside ${…} is evaluated and the result becomes a part of the string. We can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more complex.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Please note that this can only be done in backticks. Other quotes don’t have this embedding functionality!&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;alert( "the result is ${1 + 2}" ); 
// the result is ${1 + 2} (double quotes do nothing)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Template Strings:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Templates were introduced with ES6 (JavaScript 2016).&lt;/li&gt;
&lt;li&gt;Templates are strings enclosed in backticks (&lt;code&gt;This is a template string&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Templates allow single and double quotes inside a string:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = `He's often called "Johnny"`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;String Length:&lt;/strong&gt;&lt;br&gt;
To find the length of a string, use the built-in length property:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length; //26
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Escape Characters:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Because strings must be written within quotes, JavaScript will misunderstand this string:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = "We are the so-called "Vikings" from the north.";
console.log(text);
// SyntaxError: Unexpected identifier
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;To solve this problem, you can use an backslash escape character.&lt;br&gt;
The backslash escape character () turns special characters into string characters:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Code    Result  Description&lt;br&gt;
\'  '   Single quote&lt;br&gt;
\"  "   Double quote&lt;br&gt;
\  \   Backslash&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let text = "We are the so-called \"Vikings\" from the north.";
console.log(text); // We are the so-called "Vikings" from the north.

let text= 'It\'s alright.';
let text = "The character \\ is called backslash.";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;ul&gt;
&lt;li&gt;Six other escape sequences are valid in JavaScript:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Code    Result&lt;br&gt;
\b  Backspace&lt;br&gt;
\f  Form Feed&lt;br&gt;
\n  New Line&lt;br&gt;
\r  Carriage Return&lt;br&gt;
\t  Horizontal Tabulator&lt;br&gt;
\v  Vertical Tabulator&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;JavaScript Strings as Objects:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Normally, JavaScript strings are primitive values, created from literals:&lt;/p&gt;

&lt;p&gt;strings can also be defined as objects with the keyword new:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "John";
let y = new String("John");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note:-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Do not create Strings objects.&lt;/li&gt;
&lt;li&gt;The new keyword complicates the code and slows down execution speed.&lt;/li&gt;
&lt;li&gt;String objects can produce unexpected results:&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = "John"; //john
let y = new String("John"); //[String: 'John']
console.log(x == y) //true
console.log(x === y) //false
console.log(typeof x) //string
console.log(typeof y) //object
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let x = new String("John");
let y = new String("John");
console.log(x == y) //false
console.log(x === y) //false
console.log(typeof y) //object
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Symbol type&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called "atoms". The purpose of symbols is to create unique property keys that are guaranteed not to clash with keys from other code.&lt;/p&gt;

&lt;p&gt;To create a new primitive Symbol, you write Symbol() with an optional string as its description:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");

console.log(sym1) //Symbol()
console.log(sym2) //Symbol(foo)
console.log(sym3) //Symbol(foo)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;blockquote&gt;
&lt;p&gt;The above code creates three new Symbols. Note that Symbol("foo") does not coerce the string "foo" into a Symbol. It creates a new Symbol each time:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sym2 = Symbol("foo");
const sym3 = Symbol("foo");

console.log(sym2 === sym3) // false
console.log(sym2 == sym3) //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Note:-&lt;/strong&gt; &lt;br&gt;
Symbols are the only primitive data type that has reference identity (that is, you cannot create the same symbol twice).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sym = Symbol("foo");
typeof sym; // "symbol"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
      <category>programming</category>
    </item>
    <item>
      <title>Integrating Nodemailer in a Node.js Project</title>
      <dc:creator>Ashwani Singh</dc:creator>
      <pubDate>Tue, 19 Mar 2024 15:13:15 +0000</pubDate>
      <link>https://dev.to/imashwani/integrating-nodemailer-in-a-nodejs-project-4mfh</link>
      <guid>https://dev.to/imashwani/integrating-nodemailer-in-a-nodejs-project-4mfh</guid>
      <description>&lt;h2&gt;
  
  
  &lt;strong&gt;Integrating Nodemailer in a Node.js Project&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;To integrate Nodemailer in a Node.js project, you can follow these steps:&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;1. Install Nodemailer&lt;/strong&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install nodemailer --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This will install Nodemailer and add it to your project's dependencies .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;2. Set Up Nodemailer in Your Project:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;After installing Nodemailer, you can include it in your Node.js application using the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var nodemailer = require('nodemailer');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;If you are using ES modules, you can use the import statement instead .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;3. Create a Transporter:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Use the createTransport method to create a transporter for sending emails. You can specify the email service (e.g. Gmail, outlook, aws ses ect.) and provide authentication details:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: 'youremail@gmail.com',
    pass: 'yourpassword'
  }
});

-------------------------or--------------------------
var transporter = nodemailer.createTransport({
        service: "Outlook365",
        host: "smtp.office365.com",
        port: "587",
        auth: {
         user: 'youremail@gmail.com',
         pass: 'yourpassword',
        },
        requireTLS: true,
      });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Replace '&lt;a href="mailto:youremail@gmail.com"&gt;youremail@gmail.com&lt;/a&gt;' with your email address and 'yourpassword' with your email password .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;4. Send an Email:&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Once the transporter is set up, you can use it to send an email. Here's an example of how to send a simple email:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var mailOptions = {
  from: 'youremail@gmail.com',
  to: 'recipient@example.com',
  subject: 'Subject of the Email',
  text: 'Body/template of the Email'
};

transporter.sendMail(mailOptions, function(error, info) {
  if (error) {
    console.log(error);
  } else {
    console.log('Email sent: ' + info.response);
  }
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Replace '&lt;a href="mailto:youremail@gmail.com"&gt;youremail@gmail.com&lt;/a&gt;' with your email address, '&lt;a href="mailto:recipient@example.com"&gt;recipient@example.com&lt;/a&gt;' with the recipient's email address, and provide the subject and body of the email as needed .&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;These steps outline the process of integrating Nodemailer in a Node.js project and sending emails using Nodemailer and Gmail/outlook/aws ect. Remember to handle sensitive information such as email credentials securely in your project.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you want to make you gmail/outlook will able to send email through code, you will also need to provide authentication of nodemailer in setting of gmail/aws/outlook etc.&lt;/p&gt;

&lt;p&gt;For best practice, put all the credential in &lt;code&gt;.env&lt;/code&gt; file, and call it in the function to make active.&lt;/p&gt;

&lt;p&gt;e.g:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;.env file&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SMTP_PASS = xxxxxxxx
SMTP_HOST = amazonaws.com / gmail / office365.com
STMP_PORT = 5187
FROM_Email = youremail@gmail.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;create an export function to call when send an mail.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function mailSend(email_id, otp) {

    let mailTransporter = nodemailer.createTransport({
        service: 'aws',
        host: process.env.SMTP_HOST,
        auth: {
            user: process.env.SMTP_USER_NAME,
            pass: process.env.SMTP_PASS
        }
    });

    let mailDetails = {
        from: process.env.FROM_Email,
        to:   `${email_id}`,
        subject: 'Otp send by Team',
        text : `OTP is ${otp}`

    };

    mailTransporter.sendMail(mailDetails, function(err, data) {
        if(err) {
            console.log('Error Occurs', err);
        } else {
            console.log('Email sent successfully');
        }
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Call mailSend function when you want to initiate nodemailer to send otp.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mailSend(email_id, '983844');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>node</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
