<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ipek on Medium]]></title>
        <description><![CDATA[Stories by Ipek on Medium]]></description>
        <link>https://medium.com/@basipek57?source=rss-1c8aa0a4fdee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Ipek on Medium</title>
            <link>https://medium.com/@basipek57?source=rss-1c8aa0a4fdee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:03:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@basipek57/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What is JavaScript?]]></title>
            <link>https://medium.com/@basipek57/what-is-javascript-3351e76d9e82?source=rss-1c8aa0a4fdee------2</link>
            <guid isPermaLink="false">https://medium.com/p/3351e76d9e82</guid>
            <category><![CDATA[basics-of-javascript]]></category>
            <dc:creator><![CDATA[Ipek]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 08:28:13 GMT</pubDate>
            <atom:updated>2025-01-31T08:28:13.478Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript(JS) is a high-level, interpreted programming language that allows developers to create interactive and dynamic web applications. It is one of the core technologies of the web, alongside HTML &amp; CSS. JavaScript;</p><p>Can be used almost everywhere — Powers over 97% of websites.</p><p>Works on browsers and servers — Frontend (React, Vue) &amp; Backend (Node.js).</p><p>Interacts with DOM — Enables dynamic updates without refreshing the page.</p><p>Has huge ecosystem — Libraries like <em>jQuery</em>, <em>React</em>, <em>Angular</em>, and <em>Vue</em> make development easier.</p><p><strong>JavaScript’s Use Cases:</strong></p><p><strong>Frontend Development</strong> — DOM manipulation, animations, event handling.<br> <strong>Backend Development</strong> — Using Node.js for APIs, databases, and servers.<br> <strong>Mobile App Development</strong> — Using React Native, Ionic, or NativeScript.<br> <strong>Game Development</strong> — Using Phaser.js or Three.js for browser-based games.<br> <strong>AI &amp; ML with JavaScript</strong> — TensorFlow.js for machine learning models in the browser.</p><p><strong>Key Features of JavaScript:</strong></p><ul><li><strong>Client-Side Execution :</strong> Runs directly in the browser without requiring compilation.</li><li><strong>Dynamically Typed :</strong> No need to explicitly declare variable types.</li><li><strong>Event-Driven &amp; Asynchronous :</strong> Supports event handling, promises, and async/await.</li><li><strong>Multi-Paradigm :</strong> Can be used for functional, object-oriented, and imperative programming.</li><li><strong>Cross-Platform :</strong> Works on web browsers, servers (Node.js), mobile apps, and even IoT devices.</li></ul><p><strong>Differences Between “var”, “let” and “const” in JavaScript:</strong></p><p><strong>“var” declaration:</strong></p><p>Function-Scoped : A var variable is accessible anywhere within the function it is declared in.</p><pre>function example() {<br>     if (true) {<br>     var x = 10; <br>     }<br>console.log(x); // Output: 10 (Still accessible outside the block)<br>}<br>example();</pre><p>Reassignment and Redeclaration : A var variable can be reassigned and redeclared.</p><p><strong>NOTE:</strong> Redeclaring a variable using var can lead to unintended bugs.</p><pre>var a = 5;<br>var a = 10; // No error<br>console.log(a); // Output: 10</pre><p><strong>“let” declaration:</strong></p><p>Block-Scoped: A let variable is only accessible within the block {} where it was declared.</p><pre>function example() {<br>       if (true) {<br>       let y = 20; <br>      }<br>console.log(y); // Error: y is not defined<br>}<br>example();</pre><p>Reassignment : A let variable can be reassigned but not declared. Use “let” when a variable’s value needs to change.</p><pre>let b = 5;<br>b = 10; //  Allowed<br>let b = 15; //  Error: Identifier &#39;b&#39; has already been declared</pre><p><strong>“const” declaration:</strong></p><p>Block-Scoped: A const variable is only accessible within the block {} where it was declared.</p><pre>if (true) {<br>    const apiKey = &quot;12345-ABCDE&quot;;<br>    console.log(apiKey); // Output: 12345-ABCDE<br>}<br>console.log(apiKey); //  Error: apiKey is not defined (outside the block)</pre><p>Unchangeable: A const variable can’t be reassigned or redeclared.</p><pre>const c = 5;<br>c = 10; //  Error: Assignment to constant variable</pre><p><strong>What are JavaScript Data Types?</strong></p><p>JavaScript has two main categories of data types:</p><ol><li><strong>Primitive Data Types — </strong>Immutable values (stored directly in memory):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*q0JNLO_lpqz8dKoQLExfYA.png" /></figure><p><strong>2.Non-Primitive (Reference) Data Types — </strong>Complex objects stored as references<strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*mlnkdR1NKX00oYyac2BnFw.png" /></figure><p><strong>Special Cases and Type Coercion:</strong></p><p>JS dynamically converts types when necessary.</p><pre>console.log(5 + &quot;5&quot; ); // Output: &quot;55&quot; (number + string → string)<br>console.log( &quot;5&quot; - 2); // Output: 3 (string - number → number)<br>console.log( true + 1); // Output: 2 (true → 1)</pre><p><strong>What is Closure in JavaScript?</strong></p><p>A closure in JavaScript is a function that remembers the variables from its outer scope, even after the outer function has finished execution. It allows functions to remember the environment in which they were created.</p><pre>function createCounter() {<br>    let count = 0; // Private variable (hidden from global scope)<br>    return function() {<br>           count++;<br>           console.log(`Current count: ${count}`);<br>    };<br>}<br>const counter = createCounter();<br>counter(); // Output: Current count: 1<br>counter(); // Output: Current count: 2<br>counter(); // Output: Current count: 3</pre><p><strong>-Closures and Function Factories:</strong></p><p>Closures allow you to create customized functions dynamically.</p><pre>function multiplier(factor) {<br>      return function (num) {<br>          return num * factor;<br>      };<br>}<br>const double = multiplier(2);<br>console.log(double(5)); // Output: 10<br>const triple = multiplier(3);<br>console.log(triple(5)); // Output: 15</pre><p><strong>-Closures in Event Listeners:</strong></p><p>Closures help retain state in asynchronous code.</p><pre>function setupEventListener() {<br>     let clicks = 0;<br>     document.getElementById(&quot;btn&quot;).addEventListener(&quot;click&quot;, function() {<br>   clicks++;<br>   console.log(`Button clicked ${clicks} times`);<br>        });<br>}<br>setupEventListener(); //clicks remain in memory even after setupEventListener() has executed.</pre><p><strong>-Closures in setTimeout():</strong></p><p>Closures allow delayed execution while preserving variables.</p><pre>function delayedMessage(msg, delay) {<br>      setTimeout(function() {<br>           console.log(msg);<br>      }, delay);<br>}<br>delayedMessage(&quot;Hello after 2 seconds!&quot;, 2000); // Output (after 2 sec): Hello after 2 seconds!</pre><p><strong>What is Hoisting in JavaScript?</strong></p><p>Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope before execution. This means you can use variables and functions before they are declared in the code.</p><p><strong>NOTE:</strong> Only declarations are hoisted, not initializations.</p><pre>console.log(a); // Output: undefined (Hoisted but not assigned)<br>var a; // Declaration hoisted<br>console.log(a); // undefined<br>a = 10; // Assignment remains in place<br>console.log(a); // Output: 10</pre><p><strong>Hoisting with Functions: </strong>Function declarations are fully hoisted, so you can call a function before defining it.</p><pre>sayHello(); // Output: Hello!<br>function sayHello() {<br>    console.log(&quot;Hello!&quot;);<br>}</pre><p>But function expressions are not hoisted:</p><pre>console.log(sum(5, 10)); //  Error: Cannot access &#39;sum&#39; before initialization<br>const sum = function(a, b) {<br>    return a + b;<br>};</pre><p><strong>Differences Between “==” and “===” Operator:</strong></p><p>In JS, both loose equality (==) and strict equality (===) are used for comparison, but they behave differently in terms of type coercion.</p><p><strong>-Loose Equality (==):</strong></p><p>Checks only values but not data types.</p><p>Performs type conversion (coercion) if the types are different.</p><pre>console.log(5 == &quot;5&quot;); // Output: true (String is converted to Number)<br>console.log(0 == false); // Output: true (Boolean is converted to Number)<br>console.log(null == undefined); // Output: true (Special case)</pre><p><strong>-Strict Equality (===):</strong></p><p>Checks both value and type.</p><p>No type conversion is performed.</p><pre>console.log(5 === &quot;5&quot;); // Output: false (Different types)<br>console.log(0 === false); // Output: false (Number vs Boolean)<br>console.log(null === undefined); // Output: false (Different types)</pre><p><strong>NOTE: </strong>Special Cases;</p><pre>console.log(&quot;&quot; == 0); //  true (&quot;&quot; converts to 0)<br>console.log([ ] == 0); // true ([ ] converts to &quot; &quot;)<br>console.log([ ] == &quot;&quot;); // true (Both convert to &quot; &quot;)<br>console.log([ ] == ![ ]); // true (Weird case: ! [ ] is false, [ ] converts to false)</pre><p><strong>What are JavaScript Promises?</strong></p><p>A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation. It allows handling asynchronous tasks in a more structured and readable way compared to callbacks. Promises help deal with asynchronous operations like fetching data, reading files, or making API calls.</p><p>A promise can be in one of the following states:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*NCVcFStbvP5tECHccAbfNA.png" /></figure><p>A promise takes a callback function with two parameters: resolve(for success) and reject(for failure).</p><pre>const myPromise = new Promise((resolve, reject) =&gt; {<br>    let success = true; // Change this to false to simulate rejection<br>    if (success) {<br>        resolve(&quot;Operation successful!&quot;); // moves the promise to Fulfilled<br>    } else {<br>        reject(&quot;Something went wrong!&quot;); // // moves the promise to Rejected<br>    }<br>});<br>console.log(myPromise); // Output: Promise { &lt;pending&gt; }</pre><p><strong>Handling Promises with .then() and .catch():</strong></p><p>Once a Promise is fulfilled or rejected, you can handle the result using .then() and .catch().</p><pre>myPromise<br>    .then((message) =&gt; {<br>        console.log(&quot;Success:&quot;, message); // Output: Success: Operation successful!<br>    })<br>    .catch((error) =&gt; {<br>        console.log(&quot;Error:&quot;, error); // Output: Error: Something went wrong!<br>    });</pre><p><strong>Using async/await (Simplified Promises):</strong></p><p>Instead of using .then() and .catch(), you can use async/await for a cleaner syntax.</p><pre>const fetchData = () =&gt; {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; resolve(&quot;Fetched Data&quot;), 2000);<br>    });<br>};<br>async function getData() {<br>    try {<br>        const result = await fetchData();<br>        console.log(result); // Output: Fetched Data<br>    } catch (error) {<br>        console.log(&quot;Error:&quot;, error);<br>    }<br>}<br>getData();</pre><p><strong>Promise.all( ) (Run Multiple Promises in Parallel):</strong></p><p>If you want to run multiple promises at the same time, use Promise.all().</p><pre>const p1 = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;One&quot;), 1000));<br>const p2 = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Two&quot;), 2000));<br>const p3 = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Three&quot;), 3000));<br>Promise.all([p1, p2, p3]).then((results) =&gt; console.log(results));<br>// Output after 3s: [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;]</pre><p><strong>Promise.race( ) (Return First Resolved Promise):</strong></p><p>If you want the first resolved promise, use Promise.race().</p><pre>Promise.race([p1, p2, p3]).then((result) =&gt; console.log(result));<br>// Output: &quot;One&quot; (whichever resolves first)</pre><p><strong>What is the “event” Loop in JavaScript?</strong></p><p>The Event Loop in JavaScript is a mechanism that allows asynchronous operations to be handled efficiently. It ensures non-blocking execution by continuously checking and executing tasks in different queues.</p><p>-JavaScript is<strong> single-threaded</strong>, meaning it can only execute one task at a time. The event loop helps manage multiple tasks asynchronously without blocking the execution of other code.</p><p><strong>How does the “event” loop work?</strong></p><p>1. Call Stack: Synchronous code execution. (console.log(), loops, calculations)</p><p>2. Web APIs: Timers, DOM events, HTTP requests, etc. (setTimeout(), fetch(), DOM events)</p><p>3. Callback Queue: Pending asynchronous tasks (Promises, MutationObserver)</p><p>4. Microtask Queue: Promises, MutationObserver (setTimeout(), setInterval(), event listeners)</p><p><strong>Step by Step Execution:</strong></p><pre>console.log(&quot;Start&quot;); //Output: Start<br>setTimeout(() =&gt; console.log(&quot;Timeout&quot;), 0); //Output: End<br>Promise.resolve().then(() =&gt; console.log(&quot;Promise&quot;)); //Output: Promise<br>console.log(&quot;End&quot;); //Output: Timeout</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*Im-JjvRnBgivh2T9BlWYrQ.png" /></figure><p><strong>setTimeout( ) vs Promises:</strong></p><pre>setTimeout(() =&gt; console.log(&quot;Timeout&quot;), 0);                                            <br>Promise.resolve().then(() =&gt; console.log(&quot;Promise&quot;));                  <br>console.log(&quot;Hello&quot;);  //setTimeout() runs after Promises!  </pre><p><strong>What is the difference between “null” and “undefined” in JS?</strong></p><p>If a variable is declared but not assigned, it is undefined by default.</p><pre>let x;<br>console.log(x); // Output: undefined<br>          If you want to intentionally indicate &quot;no value,&quot; assign null.<br>let y = null;<br>console.log(y); // Output: null</pre><p>Mixed example:</p><pre>function checkValue(value) {<br>    if (value === null) {<br>        console.log(&quot;Value is explicitly set to null.&quot;);<br>    } else if (value === undefined) {<br>        console.log(&quot;Value is undefined (not assigned).&quot;);<br>    } else {<br>        console.log(&quot;Value exists:&quot;, value);<br>    }<br>}<br>let a;<br>let b = null;<br>let c = &quot;Hello&quot;;<br><br>checkValue(a); // Output: Value is undefined (not assigned).<br>checkValue(b); // Output: Value is explicitly set to null.<br>checkValue(c); // Output: Value exists: Hello.</pre><p><strong>What is Prototypal Inheritance in JavaScript?</strong></p><p>Prototypal inheritance in JS is a feature where objects inherit properties and methods from other objects through a special hidden property called [[Prototype]].</p><ul><li>Instead of copying properties from one object to another (like classical inheritance in Java or C++), JavaScript allows objects to link to other objects dynamically.</li></ul><p>Every JavaScript object has an internal hidden property called [[Prototype]], which can be accessed using <strong>Object.getPrototypeOf(obj)</strong> or <strong>__proto__ </strong>.</p><ol><li>When you try to access a property on an object:</li></ol><ul><li>JavaScript first checks if the object has the property.</li><li>If not found, it looks up the prototype chain until it finds the property.</li><li>If it doesn’t exist in any prototype, it returns undefined</li></ul><p>Prototype Chain Example:</p><pre>const animal = {<br>    makeSound: function() {<br>        console.log(&quot;Some generic sound...&quot;);<br>    }<br>};<br><br>const dog = Object.create(animal); // dog inherits from animal<br>dog.bark = function() {<br>    console.log(&quot;Woof! Woof!&quot;);<br>};<br><br>dog.makeSound(); // Output: Some generic sound...<br>dog.bark();      //  Output: Woof! Woof!<br><br>console.log(Object.getPrototypeOf(dog) === animal); // Output: true</pre><p><strong>Constructor Functions for Inheritance:</strong></p><p>Before ES6 classes, JavaScript used constructor functions for inheritance.</p><pre>function Person(name, age) {<br>    this.name = name;<br>    this.age = age;<br>}<br><br>Person.prototype.greet = function() {<br>    console.log(`Hello, my name is ${this.name}`);<br>};<br><br>const person1 = new Person(&quot;Ipek&quot;, 25);<br>person1.greet(); //  Output: Hello, my name is Ipek<br><br>console.log(person1.__proto__ === Person.prototype); //  Output: true</pre><p><strong>Using ES6 Classes(Modern Approach):</strong></p><p>With ES6, class syntax provides a cleaner way to work with inheritance.</p><pre>class Animal {<br>    constructor(name) {<br>        this.name = name;<br>    }<br><br>    makeSound() {<br>        console.log(&quot;Some generic sound...&quot;);<br>    }<br>}<br><br>class Dog extends Animal {<br>    bark() {<br>        console.log(&quot;Woof! Woof!&quot;);<br>    }<br>}<br><br>const myDog = new Dog(&quot;Buddy&quot;);<br>myDog.makeSound(); // Output: Some generic sound...<br>myDog.bark();      // Output: Woof! Woof!<br><br>console.log(myDog instanceof Dog);     //  true<br>console.log(myDog instanceof Animal);  //  true</pre><p><strong>Overriding Inherited Methods:</strong></p><p>If a child object has a method with the same name as a prototype method, it overrides the inherited method.</p><pre>class Cat extends Animal {<br>    makeSound() {<br>        console.log(&quot;Meow! Meow!&quot;);<br>    }<br>}<br><br>const myCat = new Cat(&quot;Whiskers&quot;);<br>myCat.makeSound(); // Output: Meow! Meow! (Overridden method)</pre><p><strong>Difference Between Synchronous and Asynchronous Code in JS</strong></p><p><strong>Synchronous Code:</strong> Executes line by line, blocking further execution until the current task is completed. Each line waits for the previous one to complete before executing.</p><pre>console.log(&quot;Step 1&quot;);<br>console.log(&quot;Step 2&quot;);<br>console.log(&quot;Step 3&quot;);</pre><p><strong>Asynchronous Code:</strong> Allows execution to continue while waiting for an operation to complete. That’s useful for fetching data from APIs, reading files, running timers(setTimeout) and handling events(click, keydown).</p><pre>console.log(&quot;Step 1&quot;);<br>setTimeout(() =&gt; {<br>    console.log(&quot;Step 2 (Delayed)&quot;); //Step 3 runs before Step 2<br>}, 2000);<br>console.log(&quot;Step 3&quot;);</pre><p><strong>What is “this” keyword in JavaScript?</strong></p><p>The “this” keyword in JavaScript refers to the object that is executing the function. Its value depends on where and how the function is called.</p><ul><li>In the global scope, this refers to the <strong>global object</strong> (window in browsers, global in Node.js).</li></ul><pre>console.log(this); // Output (Browser): Window {...}</pre><ul><li>In strict mode <strong>(“use strict”;)</strong>, this is undefined in the global scope.</li></ul><pre>&quot;use strict&quot;;<br>console.log(this); // Output: undefined</pre><p><strong>“this” Inside an Object Method:</strong></p><p>When a function is a method of an object, this refers to the object itself.</p><pre>const person = {<br>    name: &quot;Ipek&quot;,<br>    greet: function () {<br>        console.log(`Hello, my name is ${this.name}`);<br>    }<br>};<br>person.greet(); //  Output: Hello, my name is Ipek</pre><p><strong>“this” in Arrow Functions (Lexical “this”):</strong></p><p>Arrow functions <strong>do not have their own this</strong>. Instead, they inherit this from the surrounding lexical scope.</p><pre>const person = {<br>    name: &quot;Bob&quot;,<br>    greet: function () {<br>        const arrowFunc = () =&gt; {<br>            console.log(this.name);<br>        };<br>        arrowFunc();<br>    }<br>};<br>person.greet(); //  Output: Bob</pre><p><strong>“this” in Constructor Functions:</strong></p><p>In a constructor function, this refers to the newly created object.</p><pre>function Person(name) {<br>    this.name = name;<br>}<br>const user = new Person(&quot;Charlie&quot;);<br>console.log(user.name); // Output: Charlie</pre><p><strong>“this” in ES6 Classes:</strong></p><p>In a class, this refers to the instance of the class.</p><pre>class Car {<br>    constructor(brand) {<br>        this.brand = brand;<br>    }<br>    showBrand() {<br>        console.log(`Car brand: ${this.brand}`);<br>    }<br>}<br>const myCar = new Car(&quot;Toyota&quot;);<br>myCar.showBrand(); // Output: Car brand: Toyota</pre><p><strong>“this” in Event Listeners:</strong></p><p>In event listeners, this refers to the element that triggered the event.</p><pre>document.getElementById(&quot;btn&quot;).addEventListener(&quot;click&quot;, function() {<br>    console.log(this); // Output: The button element<br>});</pre><p><strong>Explicitly Binding “this”:</strong></p><p>JavaScript provides methods to explicitly bind “this”:</p><p>1. bind(): Creates a new function with a specific this.</p><p>2. call(): Calls a function with a specific this.</p><p>3. apply(): Similar to call(), but takes arguments as an array.</p><pre>const user = {<br>    name: &quot;Charlie&quot;,<br>};<br><br>function introduce(city, country) {<br>    console.log(`Hi, I&#39;m ${this.name} from ${city}, ${country}.`);<br>}<br><br>// Using call<br>introduce.call(user, &quot;Paris&quot;, &quot;France&quot;);<br>// Output: Hi, I&#39;m Charlie from Paris, France.<br><br>// Using apply<br>introduce.apply(user, [&quot;Tokyo&quot;, &quot;Japan&quot;]);<br>// Output: Hi, I&#39;m Charlie from Tokyo, Japan.<br><br>// Using bind (returns a new function)<br>const boundIntro = introduce.bind(user, &quot;Sydney&quot;, &quot;Australia&quot;);<br>boundIntro();<br>// Output: Hi, I&#39;m Charlie from Sydney, Australia.</pre><p><strong>What are JavaScript Modules?</strong></p><p>JavaScript modules are a way to organize and reuse code by splitting JavaScript into separate files. They help keep the codebase clean, manageable and reusable.</p><p><strong>Why use modules?</strong></p><p><strong>1.</strong> <strong>Encapsulation:</strong> Keeps variables/functions private unless explicitly exported.</p><p><strong>2.</strong> <strong>Reusability:</strong> Code can be reused across multiple files.</p><p><strong>3.</strong> <strong>Maintainability:</strong> Keeps code clean and structured.</p><p><strong>4.</strong> <strong>Avoids Global Scope Pollution:</strong> Prevents name conflicts.</p><p>We talked about export ,import and curly braces ( { } ). That’s why I want to continue my report with <strong>“as alias”</strong>:</p><p>If you want to import everything from a module:</p><pre>import * as MathUtils from &#39;./math.js&#39;;<br>console.log(MathUtils.add(2, 3)); //  Output: 5<br>console.log(MathUtils.PI); //  Output: 3.14159</pre><p>-This imports all exports under the namespace “MathUtils”.</p><p><strong>Using Modules in HTML(Browser):</strong></p><p>To use ES6 modules in the browser, add <strong>type=”module”</strong> in your script tag. Without type=”module”, the browser won’t recognize import/export.</p><pre>&lt;script type=&quot;module&quot; src=&quot;app.js&quot;&gt;&lt;/script&gt; </pre><p><strong>CommonJS (Node.js Modules):</strong></p><p>Before ES6 modules, Node.js used CommonJS syntax (require and module.exports).</p><p><em>Exporting example (CommonJS):</em></p><pre>// math.js<br>module.exports = {<br>    add: (a, b) =&gt; a + b,<br>    PI: 3.14159<br>};</pre><p><em>Importing example (CommonJS):</em></p><pre>const math = require(&#39;./math.js&#39;);<br>console.log(math.add(2, 3)); //  Output: 5</pre><p><strong>What is DOM in JavaScript?</strong></p><p>The DOM(Document Object Model) is a programming interface that represents the structure of an HTML or XML documents as a tree-like structure. JavaScript can use the DOM to manipulate HTML elements dynamically(change content, styles, structure etc.)</p><p><strong>How to DOM Works?</strong></p><p>When a page loads:</p><p>1. The browser parses HTML and creates a DOM tree.</p><p>2. The DOM tree represents the structure of the webpage.</p><p>3. JavaScript can use the DOM to select, modify and manipulate elements.</p><p><strong>HTML Code:</strong></p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;My Page&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1 id=&quot;title&quot;&gt;Hello, World!&lt;/h1&gt;<br>    &lt;p class=&quot;description&quot;&gt;This is a paragraph.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>DOM Representation:</strong></p><p>JavaScript can access and modify any element in this tree.</p><pre>Document<br> |---html<br> │    |--- head<br> │    │    |--- title<br> │    |---body<br> │         |--- h1 (id=&quot;title&quot;)<br> │         |---p (class=&quot;description&quot;)</pre><p><strong>Selecting DOM Elements:</strong></p><p><em>getElementById() : Select by ID</em></p><pre>const heading = document.getElementById(&quot;title&quot;);<br>console.log(heading.textContent); // Output: Hello, World!</pre><p><em>getElementsByClassName() : Select by Class</em></p><pre>const paragraphs = document.getElementsByClassName(&quot;description&quot;);<br>console.log(paragraphs[0].textContent); // Output: This is a paragraph.</pre><p><em>getElementsByTagName() : Select by Tag</em></p><pre>const allParagraphs = document.getElementsByTagName(&quot;p&quot;);<br>console.log(allParagraphs.length); // Output: Number of `&lt;p&gt;` elements</pre><p><em>querySelector() : Select First Matching Element</em></p><pre>const firstParagraph = document.querySelector(&quot;.description&quot;);<br>console.log(firstParagraph.textContent); //  Output: This is a paragraph.</pre><p><em>querySelectorAll() : Select Multiple Elements</em></p><pre>const allParagraphs = document.querySelectorAll(&quot;p&quot;);<br>console.log(allParagraphs.length); // Output: Number of `&lt;p&gt;` elements</pre><p><strong>Modifying the DOM:</strong></p><p>JavaScript can change content, styles, attributes and structures dynamically.</p><p><strong>Changing HTML Content (innerText / innerHTML):</strong></p><p>“innerText” modifies text, “innerHTML” allows inserting HTML.</p><pre>document.getElementById(&quot;title&quot;).innerText = &quot;Hello, JavaScript!&quot;;<br>document.getElementById(&quot;title&quot;).innerHTML = &quot;&lt;i&gt;Hello, JavaScript!&lt;/i&gt;&quot;;</pre><p><strong>Changing CSS Styles:</strong></p><pre>document.getElementById(&quot;title&quot;).style.color = &quot;blue&quot;;<br>document.getElementById(&quot;title&quot;).style.fontSize = &quot;24px&quot;;</pre><p><strong>Adding and Removing Classes (classList):</strong></p><p>Useful for toggling styles dynamically.</p><pre>const heading = document.getElementById(&quot;title&quot;);<br>heading.classList.add(&quot;highlight&quot;);  // Adds a class<br>heading.classList.remove(&quot;highlight&quot;);  //  Removes a class</pre><p><strong>Creating and Removing Elements:</strong></p><pre>const newElement = document.createElement(&quot;p&quot;);<br>newElement.textContent = &quot;This is a new paragraph!&quot;;<br>document.body.appendChild(newElement);</pre><p><strong>Traversing the DOM:</strong></p><p>JavaScript allows navigating between elements in the DOM tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*lFpr6o_4BHhHEdZ1lCmxgg.png" /></figure><p><strong>What is the Concept of Event Delegation in JavaScript?</strong></p><p>Event Delegation is a technique in JavaScript that involves attaching a single event listener to a parent element to handle events triggered by its child elements. Instead of adding event listeners to each individual child, you add one listener to the parent and use event bubbling to manage events efficiently.</p><p>When an event is triggered on a child element, it bubbles up to its parent elements. By attaching a single event listener to a common ancestor, you can manage events for multiple child elements.</p><p>Event delegation:</p><ul><li>improves performance; fewer event listeners mean less memory usage and better performance,</li><li>has dynamic content handling; works for elements added dynamically after page load,</li><li>simplifies code; centralizes event handling in one place.</li></ul><p><strong>HTML Structure</strong></p><pre>&lt;ul id=&quot;itemList&quot;&gt;<br>    &lt;li&gt;Item 1&lt;/li&gt;<br>    &lt;li&gt;Item 2&lt;/li&gt;<br>    &lt;li&gt;Item 3&lt;/li&gt;<br>&lt;/ul&gt;</pre><p><strong>JavaScript with Event Delegation</strong></p><pre>const itemList = document.getElementById(&quot;itemList&quot;);<br><br>itemList.addEventListener(&quot;click&quot;, function(event) {<br>    if (event.target.tagName === &quot;LI&quot;) {<br>        console.log(`You clicked on: ${event.target.textContent}`);<br>    }<br>}); // Output : Clicking on any &lt;li&gt; displays its text in the console</pre><p><strong>Handing Dynamic Elements with Event Delegation:</strong></p><p><em>Adding a new list item dynamically:</em></p><pre>const newItem = document.createElement(&quot;li&quot;);<br>newItem.textContent = &quot;Item 4&quot;;<br>itemList.appendChild(newItem); // No extra event listener needed!</pre><p><strong>Event Delegation with Multiple Child Elements:</strong></p><p><em>HTML Structure</em></p><pre>&lt;div id=&quot;container&quot;&gt;<br>    &lt;button class=&quot;btn&quot;&gt;Button 1&lt;/button&gt;<br>    &lt;button class=&quot;btn&quot;&gt;Button 2&lt;/button&gt;<br>    &lt;button class=&quot;btn&quot;&gt;Button 3&lt;/button&gt;<br>&lt;/div&gt;</pre><p><em>JavaScript for Handling Multiple Buttons</em></p><pre>document.getElementById(&quot;container&quot;).addEventListener(&quot;click&quot;, function(event) {<br>    if (event.target.classList.contains(&quot;btn&quot;)) {<br>        console.log(`${event.target.textContent} clicked`);<br>    }<br>});</pre><p><strong>Event Delegation in From Validation:</strong></p><p><em>HTML Structure</em></p><pre>&lt;form id=&quot;myForm&quot;&gt;<br>    &lt;input type=&quot;text&quot; name=&quot;username&quot; placeholder=&quot;Username&quot;&gt;<br>    &lt;input type=&quot;password&quot; name=&quot;password&quot; placeholder=&quot;Password&quot;&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;</pre><p><em>JavaScript for Validating Inputs</em></p><pre>document.getElementById(&quot;myForm&quot;).addEventListener(&quot;input&quot;, function(event) {<br>    if (event.target.name === &quot;username&quot; &amp;&amp; event.target.value.length &lt; 3) {<br>        console.log(&quot;Username must be at least 3 characters long.&quot;);<br>    }<br>    if (event.target.name === &quot;password&quot; &amp;&amp; event.target.value.length &lt; 6) {<br>        console.log(&quot;Password must be at least 6 characters long.&quot;);<br>    }<br>});</pre><p><strong>Potential Pitfalls of Event Delegation</strong></p><p>Event delegation may not be suitable when:</p><p>1. <strong>Target elements have complex structures; </strong>misidentifying the event.target</p><p>2. <strong>Performance concerns with deep nesting;</strong> event bubbling might cause unintended triggers</p><p>3. <strong>Specific event types(blur, focus, etc.);</strong> these do not bubble</p><p><strong>What are Higher-Order Functions in JavaScript?</strong></p><p>A higher-order function(HOF) is functions make code more reusable, modular and easier to work with in functional programming. It does one or both of the following:</p><p>1. Takes another function as an argument.</p><p>2. Returns a function as its output.</p><p><strong>HOF Example that takes a function as an argument:</strong></p><pre>function greet(name, callback) {<br>    console.log(`Hello, ${name}!`);<br>    callback();<br>}<br>function sayGoodbye() {<br>    console.log(&quot;Goodbye!&quot;);<br>}<br>greet(&quot;Ipek&quot;, sayGoodbye);<br>//Output: <br>//Hello, Ipek!<br>//Goodbye!</pre><p><strong>HOF Example that returns a function:</strong></p><pre>function multiplier(factor) {<br>    return function (number) {<br>        return number * factor;<br>    };<br>}<br>const double = multiplier(2);<br>console.log(double(5)); // Output: 10<br>const triple = multiplier(3);<br>console.log(triple(5)); // Output: 15</pre><p><strong>Common Built-in Higher-Order Functions:</strong></p><p><strong>map():</strong> Transforms each element.</p><pre>const numbers = [1, 2, 3, 4];<br>const squared = numbers.map(num =&gt; num * num);<br>console.log(squared); // Output: [1, 4, 9, 16]</pre><p><strong>filter():</strong> Filters elements based on a condition.</p><pre>const ages = [10, 25, 30, 15, 40];<br>const adults = ages.filter(age =&gt; age &gt;= 18);<br>console.log(adults); // Output: [25, 30, 40]</pre><p><strong>reduce():</strong> Accumulates a value.</p><pre>const numbers = [1, 2, 3, 4];<br>const sum = numbers.reduce((acc, num) =&gt; acc + num, 0);<br>console.log(sum); // Output: 10</pre><p><strong>What is the use of JSON.stringify() and JSON.parse() in JS?</strong></p><p>JavaScript provides two built-in methods, JSON.stringify() and JSON.parse() to convert data between JavaScript objects and JSON format.</p><p><strong>What is JSON?</strong></p><p>JSON(JavaScript Object Notation) is a lightweight format used to store and exchange data. It is often used when:</p><p>-Sending data between a server and a client,</p><p>-Storing data in localStorage or sessionStorage,</p><p>-Reading or writing configuration files.</p><p><strong>JSON.stringify():</strong> Converts JavaScript object to JSON string.</p><pre>const person = { name: &quot;Alice&quot;, age: 25, isStudent: false };<br><br>const jsonString = JSON.stringify(person);<br>console.log(jsonString);<br>//Output: {&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:25,&quot;isStudent&quot;:false}</pre><p><strong>Pretty Print JSON:</strong></p><pre>console.log(JSON.stringify(person, null, 2)); <br>//Output:         { <br>                   //“name”: &quot;Alice&quot;, <br>                   //“age”: 25, <br>                   //“isStudent”: false <br>                //}</pre><p><strong>JSON.parse():</strong> Converts JSON string back to a JavaScript object.</p><pre>const jsonString = &#39;{&quot;name&quot;:&quot;Alice&quot;,&quot;age&quot;:25,&quot;isStudent&quot;:false}&#39;;<br><br>const personObject = JSON.parse(jsonString);<br>console.log(personObject);<br>//Output:      { <br>                   //“name”: &quot;Alice&quot;, <br>                   //“age”: 25, <br>                   //“isStudent”: false <br>//             }</pre><p><strong>-Use cases:</strong></p><p><strong>Storing data in localStorage(Browser) :</strong> Data remains persistent after page reload.</p><pre>const user = { name: &quot;Bob&quot;, score: 100 };<br><br>// Save object as a JSON string<br>localStorage.setItem(&quot;user&quot;, JSON.stringify(user));<br><br>// Retrieve and convert back to object<br>const retrievedUser = JSON.parse(localStorage.getItem(&quot;user&quot;));<br>console.log(retrievedUser);<br>//Output: {<br>                //&quot;name&quot;: &quot;Bob&quot;,<br>                //&quot;score&quot;: 100<br>//        }</pre><p><strong>Sending data to an API(AJAX, Fetch):</strong></p><pre>const user = { username: &quot;Charlie&quot;, email: &quot;charlie@example.com&quot; };<br><br>fetch(&quot;https://api.example.com/users&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify(user)<br>})<br>.then(response =&gt; response.json())<br>.then(data =&gt; console.log(data));</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3351e76d9e82" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>