Ever felt like JavaScript is just… pretending to be object-oriented? Like you write a function, slap a .prototype on it, and boom - suddenly it's a “class”? 😄 Now enter the "new" keyword. And this is where things get interesting. Because "new" is not just syntax. It’s doing a bunch of hidden work for you. Let’s break it down: You write this: function User(name) { this.name = name; } const user1 = new User("John"); Looks simple, right? But under the hood, JavaScript is doing FOUR steps automatically: - It creates a brand new empty object - It links that object to User.prototype - It sets this inside User to that new object - It returns the object (unless you explicitly return something else) So essentially, "new" is like your invisible assistant. Without new, you'd have to manually do all of this: const obj = {}; Object.setPrototypeOf(obj, User.prototype); User.call(obj, "John"); And honestly… nobody wants to write that every time. - new is not about “creating a class instance” - It’s about orchestrating object creation + prototype linkage + execution context JavaScript doesn’t magically become OOP. It’s still doing what it always does - just giving us a shortcut. #JavaScript #WebDevelopment #Programming #Coding
JavaScript's Hidden 'new' Keyword: Simplifying Object Creation
More Relevant Posts
-
Stop writing JavaScript like it’s still 2015. 🛑 The language has evolved significantly, but many developers are still stuck using clunky, outdated patterns that make code harder to read and maintain. If you want to write cleaner, more professional JS today, start doing these 3 things: **1. Embrace Optional Chaining (`?.`)** Stop nesting `if` statements or using long logical `&&` chains to check if a property exists. Use `user?.profile?.name` instead. It’s cleaner, safer, and prevents those dreaded "cannot read property of undefined" errors. **2. Master the Power of Destructuring** Don't repeat yourself. Instead of calling `props.user.name` and `props.user.email` five times, extract them upfront: `const { name, email } = user;`. It makes your code more readable and your intent much clearer. **3. Use Template Literals for Strings** Stop fighting with single quotes and `+` signs. Use backticks (`` ` ``) to inject variables directly into your strings. It handles multi-line strings effortlessly and makes your code look significantly more modern. JavaScript moves fast—make sure your coding habits are moving with it. What’s one JS feature you can’t live without? Let’s chat in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend #Programming
To view or add a comment, sign in
-
🚀 JavaScript Hoisting — what it actually means (with a simple mental model) Most people say: “Variables and functions are moved to the top". Even the educators on youtube (some of them) are teaching that and even I remember answering that in my first interview call. That’s not wrong… but it’s also not the full picture. Then Priya what’s really happening? JavaScript doesn’t “move” your code. Instead, during execution, it runs in two phases: 1️⃣ Creation Phase Memory is allocated Variables → initialised as undefined Functions → fully stored in memory 2️⃣ Execution Phase Code runs line by line Values are assigned 🎨 Think of it like this: Before running your code, JavaScript prepares a “memory box” 📦 Creation Phase: a → undefined sayHi → function() { ... } Execution Phase: console.log(a) → undefined a = 10 🔍 Example 1 (var) console.log(a); // undefined var a = 10; 👉 Why? Because JS already did: var a = undefined; ⚡ Example 2 (function) sayHi(); // Works! function sayHi() { console.log("Hello"); } 👉 Functions are fully hoisted with their definition. 🚫 Example 3 (let / const) console.log(a); // ❌ ReferenceError let a = 10; 👉 They are hoisted too… But stuck in the Temporal Dead Zone (TDZ) until initialised. 🧩 Simple rule to remember: var → hoisted + undefined function → hoisted completely let/const → hoisted but unusable before declaration 💬 Ever seen undefined and wondered why? 👉 That’s hoisting working behind the scenes. #javascript #webdevelopment #frontend #reactjs #programming #100DaysOfCode
To view or add a comment, sign in
-
-
💡 Short Circuiting in JavaScript — Explained Simply In JavaScript, I came across a powerful concept called Short Circuiting. 👉 In simple words: JavaScript stops checking further values as soon as the result is decided. 🔹 OR (||) Operator It returns the first TRUE (truthy) value it finds. Example: console.log(false || "Javascript"); ✔️ Output: "Javascript" Another example: console.log(false || 10 || 7 || 15); ✔️ Output: 10 👉 Why? Because JavaScript finds 10 (true value) and stops checking further values 🔹 My Practice Code 👨💻 console.log("Short circuit in OR operator"); console.log(false || "Javascript"); console.log(false || "OR Operator"); console.log(false || 3); console.log(false || 10 || 7 || 15 || 20); // short circuit in OR operator console.log(false || "Javascript - client side scripting language" || "HTML - structure of web page" || "CSS - Cascading Style Sheet" || "Bootstrap - Framework of CSS"); 🔹 Recap: ✔️ JavaScript returns the first truthy value ✔️ It does not check remaining values once result is found ✔️ This makes code faster and efficient 📌 In simple words: Short Circuiting = JavaScript stops early when result is found #JavaScript #WebDevelopment #Coding #Learning #Frontend #100DaysOfCode
To view or add a comment, sign in
-
🚀 Understanding Prototypes in JavaScript (Simple Breakdown) 🔹 Every JavaScript object has a hidden property called [[Prototype]] 👉 It links to another object and allows inheritance 💡 Why Prototypes? Instead of creating duplicate methods for every object, JavaScript shares them using prototypes → saves memory ✅ 🔹 Example: toString() isn’t inside your object, but JS finds it through the prototype chain object → prototype → null 🔗 Prototype Chain (Search Order) Check the object Check its prototype Continue up the chain Stop at null 🔹 Constructor + Prototype Functions can use prototype to share methods: function Person(name) { this.name = name; } Person.prototype.sayHello = function() { console.log("Hello " + this.name); }; ✔ Method stored once, reused by all objects 🔹 proto vs prototype prototype → belongs to constructor __proto__ → belongs to object (actual link) p1.__proto__ === Person.prototype // true 🔥 Key Takeaways ✔ JavaScript uses prototype-based inheritance ✔ Objects inherit via prototype chain ✔ Memory efficient (shared methods) ✔ Core concept for interviews & real-world JS #JavaScript #WebDevelopment #Frontend #Coding #LearnToCode #Developers
To view or add a comment, sign in
-
Clean code is not just about solving problems… it’s also about how readable your code is. In my latest blog, I covered Template Literals in JavaScript — a small feature that makes a huge difference in real-world coding. Instead of writing messy string concatenations using +, template literals help you write cleaner, more readable, and modern JavaScript. ✔️ No more unreadable strings ✔️ Easy variable embedding ✔️ Multi-line strings without headaches ✔️ Cleaner UI & API code If you're still using traditional concatenation, it's time to upgrade your approach 🚀 Read the full blog here: https://lnkd.in/gZV6uWk7 Next, I’ll be covering Array Flattening in JavaScript — a very important concept for interviews and real-world problems. #JavaScript #WebDevelopment #FrontendDevelopment #CleanCode #Coding #Developers #100DaysOfCode
To view or add a comment, sign in
-
-
Most developers use JavaScript every day… But very few truly understand how it actually executes code behind the scenes. That’s where the Event Loop comes in — the heart of JavaScript’s asynchronous behavior. At a high level: JavaScript is single-threaded. But it behaves like it can handle multiple things at once. How? Because of this powerful architecture 👇 • Call Stack → Executes synchronous code line by line • Microtask Queue → Handles Promises, async/await (high priority) • Macrotask Queue → Handles setTimeout, setInterval, I/O operations • Event Loop → Constantly checks and decides what runs next Here’s the game-changing concept: 👉 Microtasks ALWAYS run before Macrotasks That’s why: Promise resolves → runs immediately after current execution setTimeout → waits even if delay is 0 This small detail is the reason behind: • Unexpected output order • Async bugs • Performance differences • UI responsiveness If you’ve ever wondered: “Why is my code running in a different order than I expected?” The answer is almost always → Event Loop behavior Understanding this doesn’t just make you a better developer — It changes how you think about writing code. You stop guessing. You start predicting. And that’s where real engineering begins. 🚀 #JavaScript #EventLoop #AsyncJavaScript #WebDevelopment #FullStackDevelopment #Programming #SoftwareEngineering #TechDeepDive #CodingJourney JavaScript Mastery w3schools.com
To view or add a comment, sign in
-
-
Have you ever felt overwhelmed by JavaScript objects? The good news is that methods like Object.keys(), Object.values(), and Object.entries() can simplify how we interact with them. Which one do you find yourself using the most? ────────────────────────────── Demystifying Object.keys(), Object.values(), and Object.entries() Unlock the power of object methods in JavaScript with these simple techniques. #javascript #es6 #programming ────────────────────────────── Key Rules • Object.keys(obj) returns an array of the object's own property names. • Object.values(obj) returns an array of the object's own property values. • Object.entries(obj) returns an array of the object's own property [key, value] pairs. 💡 Try This const person = { name: 'Alice', age: 30, city: 'Wonderland' }; console.log(Object.keys(person)); // ['name', 'age', 'city'] console.log(Object.values(person)); // ['Alice', 30, 'Wonderland'] console.log(Object.entries(person)); // [['name', 'Alice'], ['age', 30], ['city', 'Wonderland']] ❓ Quick Quiz Q: What does Object.entries() return? A: An array of [key, value] pairs from the object. 🔑 Key Takeaway Using these methods can drastically improve your code's readability and efficiency! ────────────────────────────── Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery.
To view or add a comment, sign in
-
I stopped chasing correct answers in JavaScript today… and started chasing why I was wrong. 👇 --- 💥 Mistakes that taught me more than tutorials: ❌ Thought "onclick" supports multiple handlers 👉 It overrides—use "addEventListener" instead ❌ Confused arrow function "this" 👉 Arrow functions don’t have their own "this" ❌ Expected "var" to behave like "let" 👉 Faced hoisting and scope differences ❌ Assumed async code runs in order 👉 Learned: microtasks run before macrotasks ❌ Misunderstood "await" 👉 It pauses execution and resumes via the microtask queue ❌ Ignored shallow copy behavior 👉 Spread operator copies references, not nested objects --- 💡 Big shift: I wasn’t stuck because JavaScript is hard… I was stuck because I wasn’t questioning why. --- 🎯 What changed: ✔ I analyze outputs instead of guessing ✔ I understand how JS behaves under the hood ✔ I debug with clarity, not confusion --- 📌 Lesson: Mistakes in coding aren’t failures. They’re proof that your understanding is evolving. --- 🚀 Next focus: Closures + real-world problem solving --- If you're learning JavaScript: 👉 Which concept confused you the most? 👉 And what finally made it click? Let’s learn together 👇 #JavaScript #LearningInPublic #Frontend #CodingJourney #Debugging
To view or add a comment, sign in
-
🚀 **Day 4 – Scope Chain & Lexical Environment in JavaScript** In Day 3, we learned about Execution Context… But now the real question is: 👉 **How does JavaScript find variables when executing code?** 🤔 Let’s understand 👇 --- 💡 **What is Scope?** Scope defines **where a variable can be accessed** 👉 Simple: Scope = where is variable available ? --- 💡 **What is Scope Chain?** When JavaScript tries to access a variable: 👉 It searches in this order: * Current scope * Parent scope * Global scope 👉 This is called **Scope Chain** --- 💡 **Example:** ```js let name = "Aman"; function outer() { let city = "Indore"; function inner() { console.log(name); console.log(city); } inner(); } outer(); ``` --- 💡 **Behind the scenes:** When `inner()` runs: * looks for `name` → not in inner * goes to parent → not found * goes to global → found * looks for `city` → found in outer 👉 JavaScript climbs the **scope chain** --- 💡 **What is Lexical Environment?** 👉 It means: Scope is decided by where code is written, not where it is called --- ⚡ **Key Insight** JavaScript uses: * Scope * Scope Chain * Lexical Environment 👉 to resolve variables --- 💡 **Why this matters?** Because this is the base of: * Closures * Variable access * Debugging scope issues --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Hoisting (most misunderstood concept)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
Why I don't chain everything in JavaScript anymore Method chaining in JavaScript looks elegant at first glance. But over time, I realized it often comes with hidden costs. Long chains can: • Reduce readability • Hide unnecessary computations • Make debugging harder When everything happens in a single line, understanding what exactly went wrong becomes a challenge. Instead, I started breaking logic into small, named steps: // ❌ Harder to read & debug const result = users .filter(u => u.active) .map(u => u.profile) .filter(p => p.age > 18) .sort((a, b) => a.age - b.age); // ✅ Easier to read & maintain const activeUsers = users.filter(u => u.active); const profiles = activeUsers.map(u => u.profile); const adults = profiles.filter(p => p.age > 18); const result = adults.sort((a, b) => a.age - b.age); A simple rule I follow now: • 1–2 chain steps → 👍 totally fine • 3–4 steps → 🤔 think twice • 5+ steps → 🚩 break it down Cleaner code isn’t about writing less — it’s about making it easier to understand. What’s your take on method chaining? #javascript #webdevelopment #cleancode #frontend #programming
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