🚀 Day 27/30 – Compact Object in JavaScript 🧹 | Remove Falsy Values Recursively Given an object or array obj, return a compact object. ✅ What is a Compact Object? It’s the same structure as the original — but with all keys containing falsy values removed. 🔎 Falsy Values in JavaScript: false 0 "" (empty string) null undefined NaN ⚠️ This removal applies: To the main object To nested objects To nested arrays You may assume: obj is valid JSON (output of JSON.parse) Arrays are treated as objects (indices are keys) 🧠 Example 1 obj = {"a": null, "b": [false, 1]} Output: {"b": [1]} 🧠 Example 2 obj = { "a": 0, "b": { "c": false, "d": 5 } } Output: { "b": { "d": 5 } } 💡 JavaScript Solution (Recursive) var compactObject = function(obj) { if (Array.isArray(obj)) { const result = []; for (let item of obj) { const compacted = compactObject(item); if (Boolean(compacted)) { result.push(compacted); } } return result; } else if (obj !== null && typeof obj === "object") { const result = {}; for (let key in obj) { const compacted = compactObject(obj[key]); if (Boolean(compacted)) { result[key] = compacted; } } return result; } return obj; }; 🔎 Why This Works Recursively traverse structure If array → build new filtered array If object → build new filtered object Only keep values where Boolean(value) === true Preserves structure while removing falsy values Time Complexity: O(n) Space Complexity: O(n) (n = total nested elements) 🧠 What This Teaches ✅ Recursive traversal ✅ Object vs Array handling ✅ Deep data transformation ✅ JSON structure processing ✅ Real-world data cleaning logic ⚡ Real-World Use Cases Cleaning API payloads Removing empty form fields Optimizing database writes Sanitizing user input Preprocessing configuration files #JavaScript #30DaysOfJavaScript #CodingChallenge #Recursion #DataStructures #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CleanCode #LearnToCode #Programming #InterviewPrep #ProblemSolving #JSDeveloper #100DaysOfCode JavaScript remove falsy values Compact object JavaScript Remove null values from object JS Recursive object cleaning JS Deep object traversal JavaScript JSON data cleaning JavaScript JavaScript interview question recursion Remove empty keys from object JS
Remove Falsy Values from JavaScript Objects Recursively
More Relevant Posts
-
Complete JavaScript Road Map🔥 A-Z JavaScript👇 1.Variables ↳ var ↳ let ↳ const 2. Data Types ↳ number ↳ string ↳ boolean ↳ null ↳ undefined ↳ symbol 3.Declaring variables ↳ var ↳ let ↳ const 4.Expressions Primary expressions ↳ this ↳ Literals ↳ [] ↳ {} ↳ function ↳ class ↳ function* ↳ async function ↳ async function* ↳ /ab+c/i ↳ string ↳ ( ) Left-hand-side expressions ↳ Property accessors ↳ ?. ↳ new ↳ new .target ↳ import.meta ↳ super ↳ import() 5.operators ↳ Arithmetic Operators: +, -, *, /, % ↳ Comparison Operators: ==, ===, !=, !==, <, >, <=, >= ↳ Logical Operators: &&, ||, ! 6.Control Structures ↳ if ↳ else if ↳ else ↳ switch ↳ case ↳ default 7.Iterations/Loop ↳ do...while ↳ for ↳ for...in ↳ for...of ↳ for await...of ↳ while 8.Functions ↳ Arrow Functions ↳ Default parameters ↳ Rest parameters ↳ arguments ↳ Method definitions ↳ getter ↳ setter 9.Objects and Arrays ↳ Object Literal: { key: value } ↳ Array Literal: [element1, element2, ...] ↳ Object Methods and Properties ↳ Array Methods: push(), pop(), shift(), unshift(), splice(), slice(), forEach(), map(), filter() 10.Classes and Prototypes ↳ Class Declaration ↳ Constructor Functions ↳ Prototypal Inheritance ↳ extends keyword ↳ super keyword ↳ Private class features ↳ Public class fields ↳ static ↳ Static initialization blocks 11.Error Handling ↳ try, ↳ catch, ↳ finally (exception handling) ADVANCED CONCEPTS -------------------------- 12.Closures ↳ Lexical Scope ↳ Function Scope ↳ Closure Use Cases 13.Asynchronous JavaScript ↳ Callback Functions ↳ Promises ↳ async/await Syntax ↳ Fetch API ↳ XMLHttpRequest 14.Modules ↳ import and export Statements (ES6 Modules) ↳ CommonJS Modules (require, module.exports) 15.Event Handling ↳ Event Listeners ↳ Event Object ↳ Bubbling and Capturing 16.DOM Manipulation ↳ Selecting DOM Elements ↳ Modifying Element Properties ↳ Creating and Appending Elements 17.Regular Expressions ↳ Pattern Matching ↳ RegExp Methods: test(), exec(), match(), replace() 18.Browser APIs ↳ localStorage and sessionStorage ↳ navigator Object ↳ Geolocation API ↳ Canvas API 19.Web APIs ↳ setTimeout(), setInterval() ↳ XMLHttpRequest ↳ Fetch API ↳ WebSockets 20.Functional Programming ↳ Higher-Order Functions ↳ map(), reduce(), filter() ↳ Pure Functions and Immutability 21.Promises and Asynchronous Patterns ↳ Promise Chaining ↳ Error Handling with Promises ↳ Async/Await 22.ES6+ Features ↳ Template Literals ↳ Destructuring Assignment ↳ Rest and Spread Operators ↳ Arrow Functions ↳ Classes and Inheritance ↳ Default Parameters ↳ let, const Block Scoping 23.Browser Object Model (BOM) ↳ window Object ↳ history Object ↳ location Object ↳ navigator Object 24.Node.js Specific Concepts ↳ require() ↳ Node.js Modules (module.exports) ↳ File System Module (fs) ↳ npm (Node Package Manager) 25.Testing Frameworks ↳ Jasmine ↳ Mocha ↳ Jest Hope it helps 😊🌱
To view or add a comment, sign in
-
1. What are the different data types in JavaScript • String, Number, Boolean, Undefined, Null, Object, Symbol, BigInt Use `typeof` to check a variable’s type. 2. What is the difference between == and === • `==` compares values with type coercion • `===` compares both value and type (strict equality) 3. What is hoisting in JavaScript Variables and function declarations are moved to the top of their scope before execution. Only declarations are hoisted, not initializations. 4. What is a closure A function that remembers variables from its outer scope even after the outer function has finished executing. Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 ``` 5. What is the difference between var, let, and const • `var`: function-scoped, can be re-declared • `let`: block-scoped, can be updated • `const`: block-scoped, cannot be re-assigned 6. What is event delegation Using a single event listener on a parent element to handle events from its child elements using `event.target`. 7. What is the use of promises in JavaScript Handle asynchronous operations. States: pending, fulfilled, rejected Example: ```js fetch(url) .then(res => res.json()) .catch(err => console.error(err)); ``` 8. What is async/await Syntactic sugar over promises for cleaner async code Example: ```js async function getData() { const res = await fetch(url); const data = await res.json(); console.log(data); } ``` 9. What is the difference between null and undefined • `null`: intentional absence of value • `undefined`: variable declared but not assigned 10. What is the use of arrow functions* Shorter syntax, no own `this` binding Example: ```js const add = (a, b) => a + b; ``` 11. What is the DOM Document Object Model — represents HTML as a tree structure. JavaScript can manipulate it using methods like `getElementById`, `querySelector`, etc. 12. What is the difference between call, apply, and bind • `call`: invokes function with arguments passed individually • `apply`: invokes function with arguments as array • `bind`: returns a new function with bound context 13. What is the use of setTimeout and setInterval • `setTimeout`: runs code once after delay • `setInterval`: runs code repeatedly at intervals 14. What is the difference between stack and heap • Stack: stores primitive values and function calls • Heap: stores objects and reference types 15. What is the use of the spread operator (...) Expands arrays/objects or merges them Example: ```js const arr = [1, 2]; const newArr = [...arr, 3]; // [1, 2, 3] ``` 16. What is the difference between map and forEach • `map`: returns a new array • `forEach`: performs action but returns undefined 17. What is the use of localStorage and sessionStorage • `localStorage`: persists data even after browser is closed • `sessionStorage`: persists data only for session
To view or add a comment, sign in
-
🤔 Ever copied an object with { ...obj } and thought you made a fully separate copy… then a nested value changed in both places? That’s the shallow vs deep copy trap in JavaScript. 🧠 JavaScript interview question What’s the difference between a shallow copy and a deep copy in JavaScript? ✅ Short answer A shallow copy copies only the top-level properties. If a property contains a nested object or array, the copy still points to the same reference. A deep copy creates a fully independent clone, including nested objects and arrays. 🔍 A bit more detail Shallow copy Top-level values are copied Nested objects/arrays are still shared Changing nested data affects both the original and the copy Common shallow copy methods: spread syntax: { ...obj } Object.assign() array methods like slice() and concat() Deep copy Clones nested structures too Changes in the copy do not affect the original Better when you need true independence Common deep copy approaches: structuredClone() custom recursive cloning JSON.parse(JSON.stringify(obj)) for simple JSON-safe data only 💻 Example const original = { name: "Alice", address: { city: "Miami" }, scores: [10, 20], }; const shallow = { ...original }; shallow.name = "Bob"; // affects only the copy shallow.address.city = "Tampa"; // affects both shallow.scores.push(30); // affects both console.log(original.address.city); // "Tampa" console.log(original.scores); // [10, 20, 30] Here, name is fine because it’s a primitive. But address and scores are nested references, so both objects still share them. 💻 Deep copy example const original = { date: new Date(), list: [1, 2, 3] }; const deep = structuredClone(original); deep.list.push(4); console.log(original.list); // [1, 2, 3] // Changing the original doesn't affect the copy original.date.setFullYear(2030); console.log(deep.date.getFullYear()); // original change has no effect ⚠️ Important gotchas { ...obj } does not make a deep copy Object.assign() is also shallow JSON.parse(JSON.stringify(obj)) loses things like: functions undefined Date objects as real Dates Map Set cyclic references So for modern JavaScript, structuredClone() is usually the safer built-in option when supported. 🎯 Real-world way to think about it A shallow copy is like copying a folder but keeping the same files inside. A deep copy is like duplicating the folder and duplicating every file inside it too. That’s why nested changes behave differently. 💡 When to use which Use shallow copy when: your data is flat nested data is intentionally shared you only need a quick top-level clone Use deep copy when: nested data must be fully independent you’re working with mutable complex state shared references could cause bugs That difference looks small in code, but it causes a lot of real bugs in apps. #javascript #webdevelopment #frontend #reactjs #softwareengineering #programming #coding #javascriptdeveloper #frontenddeveloper #interviewprep
To view or add a comment, sign in
-
🚀 JavaScript Strings & Objects 1️⃣ What is a String? A string is a sequence of characters (text data) let name = "Javascript"; ✔️ Used to store text ✔️ Can include letters, numbers, symbols String Methods: let text = " hello world "; 1. length console.log(text.length); // Output: 15 (includes spaces) 2. toUpperCase() console.log(text.toUpperCase()); // Output: " HELLO WORLD " 3. toLowerCase() console.log(text.toLowerCase()); // Output: " hello world " 4. trim() console.log(text.trim()); // Output: "hello world" 5. includes() console.log(text.includes("hello")); // Output: true 6. slice() console.log(text.slice(2, 7)); // Output: "hello" 7. replace() console.log(text.replace("world", "JavaScript")); // Output: " hello JavaScript " 8. split() console.log(text.trim().split(" ")); // Output: ["hello", "world"] 2️⃣ What is an Object? An object is a collection of key-value pairs let user = { name: "Javascript", age: 21 }; ✔️ Used to store related data together ✔️ Represents real-world entities 🔹 Object.keys() : Returns all keys of the object console.log(Object.keys(user)); // ["name", "age", "city"] 🔹 Object.values(): Returns all values console.log(Object.values(user)); // ["Javascript", 21, "India"] 🔹 Object.entries(): Returns key-value pairs as arrays console.log(Object.entries(user)); // [["name","Javascript"], ["age",21], ["city","India"]] 🔹 Object.assign(): Used to copy or merge objects let updatedUser = Object.assign({}, user, { age: 22 }); /// { name: "Javascript", age: 22, city: "India" } 🔹 hasOwnProperty(): Checks if a key exists in object console.log(user.hasOwnProperty("name")); // true 🔹 Object.freeze(): Prevents changes to object Object.freeze(user); user.age = 25; console.log(user.age); // 21 (no change) 🔹 Object.seal(): Allows update but not add/remove Object.seal(user); user.age = 25; // ✅ allowed user.country = "India"; // ❌ not allowed #JavaScript #Frontend #WebDevelopment #Coding #LearnInPublic
To view or add a comment, sign in
-
How do you deep clone an object in JavaScript? If you answered JSON.parse(JSON.stringify(obj)), you're not alone. It's been the go-to hack for over a decade. But it's broken in ways that will bite you at the worst possible time. const original = { name: "Pranjul", joined: new Date("2024-01-01"), skills: new Set(["React", "CSS", "TypeScript"]) }; const cloned = JSON.parse(JSON.stringify(original)); console.log(cloned.joined); // "2024-01-01T00:00:00.000Z" (string, NOT a Date) console.log(cloned.skills); // {} (empty object, NOT a Set) Everything silently broke. No errors and warnings. Your Date is now a string. Your Set is an empty object. And your code downstream has no idea. This is why structuredClone() exists. const cloned = structuredClone(original); console.log(cloned.joined); // Date object (correct!) console.log(cloned.skills); // Set {"React", "CSS", "TypeScript"} (correct!) One function call. Everything cloned properly. Let me highlight that circular reference row: const obj = { name: "Pranjul" }; obj.self = obj; // circular reference JSON.parse(JSON.stringify(obj)); // TypeError: Converting circular structure to JSON structuredClone(obj); // Works perfectly. Returns a proper deep clone. If you've ever hit that circular reference error in production, you know how painful it is. structuredClone just handles it. When JSON.parse/stringify still wins: There is one scenario where the JSON approach has an advantage: speed for simple, flat objects with only strings and numbers. The JSON functions are heavily optimized in V8. For this kind of data, JSON is faster: const simpleData = { id: 1, name: "Pranjul", active: true, tags: ["frontend", "react"] }; But the moment you have Dates, Sets, Maps, undefined, or nested structures, structuredClone is the correct choice. What structuredClone CANNOT clone: Not everything is supported. Functions and DOM nodes can't be cloned. Class instances get cloned as plain objects and lose their methods. That's by design. My rule of thumb: ✅ Need to clone plain data with possible Dates/Sets/Maps? Use structuredClone ✅ Need to serialize data for storage or network? Use JSON.stringify ✅ Need to clone class instances with methods? Write a custom clone method structuredClone ships in every modern browser and Node.js 17+. There's no reason to keep using the JSON hack for deep cloning in 2026. What's a JavaScript built-in that you learned about way too late? Share below 👇 w3schools.com JavaScript Mastery JavaScript Developer Frontend Masters
To view or add a comment, sign in
-
-
🚀 𝗧𝗵𝗲 𝗦𝗲𝗰𝗿𝗲𝘁 𝗟𝗶𝗳𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁: 𝗔 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 𝗧𝗵𝗿𝗼𝘂𝗴𝗵 𝗠𝗲𝗺𝗼𝗿𝘆 Ever wonder why some apps get sluggish over time? It’s usually a memory issue. In JS, we have an "𝗜𝗻𝘃𝗶𝘀𝗶𝗯𝗹𝗲 𝗝𝗮𝗻𝗶𝘁𝗼𝗿" (the Garbage Collector) who handles cleanup, but as engineers, we must ensure we don't accidentally "lock the broom closet." 1️⃣ 𝗧𝗵𝗲 𝗕𝗶𝗿𝘁𝗵: 𝗦𝘁𝗮𝗰𝗸 𝘃𝘀. 𝗛𝗲𝗮𝗽 JavaScript uses two distinct "storage rooms" for your data: • 𝗧𝗵𝗲 𝗦𝘁𝗮𝗰𝗸 (𝗙𝗮𝘀𝘁 & 𝗦𝘁𝗮𝘁𝗶𝗰): Stores Primitives (Numbers, Strings, Booleans). It follows a 𝗟𝗜𝗙𝗢 (Last-In, First-Out) structure. Access is nearly instantaneous. • 𝗧𝗵𝗲 𝗛𝗲𝗮𝗽 (𝗟𝗮𝗿𝗴𝗲 & 𝗗𝘆𝗻𝗮𝗺𝗶𝗰): Stores Non-Primitives (Objects, Arrays). It grows as needed but requires more management overhead. 𝗧𝗵𝗲 "𝗦𝗼 𝗪𝗵𝗮𝘁?": When you copy an object, you only copy the 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 (the address). If obj1 and obj2 point to the same heap address, modifying one changes the other. 💡 𝘗𝘳𝘰-𝘛𝘪𝘱: 𝘜𝘴𝘦 𝘴𝘵𝘳𝘶𝘤𝘵𝘶𝘳𝘦𝘥𝘊𝘭𝘰𝘯𝘦() 𝘧𝘰𝘳 𝘵𝘳𝘶𝘦 𝘥𝘦𝘦𝘱-𝘤𝘭𝘰𝘯𝘪𝘯𝘨. 2️⃣ 𝗧𝗵𝗲 𝗟𝗶𝗳𝗲𝗹𝗶𝗻𝗲: 𝗥𝗲𝗮𝗰𝗵𝗮𝗯𝗶𝗹𝗶𝘁𝘆 Your "right to exist" in JS is defined by 𝗥𝗲𝗮𝗰𝗵𝗮𝗯𝗶𝗹𝗶𝘁𝘆. An object is alive only if it can be reached from a 𝗥𝗼𝗼𝘁 (the window or global object). 𝗧𝗵𝗲 𝗦𝘂𝗿𝘃𝗶𝘃𝗮𝗹 𝗖𝗵𝗲𝗰𝗸𝗹𝗶𝘀𝘁: ✅ Is it a Root? (Global object) ✅ Is it referenced by a Root (e.g., a global variable)? ✅ Is it a local variable in a function currently running? ✅ Is it a property of an object that is itself reachable? 3️⃣ 𝗧𝗵𝗲 𝗚𝗿𝗲𝗮𝘁 𝗖𝗹𝗲𝗮𝗻𝘂𝗽: 𝗠𝗮𝗿𝗸-𝗮𝗻𝗱-𝗦𝘄𝗲𝗲𝗽 Modern engines use the 𝗠𝗮𝗿𝗸-𝗮𝗻𝗱-𝗦𝘄𝗲𝗲𝗽 algorithm: 1. 𝗠𝗮𝗿𝗸: The GC starts at the Roots and "paints" every reachable object. 2. 𝗦𝘄𝗲𝗲𝗽: It reclaims every bit of space occupied by the "unpainted" (unreachable) ones. 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁'𝘀 𝗜𝗻𝘀𝗶𝗴𝗵𝘁: This solves the 𝗖𝗶𝗿𝗰𝘂𝗹𝗮𝗿 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 problem. If two objects point to each other but are disconnected from the Root, the Janitor recognizes they are "garbage" and clears them both. 4️⃣ 𝗖𝗼𝗺𝗺𝗼𝗻 𝗠𝗲𝗺𝗼𝗿𝘆 𝗟𝗲𝗮𝗸𝘀 A leak occurs when you leave a "string" attached to an object you no longer need: ⚠️ 𝗔𝗰𝗰𝗶𝗱𝗲𝗻𝘁𝗮𝗹 𝗚𝗹𝗼𝗯𝗮𝗹𝘀: Forgetting let/const pins data to the Root forever. ⚠️ 𝗙𝗼𝗿𝗴𝗼𝘁𝘁𝗲𝗻 𝗧𝗶𝗺𝗲𝗿𝘀: setInterval captures scope until clearInterval is called. ⚠️ 𝗢𝘂𝘁-𝗼𝗳-𝗗𝗢𝗠 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲𝘀: Removing a button visually but keeping it in a JS variable keeps it in RAM. 💡 𝗧𝗵𝗲 𝟯 𝗚𝗼𝗹𝗱𝗲𝗻 𝗥𝘂𝗹𝗲𝘀: 1. 𝗠𝗶𝗻𝗶𝗺𝗶𝘇𝗲 𝗚𝗹𝗼𝗯𝗮𝗹𝘀: Keep variables tightly scoped. 2. 𝗨𝘀𝗲 𝗪𝗲𝗮𝗸𝗠𝗮𝗽𝘀: Perfect for metadata; they don't prevent the Janitor from doing his job. 3. 𝗖𝗹𝗲𝗮𝗻 𝗬𝗼𝘂𝗿 𝗧𝗶𝗺𝗲𝗿𝘀: Treat every timer as a debt that must be paid back. What’s the toughest memory leak you’ve ever fixed? Share your story below! 👇 #JavaScript #WebDev #SoftwareEngineering #CodingTips #WebPerf #Programming
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 11 Imagine this 👇 You are building an app… And you need to store: User 1 name User 2 name User 3 name User 4 name 😵 Will you create separate variables for each? ```javascript let user1 = "Abhay" let user2 = "Rahul" let user3 = "Aman" ``` This is messy ❌ Not scalable ❌ --- ## 🔥 Solution → Arrays An **Array** is a data structure that allows you to store **multiple values in a single variable** --- ## 🔹 Creating an Array ```javascript let users = ["Abhay", "Rahul", "Aman"] ``` 👉 Now everything is inside one variable --- ## 🔹 Index (Very Important) Every element in an array has an **index** ```javascript let users = ["Abhay", "Rahul", "Aman"] ``` Index: Abhay → 0 Rahul → 1 Aman → 2 👉 Array always starts from **0** --- ## 🔹 Accessing Values ```javascript console.log(users[0]) // Abhay console.log(users[1]) // Rahul ``` --- ## 🔹 Updating Values ```javascript users[1] = "Neha" console.log(users) ``` 👉 Output: ["Abhay", "Neha", "Aman"] --- ## 🔹 Array Length ```javascript console.log(users.length) ``` 👉 Output: 3 📌 Useful when working with loops --- ## 🔹 Real Life Example Think of a **shopping cart 🛒** Instead of: item1 item2 item3 We use: ```javascript let cart = ["Shoes", "T-shirt", "Watch"] ``` 👉 Clean 👉 Organized 👉 Easy to manage --- ## 🔥 Simple Summary Array → multiple values ek jagah Index → position of value Access → users[0] Update → users[1] = "Neha" --- ### 💡 Programming Rule **Group related data together. Arrays make your code clean and scalable.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
𝗧𝗼𝗽 𝟱𝟬 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗘𝘃𝗲𝗿𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿 𝗦𝗵𝗼𝘂𝗹𝗱 𝗞𝗻𝗼𝘄 Preparing for interviews? Here’s a power-packed list of essential JavaScript questions with quick descriptions 1. What is JavaScript? A scripting language used to build dynamic web applications 2. var vs let vs const – Differences in scope, hoisting, and mutability 3. What is hoisting? Declarations moved to the top during execution 4. What is closure? Function accessing outer scope variables after execution 5. Event loop – Handles async execution in JavaScript 6. call vs apply vs bind – Control function context ("this") 7. What is this keyword? Refers to execution context 8. What are promises? Handle async operations with states 9. async/await – Cleaner syntax for promises 10. Callback hell – Nested callbacks causing unreadable code 11. Prototypal inheritance – Objects inherit from other objects 12. == vs === – Loose vs strict equality 13. What is NaN? Represents invalid number operations 14. Arrow functions – Short syntax without own "this" 15. Destructuring – Extract values from arrays/objects 16. Spread vs Rest – Expand vs collect values 17. Debouncing – Delay function execution 18. Throttling – Limit execution frequency 19. Event delegation – Handle events via parent element 20. What is DOM? HTML structure as a tree. 21. What is BOM? Browser interaction model. 22. localStorage vs sessionStorage – Data persistence differences 23. What is JSON? Data format for APIs. 24. Deep vs shallow copy – Reference vs value copying 25. Currying – Transform function into nested functions 26. Memoization – Cache function results 27. setTimeout vs setInterval – One-time vs repeated execution 28. Garbage collection – Automatic memory management 29. Strict mode – Enforces better coding practices 30. IIFE – Immediately invoked function. 31. Module pattern – Encapsulation using closures 32. Event bubbling – Events propagate upward 33. Event capturing – Events propagate downward 34. preventDefault – Stops default browser behavior 35. stopPropagation – Stops event flow. 36. Fetch API – Modern HTTP request handling 37. AJAX – Async data fetching without reload 38. Web Storage API – Store data in browser 39. CORS – Cross-origin request security 40. Lexical scope – Scope based on code structure 41. Execution context – Environment where code runs 42. Call stack – Tracks function calls. 43. Microtask vs macrotask – Promise queue vs callback queue 44. Symbol – Unique primitive type 45. BigInt – Large integer handling 46. Optional chaining – Safe property access 47. null vs undefined – Intentional vs uninitialized values 48. map vs filter vs reduce – Array methods 49. Object.freeze – Prevent object modification 50. Type coercion – Automatic type conversion Tip: Don’t just memorize—understand concepts and explain with real-world examples. #JavaScript #Frontend #WebDevelopment #CodingInterview #SoftwareEngineering #Developers #TechInterview
To view or add a comment, sign in
-
𝗨𝗻𝗱𝗲𝗿𝗦𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗮𝗻𝗱 𝗗𝗮𝘁𝗮 𝗧𝘆𝗽𝗲𝘀 𝗶𝗻 𝗝𝗮𝗙𝗮𝗦𝗰𝗿𝗶𝗽𝘁 JavaScript seems easy at first. You write a few lines of code, run it, and everything works. But soon you realize that variables and data types are key. If you skip these basics, your code can become a guessing game. You will use console.log() everywhere just to understand what's happening. So, before moving deeper into JavaScript, understand how variables and data types work. Here's what you will learn: - What variables are and why they are needed - How to declare variables using var, let, and const - Primitive data types like string, number, and boolean - The differences between var, let, and const - What scope means in JavaScript A variable is a name used to store a value. Whenever you need that value, you can access it by using the variable's name. For example: let count = 1; Here, count is the variable name and 1 is the value stored in that variable. Good variable names should be short and descriptive. Examples: clickButton, addNumbers, userAge. A good variable name should be self-explanatory so that someone reading your code can easily understand what it represents. To create a variable in JavaScript, use one of these keywords: let, const, var. Example: let count = 1; This statement declares a variable called count and assigns the value 1 to it. In JavaScript, data types define what kind of value a variable can store. Think of data types like containers in real life. JavaScript data types are broadly divided into two categories: - Primitive data types: string, number, boolean, undefined, null - Other data types: BigInt, Symbol, Object, Array, Function For now, let's focus on primitive data types. A string represents text and is written inside quotes. let message = "Like this blog"; Numbers can be integers or decimals. let marks = 95; let price = 99.99; A boolean value can only be true or false. let isLoggedIn = true; let isAdmin = false; When a variable is declared but no value is assigned, its value becomes undefined. let x; null means a variable intentionally has no value. let data = null; Variables and data types are the foundation of JavaScript. If you understand these concepts well, learning more advanced topics will become much easier. Take time to practice writing small examples and experimenting with console.log() to see how values change. Source: https://lnkd.in/gdNskB_J Optional learning community: https://t.me/GyaanSetuAi
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development