🔍 JavaScript Objects: Dot Notation vs Bracket Notation Why do we have two ways to access object properties — and when should we use each? If both dot notation and bracket notation do the same thing, why does JavaScript even support both? The short answer: flexibility + real-world use cases. Let’s break it down 👇 ⸻——————————————————- 1️⃣ Dot Notation – Clean, readable, and predictable const user = { name: "Jagdish", role: "Frontend Developer" }; user.name; // "Jagdish" ——————————————- ✅ When to use dot notation • Property names are known at development time • Keys are valid JavaScript identifiers • You want clean & readable code 🚫 When you can’t use dot notation user.first-name ❌ // Error user["first-name"] ✅ Why? Dot notation does not support: • Spaces • Hyphens (-) • Dynamic values —————————————————— 2️⃣ Bracket Notation – Dynamic and powerful const key = "role"; user[key]; // "Frontend Developer" ✅ When to use bracket notation • Property name is dynamic • Key comes from user input, API response, or loop • Property contains special characters ———————————— const data = { "total-users": 120, "2025": "Active" }; data["total-users"]; // 120 data["2025"]; // "Active" —————————————- Dot notation fails here ❌ Bracket notation works perfectly ✅ _______________________________ 3️⃣ Real-world examples 🔹 API responses response.data[fieldName]; You don’t know the key beforehand → bracket notation is required. 🔹 Forms & dynamic filters filters[selectedFilter]; 🔹 Looping through objects for (let key in user) { console.log(user[key]); } Dot notation simply cannot work here. ——————————————————————- 4️⃣ Mental model to remember forever 🧠 • Dot notation → Static & known • Bracket notation → Dynamic & unknown If JavaScript needs to evaluate the key at runtime, you must use bracket notation. JavaScript didn’t give us two notations by accident. It gave us simplicity and power. Knowing why and when to use each is what separates 👉 someone who knows syntax from 👉 someone who understands JavaScript deeply. If this helped you, react or share — someone in your network needs this today 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #JavaScriptTips #CodingBestPractices #LearnJavaScript #SoftwareEngineering #CleanCode #DeveloperCommunity #ProgrammingConcepts #TechCareers #ReactJS #WebDev
Dot Notation vs Bracket Notation in JavaScript: When to Use Each
More Relevant Posts
-
When I first heard about the JavaScript Event Loop, it sounded extremely complex. ☺️ Call Stack? ☺️ Callback Queue? ☺️ Web APIs? But once I understood the logic behind it, asynchronous JavaScript finally made sense. 1️⃣ JavaScript Is Single-Threaded 2️⃣ JavaScript can do one thing at a time. 3️⃣ It uses something called the Call Stack to execute functions line by line. So how does it handle: • setTimeout() • API calls • User clicks without freezing the application? This Is Where the Event Loop Comes In Behind the scenes, JavaScript uses: • Call Stack • Web APIs • Callback Queue • Event Loop Here’s the simple flow: 1️⃣ Synchronous code goes to the Call Stack. 2️⃣ Async tasks (like setTimeout or fetch) go to Web APIs. 3️⃣ Once completed, their callbacks move to the Callback Queue. 4️⃣ The Event Loop checks if the Call Stack is empty. 5️⃣ If empty, it pushes the callback into the stack for execution. ┌─────────────────┐ Call Stack (Runs code) └─────────────────┘ ↑ │ ┌─────────────────┐ Event Loop (Traffic Cop) └─────────────────┘ ↑ │ ┌─────────────────┐ Callback Queue (Waiting Tasks) └─────────────────┘ ↑ │ ┌─────────────────┐ Web APIs (Timers, Fetch) └─────────────────┘ The Event Loop is just a traffic controller. 🤦♂️Common Beginner Mistake❓ Thinking asynchronous code runs immediately. 👉Example: setTimeout(() => { console.log("Hello"); }, 0); Even with 0 delay, it waits until the Call Stack is empty.
To view or add a comment, sign in
-
-
🔍 Cursor-Focused Zoom Effect Using Pure JavaScript (No Plugins!) Ever wanted a magnifier-style zoom effect on your web page that follows the mouse cursor? Here’s a lightweight JavaScript solution that zooms the entire page dynamically when pressing "Shift"(Button Customizable) — and resets instantly when released. No libraries. No plugins. Just clean JavaScript. 🚀 🎯 Use Case ✅ Highlight small UI elements during demos ✅ Improve visibility during presentations ✅ Quick inspection tool for developers ✅ Works great in tools like Oracle APEX, admin dashboards ⚙️ How It Works ✔ Detects "Shift" key combination ✔ Zooms the page to 3.15x ✔ Sets transform origin based on mouse position ✔ Resets when key is released, mouse click happens, or window loses focus 💻 JavaScript Code : (function () { const zoomLevel = 3.15; let isZoomed = false; let mouseX = 0; let mouseY = 0; const root = document.documentElement; function updateOrigin() { const xPercent = (mouseX / window.innerWidth) * 100; const yPercent = (mouseY / window.innerHeight) * 100; root.style.transformOrigin = `${xPercent}% ${yPercent}%`; } function applyZoom() { if (isZoomed) return; updateOrigin(); root.style.transition = "transform 0.08s ease-out"; root.style.transform = `scale(${zoomLevel})`; isZoomed = true; } function resetZoom() { if (!isZoomed) return; root.style.transform = "scale(1)"; isZoomed = false; } document.addEventListener("mousemove", function (e) { mouseX = e.clientX; mouseY = e.clientY; if (isZoomed) updateOrigin(); }); // 🔥 Zoom when Shift //(e.shiftKey && e.ctrlKey)--IF YOU WANT TWO KEYS document.addEventListener("keydown", function (e) { if (e.shiftKey) { applyZoom(); } }); // 🔥 Reset if either key released //(!e.shiftKey || !e.ctrlKey) document.addEventListener("keyup", function (e) { if (!e.shiftKey) { resetZoom(); } }); document.addEventListener("contextmenu", resetZoom); document.addEventListener("mousedown", (e) => { if (!(e.shiftKey)) resetZoom(); }); window.addEventListener("blur", resetZoom); })(); ✨ What Makes This Cool? 🔹 Cursor-based dynamic transform origin 🔹 Smooth zoom transition 🔹 Safe reset handling 🔹 No dependency on frameworks 🔹 Easy to integrate in any web application ⚠️ Note This zoom applies to the entire <html> element. Test carefully in production apps, especially if you're using fixed headers, modals, or complex UI frameworks. If you’re working with Oracle APEX, this can be added in: 👉 Page → Execute when Page Loads or 👉 Dynamic Action → Execute JavaScript Code #JavaScript #WebDevelopment #OracleAPEX #FrontendDevelopment #UXDesign #APEXTips #CleanCode #DeveloperTools #LowCode #UIUX #TechTips
To view or add a comment, sign in
-
-
🔑 Prototype & Inheritance in JavaScript 1. Prototype Chain Every JavaScript object has a hidden property called [[Prototype]]. When you try to access a property that doesn’t exist on the object itself, JavaScript looks up the prototype chain to find it. Example: const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new When you use the new keyword, JavaScript creates a new object and links it to the constructor’s prototype. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const varun = new Person("Varun"); console.log(varun.greet()); // Hello, Varun 3. ES6 Classes (Syntactic Sugar) JavaScript classes are just syntactic sugar over prototype-based inheritance. They make the code cleaner and more readable, but under the hood, they still use prototypes. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. 📌 Quick Interview Tip Interviewers often ask: “Explain the prototype chain.” “What’s the difference between class inheritance and prototype inheritance?” “Why are methods added to the prototype instead of inside the constructor?” const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new Jab tum new keyword use karte ho, ek naya object banata hai jo constructor ke prototype se link hota hai. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const champ= new Person("Champ"); console.log(champ.greet()); // Hello, Champ 3. ES6 Classes (syntactic sugar) Classes JS me bas prototype-based inheritance ka cleaner syntax hain. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. #React #ReactJS #Frontend #WebDevelopment #JavaScript #Interviews #SoftwareEngineering #infy
To view or add a comment, sign in
-
🚀 20 JavaScript Snippets Tiny code, big impact. Bookmark this for your next project! 🔖 1. Flatten an array ```javascript const flatten = arr => arr.flat(Infinity); ``` 2. Check if object is empty ```javascript const isEmpty = obj => Object.keys(obj).length === 0; ``` 3. Generate random hex color ```javascript const randomHex = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,"0")}`; ``` 4. Remove duplicates from array ```javascript const unique = arr => [...new Set(arr)]; ``` 5. Capitalize first letter ```javascript const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1); ``` 6. Copy to clipboard ```javascript const copyToClipboard = text => navigator.clipboard.writeText(text); ``` 7. Get current URL params ```javascript const params = new URLSearchParams(window.location.search); ``` 8. Detect dark mode preference ```javascript const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches; ``` 9. Debounce function ```javascript const debounce = (func, wait) => { let timeout; return (...args) => { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; }; ``` 10. Wait for a set time ```javascript const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); ``` 11. Toggle boolean in state (React-friendly) ```javascript const toggle = prev => !prev; ``` 12. Sort by key ```javascript const sortBy = (arr, key) => arr.sort((a, b) => a[key] > b[key] ? 1 : -1); ``` 13. Convert RGB to hex ```javascript const rgbToHex = (r,g,b) => "#" + ((1<<24) + (r<<16) + (g<<8) + b).toString(16).slice(1); ``` 14. Validate email ```javascript const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); ``` 15. Group array by property ```javascript const groupBy = (arr, key) => arr.reduce((acc, obj) => { acc[obj[key]] = (acc[obj[key]] || []).concat(obj); return acc; }, {}); ``` 16. Get average of array ```javascript const average = arr => arr.reduce((a, b) => a + b, 0) / arr.length; ``` 17. Random item from array ```javascript const randomItem = arr => arr[Math.floor(Math.random() * arr.length)]; ``` 18. Scroll to top smoothly ```javascript const scrollToTop = () => window.scrollTo({ top: 0, behavior: 'smooth' }); ``` 19. Format number with commas ```javascript const formatNumber = num => num.toLocaleString(); ``` 20. Check if array includes all values ```javascript const includesAll = (arr, values) => values.every(v => arr.includes(v)); ``` --- ✨ Which one will you use first? 💬 Comment your favorite snippet or share one of your own! #JavaScript #WebDevelopment #CodingTips #Programming #Frontend #DeveloperTools #CodeSnippets #JS #TechTips #LearnJavaScript #SoftwareEngineering #DevCommunity 📌 Follow Sasikumar S for daily practical developer tips & hands-on learning. ❤️ Join TechVerse Collective – a daily learning community for coders growing together. 🔁 Repost to save for later & share with your network.
To view or add a comment, sign in
-
𝗪𝗲𝗹𝗹-𝗞𝗻𝗼𝘄𝗻 𝗦𝘆𝗺𝗯𝗼𝗹𝘀 𝗮𝗻𝗱 𝗧𝗵𝗲𝗶𝗿 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has evolved over time. One major update was the introduction of Symbols in ECMAScript 2015. Well-Known Symbols provide a unique way to define behavior and properties in JavaScript. To understand Well-Known Symbols, you need to know what symbols are. Before ECMAScript 2015, JavaScript did not have a way to create private object properties. Developers used tricks like prefixes or closures to manage uniqueness. The introduction of Symbols solved this problem. A Symbol is a unique identifier created using the Symbol() function. Here are some key Well-Known Symbols: - Symbol.hasInstance: customizes the instanceof operator behavior - Symbol.isConcatSpreadable: determines if an object should be flattened when using Array.prototype.concat - Symbol.iterator: defines the default iterator for an object - Symbol.match: specifies a function used for pattern matching with regex - Symbol.replace: customizes the behavior of String.prototype.replace - Symbol.search: customizes the behavior of String.prototype.search - Symbol.split: determines how String.prototype.split performs on an object You can use Symbol.hasInstance to define custom behaviors for the instanceof operator. For example: class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance) && instance.length > 0; } } You can also use Symbol.iterator to define object iteration. For example: class Fibonacci { constructor() { this.current = 0; this.next = 1; } [Symbol.iterator]() { return this; } next() { const current = this.current; [this.current, this.next] = [this.next, this.current + this.next]; return { value: current, done: false }; } } Well-Known Symbols can streamline code and improve architecture. However, they can also impact performance. Using Symbols can incur a cost, especially when abstracting data structures or heavy computational tasks. Many modern frameworks and libraries use Well-Known Symbols for internal management. For example, React and Vue use Symbols to handle component states uniquely. To debug issues with Well-Known Symbols, you can use console logging and debugging tools like Chrome DevTools. Source: https://lnkd.in/d_8if4qz
To view or add a comment, sign in
-
🔁 Javascript Conditions and Loops 🔹 Why Conditions & Loops Matter - They help your program make decisions - They let your code repeat tasks - Without them, JavaScript is useless for logic Real use cases: Login validation, Form checks, Iterating data from APIs 🧠 Conditions (Decision Making) Conditions run code only when a condition is true. ✅ if statement let age = 20; if (age >= 18) { console.log("Eligible to vote"); } - Code runs only if condition is true 🔁 if–else if (age >= 18) { console.log("Adult"); } else { console.log("Minor"); } - Two paths • One always runs 🔂 else if let marks = 75; if (marks >= 90) { console.log("Grade A"); } else if (marks >= 70) { console.log("Grade B"); } else { console.log("Grade C"); } - Multiple conditions checked in order 🔀 switch statement Used when checking one value against many cases. let day = 2; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; default: console.log("Invalid day"); } ⚠️ Always use break to avoid fall-through. 🔁 Loops (Repetition) Loops run code multiple times. 🔹 for loop Best when number of iterations is known. for (let i = 1; i <= 5; i++) { console.log(i); } 🔹 while loop Runs while condition is true. let i = 1; while (i <= 3) { console.log(i); i++; } 🔹 do–while loop Runs at least once. let i = 5; do { console.log(i); i++; } while (i < 3); 📦 Loop Control Keywords - break → stops loop - continue → skips iteration for (let i = 1; i <= 5; i++) { if (i === 3) continue; console.log(i); } ⚠️ Common Beginner Mistakes - Infinite loops - Missing break in switch - Using == instead of === - Wrong loop condition 🧪 Mini Practice Task - Check if a number is even or odd - Print numbers from 1 to 10 - Print only even numbers - Use switch to print day name ✅ Mini Practice Task – Solution 🔁 🟦 1️⃣ Check if a number is even or odd let num = 7; if (num % 2 === 0) { console.log("Even number"); } else { console.log("Odd number"); } ✅ Uses modulus operator • Remainder 0 → even • Otherwise → odd 🔢 2️⃣ Print numbers from 1 to 10 for (let i = 1; i <= 10; i++) { console.log(i); } 🔁 3️⃣ Print only even numbers from 1 to 10 for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { console.log(i); } } 📅 4️⃣ Use switch to print day name let day = 3; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; case 4: console.log("Thursday"); break; case 5: console.log("Friday"); break; default: console.log("Invalid day"); }
To view or add a comment, sign in
-
𝗖𝗼𝗿𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 & 𝗟𝗮𝗻𝗴𝘂𝗮𝗴𝗲 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀 1. What is the difference between var, let, and const? (temporal dead zone, block scoping, re-declaration, re-assignment) 2. Explain hoisting in JavaScript. How does it behave differently with var, function, let and const? 3. What are closures in JavaScript? Give a practical example where closures are useful. 4. How does the this keyword work in JavaScript? Explain its value in different contexts (global, object method, constructor, arrow function, event handler, strict mode). 5. What is the difference between == and ===? When does type coercion happen and what are some surprising coercion results? 6. Explain null vs undefined vs void 0. When would you intentionally return null vs undefined? 7. What are the different data types in JavaScript? What is the difference between primitive and reference types? 8. How can you reliably check the type of a value in JavaScript? (typeof, instanceof, Object.prototype.toString, Array.isArray, etc.) 9. What is coercion? Give examples of implicit and explicit coercion. 10. Explain the difference between ==, ===, Object.is(), and SameValueZero. 11. What is an IIFE? Why was it commonly used before let/const and modules? 12. What are arrow functions? How do they differ from regular functions (regarding this, arguments, super, constructor behavior)? 13. What are higher-order functions? Name at least 5 built-in examples. 14. Explain the difference between function declaration, function expression, and arrow function expression. 15. What is the arguments object? Why is it usually better to use rest parameters (…args) instead? 16. What is the Event Loop? Explain the call stack, task queue (macrotask), microtask queue, and rendering phase. 17. What is the difference between macrotasks and microtasks? Give examples of each. 18. Explain how setTimeout(…, 0) really works. 19. Compare setTimeout vs setInterval. When would one be preferred over the other? 20. What are Promises? Explain the states (pending, fulfilled, rejected) and the .then/.catch/.finally chain. 21. What do Promise.all, Promise.allSettled, Promise.any, Promise.race do? When would you use each? 22. How does async/await work under the hood? Is it just syntactic sugar? 23. How can you handle errors properly with async/await? (try/catch vs .catch) 24. What happens if you forget to await an async function? 25. How would you run multiple promises concurrently but still keep good error handling? For help and guidance in you carrier path https://lnkd.in/gH3paVi7 Join my dev community for resources📚, tech talks🧑🏻💻and learning 🧠 https://lnkd.in/gt8WeZSt #React #AI #Frontend #WebDevelopment #CareerGrowth #EngineeringMindset
To view or add a comment, sign in
-
"JavaScript is single-threaded" We don't call C++ or Go "single-threaded" — yet they execute in one thread by default too. Creating parallel threads requires explicit code in any language. So why do we label JavaScript this way? -- HISTORICAL CONTEXT -- In the 2000s, browsers themselves were single-process. One frozen tab = entire browser frozen. Chrome (2008) pioneered multi-process architecture. Firefox followed with Electrolysis only in 2016. The "JS is single-threaded" myth was born in that era — and stuck. -- MODERN JAVASCRIPT -- Today, JavaScript has full parallelism capabilities. Let's look at the tools. -- WEB WORKERS -- Separate threads with their own event loop. True parallel execution. const worker = new Worker('heavy-task.js'); worker.postMessage(data); worker.onmessage = (e) => console.log(e.data); Limitation: no DOM access, communication via postMessage (structured clone). -- SHARED MEMORY -- SharedArrayBuffer + Atomics enable lock-free concurrent programming: // Main thread const sab = new SharedArrayBuffer(1024); const view = new Int32Array(sab); worker.postMessage(sab); // Worker Atomics.add(view, 0, 1); // atomic increment Atomics.wait(view, 0, expectedValue); // block until changed Same memory model as C++/Rust. Race conditions included. -- WORKLETS -- Lightweight threads for specific tasks: • AudioWorklet — real-time audio processing • PaintWorklet — custom CSS painting • AnimationWorklet — off-main-thread animations -- NODE.JS -- Node.js is multithreaded out of the box. libuv thread pool: 4 threads by default (UV_THREADPOOL_SIZE, max 1024). Handles: file system, DNS, crypto. For custom parallelism: worker_threads. For multiprocessing: child_process, cluster. -- THE REAL CONSTRAINT -- DOM access is single-threaded. Not JavaScript itself. The event loop is scheduling, not a threading limitation. V8 runs on multiple threads — it just gives you one main thread by default. Same story as C++ or Go: one thread by default, explicit code for parallelism. #JavaScript #WebWorkers #NodeJS #Concurrency #Performance
To view or add a comment, sign in
-
-
🚀 JavaScript Output Challenge — Can You Guess Them All? Let’s test your core JavaScript knowledge — Event Loop, Closures, Hoisting, and Shallow Copy. 👇 Try to guess the output before running the code. 🧩 Question 1 — Event Loop + Promises + setTimeout console.log(1) const promise = new Promise((resolve) => { console.log(2) resolve() console.log(3) }) console.log(4) promise.then(() => { console.log(5) }).then(() => { console.log(6) }) console.log(7) setTimeout(() => { console.log(8) }, 10) setTimeout(() => { console.log(9) }, 0) 👉 What is the exact order of logs? 🧩 Question 2 — Spread Operator (Shallow Copy) let person = { name: "Ram", age: 29, marks: { math: 21, physics: 25 } } let person2 = { ...person } person2.name = "Shyam" person2.age = 21 person2.marks.math = 50 console.log(person, person2) 👉 Will both objects change or only person2? 🧩 Question 3 — Closure Inside Loop function test(arr, x) { var a, c = 0; for (var i = 0; i < arr.length; i++) { if (i === x) { a = function () { console.log(i, c++) } } } return a; } var t = test([1,2,3,4,5,6,7,8,9], 5) t(); t(); t(); 👉 What gets printed each time and why? 🧩 Question 4 — Hoisting + Scope Confusion var a = 10; var b = 100; function test() { a = 30; var a; console.log(a); b = 200; console.log(b); b = 300; } test(); console.log(a); console.log(b); 👉 What are the final values of a and b? 💬 Drop your answers in the comments (no cheating 😄). I’ll share detailed explanations in the next post! #JavaScript #FrontendDevelopment #WebDevelopment #InterviewPrep #JSChallenge #100DaysOfCode
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