<?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: Saqib Jamil</title>
    <description>The latest articles on DEV Community by Saqib Jamil (@saqibjamil7866).</description>
    <link>https://dev.to/saqibjamil7866</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%2F520305%2F8ac5cebb-d490-4292-b66a-51b5c3f665ca.jpeg</url>
      <title>DEV Community: Saqib Jamil</title>
      <link>https://dev.to/saqibjamil7866</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/saqibjamil7866"/>
    <language>en</language>
    <item>
      <title>5 JavaScript coding interview questions - Part 8</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Mon, 06 Oct 2025 14:37:59 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-8-2gbb</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-8-2gbb</guid>
      <description>&lt;p&gt;&lt;strong&gt;Q1: Find the Intersection of Two Arrays.&lt;/strong&gt;&lt;br&gt;
  &lt;strong&gt;Write a function that returns the common elements between two arrays.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Ans:&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 arrayIntersection(arr1, arr2) {
  return arr1.filter(item =&amp;gt; arr2.includes(item));
}

console.log(arrayIntersection([1, 2, 3, 4], [3, 4, 5, 6])); 
// Output: [3, 4]

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

&lt;/div&gt;



&lt;p&gt;🧠 Tip: Use Set for better performance with large datasets.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q2: Capitalize the First Letter of Each Word.&lt;br&gt;
Write a function that takes a sentence and capitalizes the first letter of each word.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Ans:&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 capitalizeWords(sentence) {
  return sentence
    .split(" ")
    .map(word =&amp;gt; word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}

console.log(capitalizeWords("hello world from javascript"));
// Output: "Hello World From Javascript"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q3: Count the Frequency of Each Element in an Array&lt;br&gt;
Write a function that counts how many times each element appears in an array.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Ans:&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 countFrequency(arr) {
  return arr.reduce((acc, item) =&amp;gt; {
    acc[item] = (acc[item] || 0) + 1;
    return acc;
  }, {});
}

console.log(countFrequency(["apple", "banana", "apple", "orange", "banana", "apple"]));
// Output: { apple: 3, banana: 2, orange: 1 }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q4: Check if Two Strings Are Anagrams&lt;br&gt;
Write a function to check whether two strings are anagrams of each other.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Ans:&lt;/strong&gt;&lt;br&gt;
Anagrams are words or phrases that can be rearranged to make an entirely different word or phrase.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function isAnagram(str1, str2) {
  const normalize = str =&amp;gt; str.toLowerCase().split("").sort().join("");
  return normalize(str1) === normalize(str2);
}

console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world"));   // false

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

&lt;/div&gt;



&lt;p&gt;💡 Explanation:&lt;br&gt;
We normalize both strings by converting them to lowercase, sorting, and comparing.&lt;br&gt;
If both sorted versions match — they’re anagrams!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q5: Chunk an Array&lt;br&gt;
Write a function that splits an array into chunks of a specified size.&lt;br&gt;
Ans:&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 chunkArray(arr, size) {
  let result = [];
  for (let i = 0; i &amp;lt; arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }
  return result;
}

console.log(chunkArray([1, 2, 3, 4, 5, 6, 7], 3));
// Output: [[1, 2, 3], [4, 5, 6], [7]]

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

&lt;/div&gt;



&lt;p&gt;💡 Explanation:&lt;br&gt;
This is the core part of the loop that allows the function to chunk the array efficiently. Let’s go step by step 👇&lt;br&gt;
&lt;code&gt;for (let i = 0; i &amp;lt; arr.length; i += size)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;🧩 1. Normal for-loop structure&lt;br&gt;
A typical for loop looks like this:&lt;br&gt;
&lt;code&gt;for (initialization; condition; increment) {&lt;br&gt;
  // code to execute&lt;br&gt;
}&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;initialization — sets up a variable (like let i = 0)&lt;/li&gt;
&lt;li&gt;condition — loop continues while this is true&lt;/li&gt;
&lt;li&gt;increment — runs after each loop iteration (to move to the next step)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🧠 2. In this code:&lt;br&gt;
&lt;code&gt;for (let i = 0; i &amp;lt; arr.length; i += size)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;let i = 0 → start from index 0&lt;/li&gt;
&lt;li&gt;i &amp;lt; arr.length → keep looping until i reaches the end of the array&lt;/li&gt;
&lt;li&gt;i += size → instead of increasing i by 1, we increase it by size
That means each time, the loop jumps forward by size elements.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;💡 3. Example to visualize&lt;br&gt;
Suppose:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;arr = [1, 2, 3, 4, 5, 6, 7]
size = 3

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

&lt;/div&gt;



&lt;p&gt;Here’s how the loop runs:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Iteration&lt;/th&gt;
&lt;th&gt;
&lt;code&gt;i&lt;/code&gt; Value&lt;/th&gt;
&lt;th&gt;Slice (&lt;code&gt;arr.slice(i, i + size)&lt;/code&gt;)&lt;/th&gt;
&lt;th&gt;Result&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;td&gt;arr.slice(0, 3) → &lt;code&gt;[1, 2, 3]&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;result = &lt;code&gt;[[1,2,3]]&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;2&lt;/td&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;arr.slice(3, 6) → &lt;code&gt;[4, 5, 6]&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;result = &lt;code&gt;[[1,2,3],[4,5,6]]&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;3&lt;/td&gt;
&lt;td&gt;6&lt;/td&gt;
&lt;td&gt;arr.slice(6, 9) → &lt;code&gt;[7]&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;result = &lt;code&gt;[[1,2,3],[4,5,6],[7]]&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;After that, i = 9, which is greater than arr.length (7), so the loop stops.&lt;/p&gt;

&lt;p&gt;✅ Final Thoughts&lt;/p&gt;

&lt;p&gt;These questions are simple yet powerful for testing problem-solving and array manipulation in JavaScript.&lt;/p&gt;

&lt;p&gt;If you haven’t already, check out my previous parts:&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-1-2c4c"&gt;Part 1&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m"&gt;Part 2&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk"&gt;Part 3&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e"&gt;Part 4&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd"&gt;Part 5&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6"&gt;Part 6&lt;/a&gt;&lt;br&gt;
👉 &lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-7-eek"&gt;Part 7&lt;/a&gt;&lt;/p&gt;

</description>
      <category>interview</category>
      <category>algorithms</category>
      <category>career</category>
      <category>javascript</category>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 7</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Fri, 26 Sep 2025 19:58:58 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-7-eek</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-7-eek</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6?utm_source=chatgpt.com"&gt;5 Javascript coding interview questions - Part 6&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-8-2gbb"&gt;5 Javascript coding interview questions - Part 8&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1. Flatten a Nested Object&lt;br&gt;
Write a function that takes a nested object and flattens it into a single-level object with dot-separated keys.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&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 flattenObject(obj, parent = '', res = {}){
  for(let key in obj){
    let newKey = parent ? `${parent}.${key}` : key;
    if(typeof obj[key] === 'object' &amp;amp;&amp;amp; obj[key] !== null &amp;amp;&amp;amp; !Array.isArray(obj[key])){
      flattenObject(obj[key], newKey, res);
    } 
   else{
      res[newKey] = obj[key];
    }
  }
  return res;
}

// Example
const input = { a: 1, b: { c: 2, d: { e: 3 } } };
console.log(flattenObject(input)); 
// { a: 1, "b.c": 2, "b.d.e": 3 }

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q2. Debounce Function&lt;br&gt;
Implement a debounce function to delay execution until after a pause in calls.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&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 debounce(fn, delay){
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() =&amp;gt; fn.apply(this, args), delay);
  };
}

