Why do people say “Everything in JS is an object” ?? Does that mean primitive datatypes like string, number, and boolean are objects too? But wait… const str = "hello" console.log(typeof str) // "string" It clearly says "string" — not "object". So where is the object? The answer is hidden in proto. If you check: str.proto You will see an object that contains all the methods we use on strings: • at() • charAt() • includes() • indexOf() • toUpperCase() • length and many more… That object is String.prototype. So what’s happening behind the scenes? When you use: "hello".toUpperCase() JavaScript temporarily wraps the primitive string into an object like this: "hello" → new String("hello") This wrapper object is linked to String.prototype, and that’s how you can access string methods. Then why is typeof "hello" not "object"? Because the actual value is still a primitive. JavaScript just gives it temporary access to an object through the prototype chain. This mechanism is called autoboxing. So when people say “Everything in JS is an object”, what they really mean is: • Objects inherit from Object.prototype • Arrays inherit from Array.prototype • Functions inherit from Function.prototype • Even primitives are linked to their wrapper prototypes • Everything (except null and undefined) connects to an object internally JavaScript is prototype-based. Check out the screenshots I attached — you’ll see the prototype object containing all string methods. "So interestingly, this also allows us to modify the methods and properties of a datatype. Because all strings are linked to String.prototype, if you change something inside that prototype, it affects every string in your application." If you want to know more about Objects in JavaScript, read this blog: https://lnkd.in/dmMDv939 #javascript #javascriptObject #chaicode #chaiaurcode
JavaScript Objects: Uncovering the Truth Behind Autoboxing
More Relevant Posts
-
Why you always should insert semicolons in JS and why JS throws unexpected "undefined". I came across a 2 funny questions about JS. 1. Why in a runtime this function throws an error and shout "Uncaught SyntaxError: Unexpected identifier 'console'"? 2. What is the "undefined" appeared afterwards? function multiply(a,b) {return a*b}; function square(n) { return multiply(n,n) }; function printSquare(n) { var squared=square(n) console.log(squared) }; printSquare(4); Well, the error appears because JavaScript uses Automatic Semicolon Insertion (ASI), but - not - everywhere. ASI only inserts semicolon when: - line breaks, - grammar would otherwise be invalid, - specific rules are met It's not the case of a function above, so node environment read it as varsquared=square(n) console.log(squared). And shouts: "What is square(n) console?" Put the semicolon - everything works fine. Always use semicolons in Node / production code. But why I'm getting "undefined"? In JavaScript if a function does not explicitly return a value, it automatically returns undefined. In my case I'm getting two outputs: from console.log(), and from REPL for function printSquare(n). So just put a return and forget about that. :) Tiny moments - yes, but they can bite unexpectedly. #JavaScript
To view or add a comment, sign in
-
-
Ever copied an object in JavaScript… and later wondered why changing one thing broke something else? I used the spread operator, Object.assign—everything looked right. The object was “copied,” features worked, and I moved on. Until one small change inside a nested object started affecting the original data. That’s when I realized copying in JavaScript isn’t as straightforward as it looks. I used to think: “If I copy an object, I get a completely separate version.” Sounds reasonable—but it misses an important detail. So I slowed down and explored what was actually happening. References. Memory locations. Nested structures. I built tiny examples, tweaked values, compared outputs—sometimes it worked, sometimes it didn’t… until patterns started to show up. And then it made sense. The issue wasn’t the syntax—it was understanding what gets copied and what still points to the same place in memory. That shift changed a lot: • I stopped assuming copies were independent • Debugging weird state changes became much easier • Spread vs structuredClone finally had a clear difference • Nested objects stopped feeling unpredictable Most importantly: 👉 A shallow copy duplicates only the top level 👉 Nested objects still share the same reference 👉 A deep copy creates a fully independent structure Now when something changes unexpectedly, I don’t guess—I check how the data was copied. Still learning, but this one concept made JavaScript feel a lot more predictable. What’s one JS concept that took you time to truly understand? #JavaScript #WebDevelopment #Frontend #LearningInPublic #JSConcepts #Debugging
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗥𝗲𝗮𝘀𝗼𝗻 𝗪𝗵𝘆 𝗧𝘆𝗽𝗲𝗼𝗳([]) 𝗥𝗲𝘁𝘂𝗿𝗻𝘀 "𝗢𝗯𝗷𝗲𝗰𝘁" You've seen this before: typeof [] // "object" You think: that's an array, why does JavaScript say it's an object? Let's look at why this happens. In JavaScript, typeof returns one of these values: -undefined- "boolean" - "number" -string- "bigint" - "symbol" -function- "object" Notice what's missing? There's no "array". This is not an accident. In JavaScript, arrays are not a separate type. When you write const arr = [], you're actually doing const arr = new Array(). Array is a constructor that creates an object. So, typeof [] returnsobject because arrays are specialized objects with: - Numeric keys - A dynamic length property - Built-in methods like map, filter, reduce For example: const arr = ["a", "b"] console.log(Object.keys(arr)) // ["0", "1"] console.log(arr.length) // 2 Internally, it behaves like an object with special behavior. In the ECMAScript spec, arrays are called “exotic objects”. Why didn't JavaScript make typeof [] return "array"? Two reasons: - Historical design: JavaScript was created in
To view or add a comment, sign in
-
💡 Pass by Value vs Pass by Reference in JavaScript (Simple Explanation) If you're learning JavaScript, understanding how data is passed is crucial 👇 🔹 Pass by Value (Primitives) When you assign or pass a primitive type (number, string, boolean, null, undefined, symbol, bigint), JavaScript creates a copy. let a = 10; let b = a; b = 20; console.log(a); // 10 console.log(b); // 20 👉 Changing b does NOT affect a because it's a copy. 🔹 Pass by Reference (Objects) When you work with objects, arrays, functions or date objects, JavaScript passes a reference (memory address). let obj1 = { name: "Ali" }; let obj2 = obj1; obj2.name = "Ahmed"; console.log(obj1.name); // Ahmed console.log(obj2.name); // Ahmed 👉 Changing obj2 ALSO affects obj1 because both point to the same object. 🔥 Key Takeaway Primitives → 📦 Copy (Independent) Objects → 🔗 Reference (Shared) 💭 Pro Tip To avoid accidental changes in objects, use: Spread operator {...obj} Object.assign() Understanding this concept can save you from hidden bugs in real-world applications 🚀 #JavaScript #WebDevelopment #Frontend #Programming #CodingTips
To view or add a comment, sign in
-
Why do some functions return another function(s) if we can just call the function whenever we need it? At first this feels unnecessary. If a function can already run when we call it, why would we want that function to return another function instead of just executing the logic immediately? The reason is that sometimes we want to create a function that remembers certain information for later use. Instead of passing the same data again and again every time we call a function, we can create a function that already remembers that data and uses it whenever it runs. So in some cases we are not just executing a function — we are creating a new function that carries some context with it. This behavior leads us to an important concept in JavaScript called Closures. A closure happens when a function remembers variables from the scope where it was created, even after that outer function has finished executing. Normally, when a function finishes running, its local variables should disappear. But if another function still references them, JavaScript keeps those variables alive. Closures are widely used in JavaScript for things like: • Creating private variables • Preserving state between function calls • Avoiding unnecessary global variables • Remembering configuration values • Supporting callbacks and asynchronous code In the example attached below, you can see how a function is able to access a variable that technically belongs to an outer scope. This happens because of lexical scoping, where a function remembers the environment in which it was created. Closures might seem like a small concept, but they explain many important patterns in JavaScript. A function in JavaScript doesn’t just carry its code. It also carries the environment where it was created. #javascript #closures #chaicode #chaiaurcode
To view or add a comment, sign in
-
-
If you still don’t fully understand how objects work in JavaScript, this code might look strange: ``` const pet1= { name: "cat" } const pet2 = pet1 console.log(pet1===pet2) // true ``` Now look at this other case: const pet1 = { name:"cat" } const pet2 = { name:"cat" } console.log(pet1 === pet2) // false Both objects have exactly the same content, but JavaScript says they are different. Why does this happen? To understand this, we need to remember the feared pointers that many people probably saw in college when they were struggling with some low-level language. When you create an object, JavaScript stores it somewhere in memory. And when you assign this object to another variable, it does not copy the value, it just makes the new variable, instead of having its own object, point to the address of the object it copied. In practice, pet1 and pet2 are the same thing :o Bringing this to our examples: In the first code: ``` // Here JavaScript creates an object in memory constpet1= { name: "cat" } // Here NO copy is created // pet2 points to the same object as pet1 constpet2=pet1 // The comparison is true because both point // to the same place in memory console.log(pet1===pet2) // true ``` In the second example: ``` const pet1 = { name: "cat" } // Here a NEW value is allocated in memory for pet2 const pet2 = { name: "cat" } // This comparison is false because pet1 and pet2 // have different memory addresses console.log(pet1 === pet2) // false ``` Even if the data is the same, JavaScript does not compare the content of the objects, it compares if they are the same object in memory.
To view or add a comment, sign in
-
-
const variables cannot change. So why does this code print 0, 1, 2? When I first learned JavaScript, one thing confused me a lot. We all know: const → cannot be reassigned. But then in real projects I kept seeing this: for (let i = 0; i < 3; i++) { const value = i; console.log(value); } And the output becomes: 0 1 2 Wait… if const cannot change, how is the value changing every loop? The interesting part — it actually doesn’t change. Each loop iteration creates a new block scope, which means a new value variable is created every time. So JavaScript is not updating the same variable. It’s creating a completely new one in each iteration. Understanding this made several JavaScript concepts click for me: var • Function scoped • Hoisted and initialized with undefined • Can be reassigned and redeclared let • Block scoped • Hoisted but trapped in the Temporal Dead Zone (TDZ) until initialization • Can be reassigned but not redeclared const • Block scoped • Also lives in the TDZ • Must be initialized during declaration • Cannot be reassigned This is why most developers prefer using const by default: ✅ Prevents accidental reassignment ✅ Makes code easier to reason about ✅ Keeps variables predictable in larger codebases Only switch to let when reassignment is actually needed. Small JavaScript details like this often look simple… until you start thinking about how they actually work. I want to know which JS behavior made you go “Wait… what?!” the first time you saw it?
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀 𝗼𝗳 𝗔𝗿𝗿𝗼𝘄 𝗙𝘂𝗻𝗰𝗍𝗶𝗼𝗻𝘀 You've seen the => symbol in JavaScript code. It's called an Arrow Function. - Makes your code look sleeker - Reduces "boilerplate" code Let's look at an example: squaring a number. You can write it like this: const square = function(n) { return n * n; }; Or like this: const square = (n) => { return n * n; }; We removed the word "function" and added => after the parameters. If your function only needs one parameter, you can drop the parentheses. const square = n => { return n * n; }; If your function needs more than one parameter, you add the parentheses back. const multiply = (a, b) => { return a * b; }; console.log(multiply(5, 4)); // Output: 20 The coolest part of Arrow Functions is Implicit Return. If your function only has one line of code, you can throw away the curly braces and the return keyword. const add = (a, b) => a + b; Arrow functions are perfect for methods like map(). Check an array of numbers and return if they are "Even" orOdd.const numbers = [1, 2, 3, 4]; const checkNumbers = numbers.map(num => num % 2 === 0 ? "Even : Odd"); console.log(checkNumbers); // ["Odd", "Even", "Odd", "Even"] Arrow functions make your code shorter, easier to read, and more expressive. They help you write functions quickly and make your code easier for other developers to understand. Source: https://lnkd.in/gh_-Skrh
To view or add a comment, sign in
-
🚀 JavaScript Variables (var, let, const) & Hoisting. Before JavaScript executes your code… Have you ever wondered where variables are stored? 🤔 🧠 What is a Variable? A variable is a named container used to store data. ⚙️ JavaScript gives us 3 ways to declare variables: var a = 10; let b = 20; const c = 30; 🧠 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 In simple words: You can access variables and functions even before they are initialized. 📦 Example with var: console.log(x); // undefined var x = 5; 🚫 Example with let: console.log(y); // ❌ ReferenceError let y = 10; 🔒 Same with const: console.log(z); // ❌ ReferenceError const z = 15; 🎯 Key Differences: • var → hoisted + initialized (undefined) • let & const → hoisted but NOT initialized (Temporal Dead Zone) 👉 “In the next post, we’ll dive into Scope — the concept that truly defines how variables behave in JavaScript.” #JavaScript #WebDevelopment #Frontend #Coding
To view or add a comment, sign in
-
🔍 Prototypes and this in JavaScript — going beyond the syntax into the actual mechanics. Here's what's worth knowing: 🧬 On Prototypes Methods aren't copied to every object instance. They live once on the prototype — all instances share them via reference. That's how JS stays memory efficient even with thousands of objects. Every method lookup is a live chain traversal, every single time. Object.create is pure prototype wiring — it sets the [[Prototype]] of a new object. That's it. 🎯 On this — four rules, in priority order 1️⃣ new binding → this = newly created object 2️⃣ Explicit binding → .call() .apply() .bind() — you decide 3️⃣ Implicit binding → obj.method() — this = object left of the dot 4️⃣ Default binding → standalone call — this = window or undefined Arrow functions sit outside all four rules — they inherit this lexically from wherever they were defined. ⚠️ The classic trap js setTimeout(this.log, 1000); // this is lost Detach a method from its object and this evaporates. Fix → arrow wrapper, .bind(), or bind in the constructor. Each has different tradeoffs. 🧠 On EventEmitters and memory Per-instance state must always be initialized in the constructor. If it accidentally lands on the prototype — every instance shares the same object. Emitting on one instance fires callbacks registered on all instances. Silent. No error thrown. Every .on() listener holds a closure reference — keeping objects alive in memory long after they're "destroyed." Always implement .off(). Always clean up. Follow along — sharing one deep dive at a time. 🚀 #JavaScript #Prototypes #FrontendEngineering #WebPerformance #PlatformEngineering
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