// Example
const log = debounce(() =&amp;gt; console.log("Debounced!"), 1000);
log();
log();
log(); // Only runs once after 1s

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q3. Throttle Function&lt;br&gt;
Implement a throttle function to limit execution of a function to once every X milliseconds.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&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 throttle(fn, limit) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall &amp;gt;= limit) {
      lastCall = now;
      fn.apply(this, args);
    }
  };
}

// Example
const log = throttle(() =&amp;gt; console.log("Throttled!"), 2000);
setInterval(log, 500); // Runs every 2s, not every 0.5s

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q4. Group Anagrams&lt;br&gt;
Given an array of strings, group words that are anagrams of each other.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&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 groupAnagrams(words) {
  const map = {};
  for (let word of words) {
    const key = word.split('').sort().join('');
    if (!map[key]) map[key] = [];
    map[key].push(word);
  }
  return Object.values(map);
}

// Example
console.log(groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]));
// [["eat","tea","ate"], ["tan","nat"], ["bat"]]

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q5. Currying Function&lt;br&gt;
Implement a function that transforms a normal function into a curried one.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&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 curry(fn) {
  return function curried(...args) {
    if (args.length &amp;gt;= fn.length) {
      return fn.apply(this, args);
    } else {
      return function (...nextArgs) {
        return curried.apply(this, args.concat(nextArgs));
      };
    }
  };
}

// Example
function add(a, b, c) {
  return a + b + c;
}

const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)(3)); // 6
console.log(curriedAdd(1, 2)(3)); // 6

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

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6?utm_source=chatgpt.com"&gt;5 Javascript coding interview questions - Part 6&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>programming</category>
      <category>coding</category>
    </item>
    <item>
      <title>What is Temporal dead zone in javascript?</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Sun, 29 Dec 2024 17:06:03 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/what-is-temporal-dead-zone-in-javascript-1pn9</link>
      <guid>https://dev.to/saqibjamil7866/what-is-temporal-dead-zone-in-javascript-1pn9</guid>
      <description>&lt;p&gt;The Temporal Dead Zone (TDZ) in JavaScript refers to the period between the creation of a variable in the scope and its initialization. During this period, the variable is in an uninitialized state and cannot be accessed. Attempting to access it will result in a ReferenceError.&lt;/p&gt;

&lt;p&gt;Key Points:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;TDZ occurs with let and const: Unlike var, variables declared with let and const are not hoisted to the top of their scope in an accessible way.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Access before initialization throws ReferenceError: The variable exists in memory but is not initialized until the declaration is executed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;TDZ ends when the variable is initialized: Once the declaration line is executed, the variable becomes accessible.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Code Example 1: Accessing a Variable in the TDZ&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;console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 10;
console.log(x); // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The variable x exists in memory due to let declaration but is not initialized.&lt;/li&gt;
&lt;li&gt;Attempting to access it before initialization throws a ReferenceError.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example 2: TDZ with const&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;console.log(y); // ReferenceError: Cannot access 'y' before initialization
const y = 20;
console.log(y); // 20
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;const behaves the same as let during the TDZ. Accessing y before its initialization results in a ReferenceError.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example 3: TDZ in Block Scope&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;{
    console.log(a); // ReferenceError: Cannot access 'a' before initialization
    let a = 5;
    console.log(a); // 5
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The variable a is in the TDZ until the let a = 5 line is executed within the block.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example 4: No TDZ with var&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;console.log(b); // undefined
var b = 15;
console.log(b); // 15
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Variables declared with var are hoisted and initialized with undefined. There is no TDZ for var.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example 5: Function and TDZ&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 example() {
    console.log(c); // ReferenceError: Cannot access 'c' before initialization
    let c = 30;
}
example();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;c is in the TDZ until the let c = 30 line is executed.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Code Example 6: TDZ with Default Parameter&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 test(x = y, y = 10) {
    console.log(x, y);
}
test(); // ReferenceError: Cannot access 'y' before initialization
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Default parameters are evaluated left-to-right. Here, x tries to access y before it is initialized, causing a ReferenceError.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;How to Avoid Issues with TDZ&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Declare variables at the top of their scope.&lt;/li&gt;
&lt;li&gt;Initialize variables immediately after declaring them if possible.&lt;/li&gt;
&lt;li&gt;Understand the block scope behavior of let and const.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By being mindful of the TDZ, you can write more predictable and bug-free JavaScript code.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>temporaldeadzone</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
    <item>
      <title>Event Delegation in JavaScript</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Wed, 11 Dec 2024 18:38:06 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/event-delegation-in-javascript-nmp</link>
      <guid>https://dev.to/saqibjamil7866/event-delegation-in-javascript-nmp</guid>
      <description>&lt;p&gt;&lt;strong&gt;Event Delegation&lt;/strong&gt; is a technique in JavaScript where you add a single event listener to a parent element instead of adding multiple event listeners to child elements. The event listener on the parent element listens for events on its children using event bubbling.&lt;/p&gt;

&lt;p&gt;This technique is useful for improving performance and managing dynamically added elements.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How Event Delegation Works&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Event Bubbling: When an event occurs on an element, it bubbles up from the target element to its parent elements.&lt;/li&gt;
&lt;li&gt;Event Targeting: You can identify which child element triggered the event using the event.target property.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Why Use Event Delegation?&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Better performance (especially for a large number of elements).&lt;/li&gt;
&lt;li&gt;Simplifies code by reducing the number of event listeners.&lt;/li&gt;
&lt;li&gt;Works well with dynamically added elements.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example: Without Event Delegation&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;// Add individual event listeners to each button
const buttons = document.querySelectorAll(".child-button");
buttons.forEach((button) =&amp;gt; {
  button.addEventListener("click", (event) =&amp;gt; {
    console.log(`Button ${event.target.textContent} clicked!`);
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Drawback:&lt;/strong&gt;&lt;br&gt;
If you dynamically add a new button, the event listener won’t be automatically applied.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: With Event Delegation&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;// Add one event listener to the parent element
const parent = document.querySelector(".parent");

parent.addEventListener("click", (event) =&amp;gt; {
  if (event.target.classList.contains("child-button")) {
    console.log(`Button ${event.target.textContent} clicked!`);
  }
});

//HTML
&amp;lt;div class="parent"&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 1&amp;lt;/button&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 2&amp;lt;/button&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 3&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



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

&lt;ol&gt;
&lt;li&gt;The event listener is added only to the parent (.parent).&lt;/li&gt;
&lt;li&gt;When any button inside the parent is clicked, the event.target identifies the specific button.&lt;/li&gt;
&lt;li&gt;You use a condition (event.target.classList.contains) to ensure the event handler runs only for child-button.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Benefits of Event Delegation&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Dynamically Added Elements:
Event delegation works for elements added after the page is loaded.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Dynamically add a new button
const parent = document.querySelector(".parent");
const newButton = document.createElement("button");
newButton.className = "child-button";
newButton.textContent = "Button 4";
parent.appendChild(newButton);

// No need to add a new event listener manually
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Reduced Memory Usage:
Instead of attaching event listeners to multiple elements, a single listener is attached to the parent.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Summary:&lt;/strong&gt;&lt;br&gt;
Event delegation is a powerful pattern for efficiently handling events on many elements, especially when they are created dynamically. It uses the event bubbling and event.target to manage events effectively.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 6</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Wed, 11 Dec 2024 18:16:15 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd"&gt;5 Javascript coding interview questions - Part 5&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-7-eek"&gt;5 Javascript coding interview questions - Part 7&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1: What is the difference between let, const, and var?&lt;/strong&gt;&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;var: Function-scoped, can be redeclared, hoisted, and doesn’t support block scoping.&lt;/li&gt;
&lt;li&gt;let: Block-scoped, can’t be redeclared in the same scope, hoisted but not initialized.
&lt;/li&gt;
&lt;li&gt;const: Block-scoped, must be initialized at declaration, hoisted but not initialized. its value cannot be reassigned.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;const&lt;/strong&gt; and &lt;strong&gt;let&lt;/strong&gt; variables are hoisted, but they are not accessible before their declaration due to the &lt;a href="https://dev.to/saqibjamil7866/what-is-temporal-dead-zone-in-javascript-1pn9"&gt;temporal dead zone (TDZ)&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;// var example
if (true) {
  var x = 10;
}
console.log(x); // 10

// let example
if (true) {
  let y = 20;
  console.log(y); // 20
}
// console.log(y); // ReferenceError: y is not defined

// const example
const z = 30;
// z = 40; // TypeError: Assignment to constant variable
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q2: What is Event Delegation in JavaScript?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; Event Delegation is a technique in JavaScript where you add a single event listener to a parent element instead of adding multiple event listeners to child elements. The event listener on the parent element listens for events on its children using event bubbling.&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/event-delegation-in-javascript-nmp"&gt;Here is my separate blog on event delegation&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;// Add one event listener to the parent element
const parent = document.querySelector(".parent");

parent.addEventListener("click", (event) =&amp;gt; {
  if (event.target.classList.contains("child-button")) {
    console.log(`Button ${event.target.textContent} clicked!`);
  }
});

//HTML
&amp;lt;div class="parent"&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 1&amp;lt;/button&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 2&amp;lt;/button&amp;gt;
  &amp;lt;button class="child-button"&amp;gt;Button 3&amp;lt;/button&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q3: What is the this keyword in JavaScript?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; The value of this depends on the context:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In global scope, it refers to the global object (e.g., window in browsers).&lt;/li&gt;
&lt;li&gt;Inside a function, it depends on how the function is called (e.g., in strict mode, it’s undefined by default).&lt;/li&gt;
&lt;li&gt;Inside an object method, it refers to the object.&lt;/li&gt;
&lt;li&gt;  Inside an arrow function, it inherits this from the parent context.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const obj = {
  name: 'JavaScript',
  regularFunc() {
    console.log(this.name); // 'JavaScript'
  },
  arrowFunc: () =&amp;gt; {
    console.log(this.name); // undefined (inherits from global scope)
  },
};

obj.regularFunc();
obj.arrowFunc();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q4: How do you flatten a deeply nested array in JavaScript?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; You can use recursion or the Array.prototype.flat() method with an appropriate depth.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Recursive function to flatten an array
function flattenArray(arr) {
  return arr.reduce((acc, val) =&amp;gt; 
    Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}

const nestedArray = [1, [2, [3, [4, 5]]]];
console.log(flattenArray(nestedArray)); // [1, 2, 3, 4, 5]

// Using flat()
console.log(nestedArray.flat(Infinity)); // [1, 2, 3, 4, 5]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q5: What is the difference between == and === in JavaScript?&lt;/strong&gt;&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;== compares values after performing type coercion.&lt;/li&gt;
&lt;li&gt;=== compares values and types without type coercion.
&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(5 == '5');  // true (type coercion occurs)
console.log(5 === '5'); // false (no type coercion, types are different)

console.log(null == undefined);  // true (both are loosely equal)
console.log(null === undefined); // false (different types)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd"&gt;5 Javascript coding interview questions - Part 5&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-7-eek"&gt;5 Javascript coding interview questions - Part 7&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript and Its Core Concepts: A Beginner’s Guide to Web Development</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Mon, 09 Dec 2024 19:23:46 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/javascript-and-its-core-concepts-a-beginners-guide-to-web-development-4ge3</link>
      <guid>https://dev.to/saqibjamil7866/javascript-and-its-core-concepts-a-beginners-guide-to-web-development-4ge3</guid>
      <description>&lt;h2&gt;
  
  
  What is JavaScript?
&lt;/h2&gt;

&lt;p&gt;JavaScript is a programming language that helps make websites interactive and dynamic. While HTML is used to structure the content of a webpage, and CSS is used to style it, JavaScript adds functionality and allows the webpage to respond to user actions.&lt;/p&gt;

&lt;p&gt;For example:&lt;br&gt;
 • You click a button, and something happens (like a menu opening).&lt;br&gt;
 • You scroll, and content appears dynamically.&lt;br&gt;
 • A form checks your input (like email validation) before submission.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Features of JavaScript (Simplified)&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Runs in the Browser: JavaScript runs directly in browsers like Chrome, Firefox, or Safari, so it works without installing anything extra.&lt;/li&gt;
&lt;li&gt;Dynamic: You can change a webpage (its content or appearance) without reloading it.&lt;/li&gt;
&lt;li&gt;Interactive: It responds to events like clicks, mouse movements, or key presses.&lt;/li&gt;
&lt;li&gt;Fast: It works quickly because it runs directly in the browser.&lt;/li&gt;
&lt;li&gt;Works Everywhere: JavaScript is used on both the browser (frontend) and servers (backend, using Node.js).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;How JavaScript Works (Simplified)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you visit a webpage:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;JavaScript Loads: The browser loads the JavaScript file alongside HTML and CSS.&lt;/li&gt;
&lt;li&gt;Executes Code: The browser’s JavaScript engine (like V8 in Chrome) runs the JavaScript line by line.&lt;/li&gt;
&lt;li&gt;Interacts with the webpage: JavaScript can access and modify parts of a web page, like:&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;Adding or removing elements.&lt;/li&gt;
&lt;li&gt;Styling parts of the page dynamically.&lt;/li&gt;
&lt;li&gt;Showing or hiding content based on user actions.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Examples to Make It Clear&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Changing Text on a Page&lt;br&gt;
 Let’s say you have a heading, and you want JavaScript to change its text.&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;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;JavaScript Example&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1 id="heading"&amp;gt;Welcome!&amp;lt;/h1&amp;gt;
  &amp;lt;script&amp;gt;
    // JavaScript changes the heading text
    document.getElementById("heading").innerText = "Hello, JavaScript!";
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The getElementById("heading") selects the 'h1' element.&lt;/li&gt;
&lt;li&gt;.innerText = "Hello, JavaScript!"; changes its text.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Button Click Example&lt;br&gt;
You can make a button do something when clicked.&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;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Click Example&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;button id="myButton"&amp;gt;Click Me&amp;lt;/button&amp;gt;
  &amp;lt;p id="message"&amp;gt;&amp;lt;/p&amp;gt;

  &amp;lt;script&amp;gt;
    const button = document.getElementById("myButton");
    button.addEventListener("click", function() {
      document.getElementById("message").innerText = "You clicked the button!";
    });
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What Happens:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The button listens for a “click.”&lt;/li&gt;
&lt;li&gt;  When clicked, JavaScript updates the &lt;p&gt; tag with a message.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Simple Calculator&lt;br&gt;
 Let’s create a calculator for adding two numbers.&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;!DOCTYPE html&amp;gt;
&amp;lt;html lang="en"&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Simple Calculator&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;input type="number" id="num1" placeholder="First number"&amp;gt;
  &amp;lt;input type="number" id="num2" placeholder="Second number"&amp;gt;
  &amp;lt;button id="addButton"&amp;gt;Add&amp;lt;/button&amp;gt;
  &amp;lt;p id="result"&amp;gt;&amp;lt;/p&amp;gt;

  &amp;lt;script&amp;gt;
    document.getElementById("addButton").addEventListener("click", function() {
      const num1 = parseFloat(document.getElementById("num1").value);
      const num2 = parseFloat(document.getElementById("num2").value);
      const sum = num1 + num2;
      document.getElementById("result").innerText = "Sum: " + sum;
    });
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How It Works:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The user enters numbers in two input fields.&lt;/li&gt;
&lt;li&gt;When the “Add” button is clicked, JavaScript calculates the sum and displays it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Key Concepts in JavaScript
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Variables:&lt;/strong&gt;&lt;br&gt;
 Variables store data that can be used later.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Variables?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Variables help you:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Store Information: Keep data in memory for later use.&lt;/li&gt;
&lt;li&gt;Reuse Values: Avoid rewriting the same value multiple times.&lt;/li&gt;
&lt;li&gt;Make Code Dynamic: Change variable values to alter program behavior.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let name = "John"; // Storing the value "John" in a variable called name
console.log(name); // Output: John
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Functions:&lt;/strong&gt;&lt;br&gt;
  In JavaScript, functions are reusable blocks of code designed to &lt;br&gt;
  perform a specific task. They allow you to write a piece of logic &lt;br&gt;
  once and use it multiple times, making your code more efficient and &lt;br&gt;
  organized.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greet(name) {
  return "Hello, " + name;
}

console.log(greet("Alice")); // Output: Hello, Alice
console.log(greet("Bob"));   // Output: Hello, Bob
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Events:&lt;/strong&gt;&lt;br&gt;
 Events in JavaScript are actions or occurrences that happen in the browser, often triggered by the user (e.g., clicking a button, typing in an input field, or resizing the window). JavaScript can “listen” for these events and perform specific actions in response. This is a key concept for creating interactive and dynamic web pages.&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;button id="myButton"&amp;gt;Click Me&amp;lt;/button&amp;gt;

&amp;lt;script&amp;gt;
  const button = document.getElementById("myButton");

  // Add an event listener for a click
  button.addEventListener("click", function () {
    alert("Button was clicked!");
  });

const div = document.getElementById("myDiv");
div.addEventListener("mouseover", function () {
  console.log("Mouse is over the div!");
});
div.addEventListener("mouseout", function () {
  console.log("Mouse left the div!");
});
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Conditions:&lt;/strong&gt;&lt;br&gt;
 In JavaScript, conditions are used to perform different actions &lt;br&gt;
 based on whether a specified condition evaluates to true or false. &lt;br&gt;
 This helps control the flow of your program, allowing it to make &lt;br&gt;
 decisions.&lt;/p&gt;

&lt;p&gt;Why Use Conditions?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Decision Making: Execute code based on specific situations.&lt;/li&gt;
&lt;li&gt;Dynamic Behavior: React to user input or external data.&lt;/li&gt;
&lt;li&gt;Error Handling: Handle unexpected cases gracefully.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let age = 20;

if (age &amp;gt;= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are not an adult.");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Loops:&lt;/strong&gt;&lt;br&gt;
 In JavaScript, loops are used to repeat a block of code multiple times. They are helpful when you want to perform an action or series of actions several times, such as iterating over items in an array or performing a task until a condition is met.&lt;/p&gt;

&lt;p&gt;There are several types of loops in JavaScript, each useful for different situations. Let’s go over the most common ones&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;for Loop:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The for loop is the most basic loop. It repeats a block of code for a specified number of times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Print numbers 1 to 5
for (let i = 1; i &amp;lt;= 5; i++) {
  console.log(i);
}
// Output: 1, 2, 3, 4, 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;while Loop:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The while loop runs as long as a specified condition is true. It checks the condition before each iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Print numbers 1 to 5 using a while loop
let i = 1;
while (i &amp;lt;= 5) {
  console.log(i);
  i++;  // Don't forget to increment i!
}
// Output: 1, 2, 3, 4, 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;do...while Loop:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The do...while loop is similar to the while loop, but it guarantees that the code will run at least once, even if the condition is false initially. It checks the condition after each iteration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Print numbers 1 to 5 using do...while loop
let i = 1;
do {
  console.log(i);
  i++;
} while (i &amp;lt;= 5);
// Output: 1, 2, 3, 4, 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;for...in Loop:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The for...in loop is used to iterate over the properties of an object (keys).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person = {
  name: "John",
  age: 30,
  city: "New York"
};

for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Output:
// name: John
// age: 30
// city: New York
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;for...of Loop:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The for...of loop is used to iterate over the values in an iterable object (like an array, string, or other iterable 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 numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
  console.log(number);
}
// Output: 1, 2, 3, 4, 5
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Where JavaScript is Used
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Frontend Development:
JavaScript frameworks like React, Angular, and Vue.js are used to 
build interactive websites.&lt;/li&gt;
&lt;li&gt;Backend Development:
Node.js allows JavaScript to run on servers, powering backend logic.&lt;/li&gt;
&lt;li&gt;APIs:
JavaScript fetches data from remote servers.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Why Learn JavaScript?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Widely Used: Almost every website uses JavaScript.&lt;/li&gt;
&lt;li&gt;Career Opportunities: Essential for web developers.&lt;/li&gt;
&lt;li&gt;Easy to Start: You only need a browser to write and test JavaScript.&lt;/li&gt;
&lt;/ul&gt;

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

&lt;p&gt;JavaScript is a beginner-friendly yet powerful programming language. &lt;br&gt;
 By practicing simple examples and understanding key concepts, you &lt;br&gt;
 can unlock the ability to create interactive and engaging web &lt;br&gt;
 applications!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>javascriptbasics</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 5</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Sat, 18 Nov 2023 11:56:24 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e"&gt;5 Javascript coding interview questions - Part 4&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6"&gt;5 Javascript coding interview questions - Part 6&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1: Explain Prototypal Inheritance in JavaScript.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; Prototypal inheritance is a programming concept that allows objects to inherit properties and methods from other objects. In JavaScript, all objects are created with a prototype object, which is an object that contains the properties and methods that the object will inherit.&lt;br&gt;
When you create a new object, you are essentially creating a copy of the prototype object. This means that the new object will have all of the same properties and methods as the prototype object. However, the new object also has its own set of properties and methods, which can be used to override or extend the properties and methods of the prototype object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Person(name) {
    this.name = name;
}
Person.prototype.greet = function() {
    return `Hello, my name is ${this.name}`;
};

function Student(name, grade) {
    this.name = name;
    this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);

const student = new Student('Alice', 'A');
console.log(student.greet()); //Hello, my name is Alice
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q2: Explain Asynchronous JavaScript and its use cases.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; Asynchronous JavaScript refers to the capability of executing code out of sequence, allowing other code to run while waiting for certain tasks to complete, such as network requests, file I/O, or timers. It's a fundamental feature in JavaScript, enabling non-blocking behavior and improving the responsiveness of web applications. Here are some key aspects and use cases of asynchronous JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;--Key Aspects--&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Non-blocking Execution:&lt;/strong&gt; Asynchronous operations don't halt the program's execution. Instead, they are initiated and allowed to complete independently while the main program continues to execute.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Callbacks:&lt;/strong&gt; Often used to handle asynchronous operations, callbacks are functions passed as arguments to be executed once the operation is complete. However, nesting callbacks can lead to callback hell or difficult-to-read code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Promises:&lt;/strong&gt; Introduced to address the callback hell issue, promises provide a cleaner way to handle asynchronous code. They represent the eventual completion or failure of an asynchronous operation and enable chaining, error handling, and more readable code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Async/Await:&lt;/strong&gt; A more modern approach introduced in ES2017, async functions and the await keyword simplify working with asynchronous code, making it look more synchronous and easier to reason about.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;--Use Cases--&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;HTTP Requests:&lt;/strong&gt; Fetching data from APIs or servers is one of the most common use cases for asynchronous JavaScript. It prevents the user interface from freezing while waiting for the server's response.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Timers and Intervals:&lt;/strong&gt; Setting timeouts or intervals for executing specific tasks asynchronously without blocking the main thread is another use case. For instance, updating the UI periodically or delaying certain actions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;File Operations:&lt;/strong&gt; Reading and writing files asynchronously in web applications or Node.js environments, allowing other operations to proceed while waiting for file I/O to complete.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Database Operations:&lt;/strong&gt; Asynchronous handling of database queries, especially in web servers, helps maintain responsiveness when dealing with databases.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Handling:&lt;/strong&gt; Asynchronous code is commonly used in event-driven programming, where events can occur at unpredictable times. For example, handling user interactions in web applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concurrency:&lt;/strong&gt; Running multiple tasks concurrently without blocking each other, such as parallel processing or executing multiple asynchronous operations simultaneously.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Start');
setTimeout(() =&amp;gt; {
    console.log('Delayed message');
}, 2000);
console.log('End');
// Outputs: Start, End, (after 2 seconds) Delayed message
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q3: What is the purpose of the async and await keywords in JavaScript?.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; The async and await keywords in JavaScript are used to handle asynchronous code in a more synchronous and cleaner manner, making it easier to write and maintain asynchronous code. These keywords were introduced in ECMAScript 2017 (ES8) to simplify working with promises and asynchronous operations&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;--Purpose--&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;1. Async Functions (async):&lt;/strong&gt; The async keyword is used to define an asynchronous function. It indicates that the function will always return a promise implicitly, even if the return value is not a promise.&lt;br&gt;
Async functions enable you to write code that behaves asynchronously, but they look and feel like synchronous code, making asynchronous code more readable and easier to understand.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Await Keyword:&lt;/strong&gt; The await keyword can only be used inside an async function. It is used to pause the execution of the async function until the promise is settled (resolved or rejected).&lt;br&gt;
It waits for the promise to resolve and returns the resolved value or throws an error if the promise is rejected.&lt;br&gt;
await can be applied to any promise-based function or operation that returns a promise (e.g., fetch, Promise.all, etc.).&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        return data;
    } catch (error) {
        console.error('Error fetching data:', error);
        throw error;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q4: What are Promises in JavaScript?.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; In JavaScript, a promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Promises are a powerful tool for handling asynchronous operations, as they allow you to write code in a more synchronous-style.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function asyncOperation() {
    return new Promise((resolve, reject) =&amp;gt; {
        setTimeout(() =&amp;gt; {
            resolve('Operation completed successfully!');
            // or reject(new Error('Operation failed!'));
        }, 2000);
    });
}
asyncOperation()
    .then(result =&amp;gt; console.log(result))
    .catch(error =&amp;gt; console.error(error));

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q5: What is Callbacks in javascript?.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ans:&lt;/strong&gt; A callback is a function that is passed as an argument to another function and is intended to be executed after a specific task or event completes. Callbacks are a fundamental concept in asynchronous programming and are widely used in JavaScript to handle events, perform asynchronous operations, and more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;--Benefits of Callbacks--&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Asynchronous Operations:&lt;/strong&gt; Callbacks are extensively used to handle asynchronous tasks, such as making AJAX requests, reading files, or executing timers. They allow you to define what should happen after an asynchronous operation completes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event Handling:&lt;/strong&gt; In event-driven programming, callbacks are used to respond to user actions or system events (e.g., click events, timers, HTTP requests). They allow you to define actions to be taken when an event occurs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Modularity and Reusability:&lt;/strong&gt; Callbacks promote modularity by allowing you to pass functions as arguments, making code more reusable. This enables the creation of higher-order functions that accept different callbacks to achieve different behaviors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error Handling:&lt;/strong&gt; Callbacks can handle errors in asynchronous operations by using error-first callbacks (commonly used in Node.js). This convention enables handling both success and error cases within the same callback function. &lt;br&gt;
Example&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;readFile('file.txt', function(err, data) {
    if (err) {
        console.error('Error reading file:', err);
        return;
    }
    console.log('File content:', data);
});

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Control Flow:&lt;/strong&gt; Callbacks facilitate control flow mechanisms like serial or parallel execution of asynchronous tasks.We can pass a function as parameter in a function and called it from where we want.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function logString(){
  console.log("This is callback function")
}

function mainFun(callbackFun){

  console.log("Main function called.");
  callbackFun();
}

mainFun(logString);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e"&gt;5 Javascript coding interview questions - Part 4&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-6-3di6"&gt;5 Javascript coding interview questions - Part 6&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 4</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Mon, 04 Sep 2023 13:01:43 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk"&gt;5 Javascript coding interview questions - Part 3&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd"&gt;5 Javascript coding interview questions - Part 5&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1:Implement a function to check if two arrays are equal.&lt;/strong&gt;&lt;br&gt;
Ans:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function arraysEqual(arr1, arr2) {
  return JSON.stringify(arr1) === JSON.stringify(arr2);
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q2: Implement a function to perform a deep comparison of two objects&lt;/strong&gt;&lt;br&gt;
Ans:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function deepEqual(obj1, obj2) {
  if (obj1 === obj2) return true;
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') return false;
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  if (keys1.length !== keys2.length) return false;
  for (const key of keys1) {
    if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) return false;
  }
  return true;
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q3: Write a function that generates all permutations of a string.&lt;/strong&gt;&lt;br&gt;
Ans:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function permuteString(str) {
  if (str.length &amp;lt;= 1) return [str];
  const permutations = [];
  for (let i = 0; i &amp;lt; str.length; i++) {
    const char = str[i];
    const rest = str.slice(0, i) + str.slice(i + 1);
    const subPermutations = permuteString(rest);
    for (const perm of subPermutations) {
      permutations.push(char + perm);
    }
  }
  return permutations;
}

// Example usage:
permuteString('test')
Output:
['test', 'tets', 'tset', 'tste', 'ttes', 'ttse', 'etst', 'etts', 'estt', 'estt', 'etts', 'etst', 'stet', 'stte', 'sett', 'sett', 'stte', 'stet', 'ttes', 'ttse', 'tets', 'test', 'tste', 'tset']

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q4: Write a function to find the maximum sum of a subarray in an array of integers .&lt;/strong&gt;&lt;br&gt;
Ans:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function maxSubarraySum(arr) {
  if (arr.length === 0) {
    return 0; // Handle empty array
  }

  let maxSum = arr[0];
  let currentMax = arr[0];

  for (let i = 1; i &amp;lt; arr.length; i++) {
    currentMax = Math.max(arr[i], currentMax + arr[i]);
    maxSum = Math.max(maxSum, currentMax);
  }

  return maxSum;
}

// Example usage:
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const maxSum = maxSubarraySum(arr);
console.log("Maximum sum of a subarray:", maxSum); // Output: 6

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Q5: Implement a function to find the longest substring without repeating characters.&lt;/strong&gt;&lt;br&gt;
Ans:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function longestSubstringWithoutRepeatingChars(str) {
  let longestSubstr = '';
  let currentSubstr = '';
  const charIndexMap = {};

  for (let i = 0; i &amp;lt; str.length; i++) {
    const char = str[i];

    if (charIndexMap[char] === undefined || charIndexMap[char] &amp;lt; i - currentSubstr.length) {
      // If the character is not in the current substring
      currentSubstr += char;
    } else {
      // If the character is in the current substring, update the current substring
      currentSubstr = str.slice(charIndexMap[char] + 1, i + 1);
    }

    charIndexMap[char] = i;

    if (currentSubstr.length &amp;gt; longestSubstr.length) {
      longestSubstr = currentSubstr;
    }
  }

  return longestSubstr;
}

// Example usage:
const inputString = "abcabcbb";
const longestSubstr = longestSubstringWithoutRepeatingChars(inputString);
console.log("Longest substring without repeating characters:", longestSubstr); // Output: "abc"

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

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;We maintain a currentSubstr variable to store the current substring being examined and a longestSubstr variable to store the longest substring found so far.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We use a charIndexMap object to keep track of the most recent index at which each character was seen.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We iterate through the input string, checking each character.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the character is not in the current substring (not in charIndexMap or its last occurrence is not within the current substring), we append it to currentSubstr.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the character is already in the current substring, we update currentSubstr by slicing it from the index after the last occurrence of that character to the current position.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We update the index of the character in charIndexMap.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If the length of currentSubstr becomes greater than the length of longestSubstr, we update longestSubstr.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;After the loop, longestSubstr will contain the longest substring without repeating characters.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk"&gt;5 Javascript coding interview questions - Part 3&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-5-2cjd"&gt;5 Javascript coding interview questions - Part 5&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 3</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Sun, 27 Aug 2023 18:35:20 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m"&gt;5 Javascript coding interview questions - Part 2&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e"&gt;5 Javascript coding interview questions - Part 4&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q1: Write a function that implements a simple version of Array.prototype.map(). Your function should take an array and a mapping function as inputs and return a new array with the results of applying the mapping function to each element of the input array.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here's an example of how the function should work:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const inputArray = [1, 2, 3, 4, 5];
const mappingFunction = (x) =&amp;gt; x * 2;

const outputArray = customMap(inputArray, mappingFunction);
console.log(outputArray); // Should output: [2, 4, 6, 8, 10]

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

&lt;/div&gt;



&lt;p&gt;Your task is to implement the customMap function using JavaScript.&lt;/p&gt;

&lt;p&gt;Answer:&lt;br&gt;
Here's a possible implementation of the customMap function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function customMap(arr, mapFunction) {
  const result = [];

  for (let i = 0; i &amp;lt; arr.length; i++) {
    result.push(mapFunction(arr[i], i, arr));
  }

  return result;
}

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

&lt;/div&gt;



&lt;p&gt;In this implementation, the customMap function takes an array (arr) and a mapping function (mapFunction) as parameters. It iterates through each element of the input array, applies the mapping function to each element, and adds the result to the result array. The mapping function can optionally take three parameters: the current element, the current index, and the original array. This implementation is a simplified version of how the map function works in JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q2: Can you explain what will be logged to the console in the following code snippet?&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;for (var i = 0; i &amp;lt; 5; i++) {
  setTimeout(() =&amp;gt; {
    console.log(i);
  }, 1000);
}

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Answer&lt;/strong&gt;: This code might not behave as one might initially expect. It seems like it should log the numbers 0 to 4 to the console, each after a delay of 1000 milliseconds (1 second). However, due to the asynchronous nature of JavaScript and closures, the output will actually be five instances of the number 5 logged to the console.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explanation:&lt;/strong&gt; When the loop runs, it schedules five setTimeout functions to execute after 1000 milliseconds, each with its own closure. However, by the time the first setTimeout function executes, the loop has already finished, and the value of i is 5. Since closures capture references to variables, not their values at the time of creation, all five closures share the same i variable.&lt;/p&gt;

&lt;p&gt;So, after 1000 milliseconds, each of the five functions reads the current value of i, which is 5, and logs it to the console. Hence, you will see:&lt;br&gt;
&lt;/p&gt;

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

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

&lt;/div&gt;



&lt;p&gt;To achieve the desired behavior of logging numbers 0 to 4 with the corresponding delays, you can use the IIFE (Immediately Invoked Function Expression) technique or ES6's let block scoping in the loop:&lt;/p&gt;

&lt;p&gt;Using IIFE:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (var i = 0; i &amp;lt; 5; i++) {
  (function(j) {
    setTimeout(() =&amp;gt; {
      console.log(j);
    }, 1000);
  })(i);
}

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

&lt;/div&gt;



&lt;p&gt;Using let block scoping:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for (let i = 0; i &amp;lt; 5; i++) {
  let j = i; // Create a new variable j in each iteration
  setTimeout(() =&amp;gt; {
    console.log(j);
  }, 1000);
}

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

&lt;/div&gt;



&lt;p&gt;These approaches will ensure that each closure captures a unique variable with the correct value for the corresponding iteration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q3: What is the output?&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;console.log(1 + '1' - 1);

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Answer:&lt;/strong&gt; The output will be 10. JavaScript coerces the addition operation to concatenate the strings initially, resulting in "11". Then, it performs a subtraction operation converting the string "11" to a number, resulting in 11 - 1 = 10.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Q4: What is a closure?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt; A closure refers to a combination of a function (or method) and its lexical environment, within which that function was declared. This allows the function to access variables and parameters from its outer scope even after that outer scope has finished execution.&lt;/p&gt;

&lt;p&gt;In simpler terms, a closure "closes" over the lexical scope (variables and methods) from its surrounding context, allowing it to maintain access to those even after the outer function has finished executing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunction(outerVariable) {
  // Inner function is a closure
  return function innerFunction(innerVariable) {
    console.log('Outer variable:', outerVariable);
    console.log('Inner variable:', innerVariable);
  };
}

const closureExample = outerFunction('Hello');
closureExample('World');  
// Output: Outer variable: Hello, Inner variable: World
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example &lt;strong&gt;innerFunction&lt;/strong&gt; maintain access to variable &lt;strong&gt;outerVariable&lt;/strong&gt; even after &lt;strong&gt;outerFunction&lt;/strong&gt; finished its execution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note: The lexical environment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The lexical environment in JavaScript is the set of variables and functions that are accessible to a function at any given point in time.&lt;br&gt;
The lexical environment is created when a function is declared, and it is destroyed when the function exits. The lexical environment of a function consists of the following:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;The function's own scope: This contains all of the variables and functions that are declared within the function.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The scope of the function's parent: This contains all of the variables and functions that are declared in the scope where the function is declared.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The global scope: This contains all of the variables and functions that are declared outside of any function.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Q5: What's the difference between null and undefined?&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Answer:&lt;/strong&gt; null represents the intentional absence of any value and is often used to indicate the absence of an object value. undefined typically signifies an uninitialized variable, missing property, or an empty value.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m"&gt;5 Javascript coding interview questions - Part 2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-4-65e"&gt;5 Javascript coding interview questions - Part 4&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 2</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Mon, 07 Aug 2023 08:25:33 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-1-2c4c"&gt;Javascript coding interview questions part 1&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk"&gt;Javascript coding interview questions part 3&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1: Two Sum - Given an array of integers nums and an integer target, return the indices of the two numbers that add up to the target.&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 twoSum(nums, target) {
  const numMap = new Map();

  for (let i = 0; i &amp;lt; nums.length; i++) {
    const complement = target - nums[i];
    if (numMap.has(complement)) {
      return [numMap.get(complement), i];
    }
    numMap.set(nums[i], i);
  }

  return null; // If no such pair exists
}

// Test
console.log(twoSum([2, 7, 11, 15], 9)); // Output: [0, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2: Find the Largest Number in an Array:&lt;br&gt;
Write a function that takes an array of numbers as input and returns the largest 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;function findLargestNumber(arr) {
  return Math.max(...arr);
}

// Test
console.log(findLargestNumber([3, 5, 1, 9, 2])); // Output: 9

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;3: Find the Longest Word&lt;br&gt;
Write a function that takes a sentence as input and returns the longest word in the sentence.&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 findLongestWord(sentence) {
  const words = sentence.split(' ');
  let longestWord = '';

  for (const word of words) {
    if (word.length &amp;gt; longestWord.length) {
      longestWord = word;
    }
  }

  return longestWord;
}

// Test
console.log(findLongestWord('The quick brown fox jumped over the lazy dog')); // Output: "jumped"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;4: Count Vowels&lt;br&gt;
Write a function that takes a string as input and returns the number of vowels (a, e, i, o, u) in the string.&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 countVowels(str) {
  const vowels = str.match(/[aeiou]/gi);
  return vowels ? vowels.length : 0;
}

// Test
console.log(countVowels('Hello World')); // Output: 3

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;5: Find Missing Number&lt;br&gt;
Write a function that takes an array containing integers from 1 to n (excluding one number) and returns the missing 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;function findMissingNumber(nums) {
  const n = nums.length + 1;
  const totalSum = (n * (n + 1)) / 2;
  const currentSum = nums.reduce((sum, num) =&amp;gt; sum + num, 0);
  return totalSum - currentSum;
}

// Test
console.log(findMissingNumber([1, 2, 4, 5])); // Output: 3

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

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-1-2c4c"&gt;Javascript coding interview questions part 1&lt;/a&gt;&lt;br&gt;
&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-3-3pk"&gt;Javascript coding interview questions part 3&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interview</category>
      <category>coding</category>
      <category>interviewquestion</category>
    </item>
    <item>
      <title>5 Javascript coding interview questions - Part 1</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Mon, 07 Aug 2023 07:37:07 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-1-2c4c</link>
      <guid>https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-1-2c4c</guid>
      <description>&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m"&gt;Javascript coding interview questions part 2&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Question 1: Reverse a String&lt;br&gt;
Write a function that takes a string as input and returns its reverse.&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 reverseString(str) {
  return str.split('').reverse().join('');
}

// Test
console.log(reverseString('hello')); // Output: "olleh"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Question 2: Check for Palindrome&lt;br&gt;
Write a function that checks if a given string is a palindrome (reads the same forwards and backward).&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(str) {
  const reversedStr = str.split('').reverse().join('');
  return str === reversedStr;
}

// Test
console.log(isPalindrome('racecar')); // Output: true
console.log(isPalindrome('hello'));   // Output: false

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Question 3: Find the First Non-Repeated Character&lt;br&gt;
Write a function that takes a string as input and returns the first non-repeated character in the string.&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 firstNonRepeatedChar(str) {
  const charCount = {};

  for (const char of str) {
    charCount[char] = (charCount[char] || 0) + 1;
  }

  for (const char of str) {
    if (charCount[char] === 1) {
      return char;
    }
  }

  return null; // If all characters are repeated
}

// Test
console.log(firstNonRepeatedChar('abacdbe')); // Output: "c"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Question 4: FizzBuzz&lt;br&gt;
Write a function that prints the numbers from 1 to n. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz" instead of the number. For numbers that are multiples of both 3 and 5, print "FizzBuzz".&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 fizzBuzz(n) {
  for (let i = 1; i &amp;lt;= n; i++) {
    let output = '';
    if (i % 3 === 0) {
      output += 'Fizz';
    }
    if (i % 5 === 0) {
      output += 'Buzz';
    }
    console.log(output || i);
  }
}

// Test
fizzBuzz(15); // Output: 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Question 5: Remove Duplicates from an Array&lt;br&gt;
Write a function that takes an array as input and returns a new array with duplicates removed.&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 removeDuplicates(arr) {
  return [...new Set(arr)];
}

// Test
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5])); // Output: [1, 2, 3, 4, 5]

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

&lt;/div&gt;



&lt;p&gt;These are just a few examples of JavaScript coding interview questions. Remember to practice and understand the concepts thoroughly to perform well in technical interviews.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://dev.to/saqibjamil7866/5-javascript-coding-interview-questions-part-2-5h1m"&gt;Javascript coding interview questions part 2&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>interviewquestion</category>
      <category>coding</category>
      <category>technicalquestion</category>
    </item>
    <item>
      <title>Python Machine Learning - Handwritten Digit Recognition with TensorFlow</title>
      <dc:creator>Saqib Jamil</dc:creator>
      <pubDate>Sun, 06 Aug 2023 19:48:41 +0000</pubDate>
      <link>https://dev.to/saqibjamil7866/python-machine-learning-handwritten-digit-recognition-with-tensorflow-dff</link>
      <guid>https://dev.to/saqibjamil7866/python-machine-learning-handwritten-digit-recognition-with-tensorflow-dff</guid>
      <description>&lt;p&gt;Introduction:&lt;br&gt;
Machine learning has witnessed remarkable advancements in recent years, enabling a wide range of applications. One such fascinating application is Handwritten Digit Recognition. In this article, we will explore how to build a digit recognition model using TensorFlow, a popular deep learning library in Python. We will create a neural network that can identify handwritten digits from the famous MNIST dataset.&lt;/p&gt;

&lt;p&gt;Prerequisites:&lt;br&gt;
To follow along with this tutorial, you should have a basic understanding of Python programming and some familiarity with machine learning concepts. Additionally, ensure that you have TensorFlow and its dependencies installed on your system.&lt;/p&gt;

&lt;p&gt;The MNIST Dataset:&lt;br&gt;
The MNIST dataset is a classic dataset widely used for training and testing machine learning models. It consists of 28x28 grayscale images of handwritten digits (0 to 9) and their corresponding labels. The dataset contains 60,000 training images and 10,000 testing images.&lt;/p&gt;

&lt;p&gt;Getting Started:&lt;br&gt;
First, let’s install TensorFlow and numpy if you haven’t already:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install tensorflow
pip install numpy

//or  If you are using Python 3
pip3 install tensorflow
pip3 install numpy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;TensorFlow and NumPy are both popular and powerful libraries in Python, but they serve different purposes in the field of data science and machine learning.&lt;/p&gt;

&lt;p&gt;TensorFlow: TensorFlow is an open-source machine learning library developed by the Google Brain team. It is primarily used for building and training machine learning and deep learning models. TensorFlow allows developers to define and train complex mathematical computations involving multi-dimensional arrays, known as tensors. It provides a flexible and efficient ecosystem for various machine learning tasks, including neural networks, natural language processing, computer vision, and more.&lt;/p&gt;

&lt;p&gt;NumPy: NumPy is a fundamental library for numerical computing in Python. It stands for “Numerical Python” and provides support for large, multi-dimensional arrays and matrices, along with a collection of high-level mathematical functions to operate on these arrays. NumPy is the foundation of many other scientific computing libraries in Python, including pandas, SciPy, and scikit-learn.&lt;/p&gt;

&lt;p&gt;Import the required libraries:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

//or you can use it manually in the code without importing like this

tf.tensorflow.keras.datasets.mnist
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Load and Preprocess the Data:&lt;br&gt;
We will load the MNIST dataset and preprocess the data by normalizing the pixel values to a range between 0 and 1:&lt;/p&gt;

&lt;p&gt;Load the MNIST dataset&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

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

&lt;/div&gt;



&lt;p&gt;Normalize the pixel values to [0, 1]&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;train_images, test_images = train_images / 255.0, test_images / 255.0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Building the Neural Network:&lt;br&gt;
Now, let’s create a simple neural network using TensorFlow’s Sequential API. Our model will have one input layer, one hidden layer, and one output layer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model = Sequential([
    Flatten(input_shape=(28, 28)),  # Flatten the 28x28 input images to a 1D array
    Dense(128, activation='relu'),   # Hidden layer with 128 neurons and ReLU activation
    Dense(10, activation='softmax')  # Output layer with 10 neurons and softmax activation
])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Compile the Model:&lt;br&gt;
Before training the model, we need to compile it by specifying the optimizer, loss function, and metrics:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Training the Model:&lt;br&gt;
It’s time to train our digit recognition model on the training data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model.fit(train_images, train_labels, epochs=5, batch_size=32)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Evaluating the Model:&lt;br&gt;
Once the model is trained, we can evaluate its performance on the test data:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_loss, test_accuracy = model.evaluate(test_images, test_labels)
print(f"Test Accuracy: {test_accuracy}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Making Predictions:&lt;br&gt;
Finally, we can use our trained model to make predictions on new images:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import numpy as np
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Choose a random test image&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;random_test_image = np.expand_dims(test_images[0], axis=0)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Make a prediction on the random test image&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;prediction = model.predict(random_test_image)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Get the predicted digit&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;predicted_digit = np.argmax(prediction)

print(f"Predicted Digit: {predicted_digit}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Conclusion:&lt;br&gt;
In this article, we have explored how to build a digit recognition model using TensorFlow in Python. We leveraged the MNIST dataset to train and test the model’s accuracy. Handwritten digit recognition is just one example of the endless possibilities of machine learning. With TensorFlow’s capabilities, we can develop sophisticated models to tackle a wide range of real-world challenges.&lt;/p&gt;

&lt;p&gt;Machine learning opens up a world of opportunities for automation and pattern recognition. As you continue your journey in the field of AI and machine learning, keep exploring different datasets, architectures, and optimization techniques to enhance your models’ performance. Happy coding!&lt;/p&gt;

&lt;p&gt;(Note: This article provides a basic example of digit recognition using TensorFlow. For real-world applications, consider using more complex models and larger datasets for better accuracy.)&lt;/p&gt;

</description>
      <category>python</category>
      <category>machinelearning</category>
      <category>tensorflow</category>
      <category>digitrecognition</category>
    </item>
  </channel>
</rss>
