JavaScript’s hidden magic tricks Did you know JavaScript secretly helps your primitives behave like objects? Ever wondered how this works? 👇 "hello".toUpperCase(); // "HELLO" (42).toFixed(2); // "42.00" true.toString(); // "true" Wait a second… A string, a number, and a boolean — all have methods? But these are primitive values, not objects! So how can they call methods like .toUpperCase() or .toFixed()? 💡 The Secret: Temporary Wrapper Objects When you try to access a property or method on a primitive, JavaScript automatically creates a temporary object — a process called autoboxing. Here’s what happens behind the scenes const str = "hello"; // Step 1: JavaScript wraps it const temp = new String(str); // Step 2: Calls the method on that temporary object const result = temp.toUpperCase(); // Step 3: Discards the wrapper temp = null; console.log(result); // "HELLO" So, "hello" behaves like an object for a moment — but it’s still a primitive! ✅ typeof "hello" → "string" ❌ "hello" instanceof String → false Why this matters It keeps primitives lightweight and fast. You can safely call methods on them. But don’t confuse them with their object counterparts created using new: const s = new String("hello"); // actual object typeof s; // "object" s instanceof String → true #JavaScript #Tricks
How JavaScript makes primitives behave like objects
More Relevant Posts
-
Have you ever tried sorting numbers in JavaScript and it just gives you nonsense? 😒 Like, you do [200, 100, 5].sort() and it returns [100, 200, 5] That’s because JavaScript, by default, sorts everything as strings, not actual numbers. So it’s basically going, “Hmm, 100 starts with a 1, that must come first.” To fix that and sort numbers properly in ascending order (smallest to biggest), just add a compare function: array.sort((a, b) => a - b) This basically tells JavaScript to compare each pair of values in the array by subtracting one from the other. If the result is negative, it means a is smaller than b, so JavaScript keeps a before b. If the result is positive, b is smaller, so it gets placed before a. And if the result is zero, it means they’re equal, and the order stays the same. This allows the sort method to arrange the numbers from smallest to largest unlike the default .sort() which treats numbers like strings and messes up the order. Now if you want to sort in descending order (biggest to smallest), just flip it: array.sort((a, b) => b - a) Sorting in descending order is especially useful when you're dealing with scores, prices, rankings, or anytime the biggest number should be on top. Once you understand what a and b are doing in that function, sorting becomes super easy and honestly, kind of satisfying. You can even write your own custom sort function which you can call anytime you want to sort anything in your program. Checkout my custom sort function in the image below and tell me what you think. I made it to work in thesame way as the sort() method. The code snippet will give you an understanding of what happens under the hood when you use the sort() method. Make sure you check it out. I hope you have learnt something from this post😃
To view or add a comment, sign in
-
-
JavaScript Block-Level Variables JavaScript ES6 introduced block-level scoping with the let and const keywords. Block-level variables are accessible only within the block {} they are defined in, which can be smaller than a function's scope. For example, function display_scopes() { // declare variable in local scope let message = "local"; if (true) { // declare block-level variable let message = "block-level"; console.log(`inner scope: ${message}`); } console.log(`outer scope: ${message}`); } display_scopes(); Output inner: block-level outer: local In this example, we have created two separate message variables: Block-Level: The variable inside the if block (visible only there). Local-Level: The variable inside the display_scopes() function.
To view or add a comment, sign in
-
-
Mastering JavaScript map(): Hidden Pitfalls and Smarter Patterns JavaScript’s Array.prototype.map() is simple on the surface yet surprisingly deep once you inspect how callbacks, types, coercion, and encoding work under the hood. One of the most infamous examples — [1,2,3].map(parseInt) — looks harmless but produces confusing output that often appears in interviews. This guide breaks everything down clearly: how map() really works, why parseInt misbehaves, how NaN is detected, how wrapper objects make "text".length possible, and why emoji “length” is unintuitive. Each section includes modern examples and best-practice patterns. map() Actually Works 1.1 Syntax and Basic Behavior map() creates a brand-new array using your callback’s return values. The original array is never modified. const transformed = sourceList.map( (itemValue, itemPosition, originalList) => { return /* computed value */; }, optionalThisArgument ); const baseNumbers = [2, 5, 10]; const doubledValues = baseNumbers.map(num => num * 2); console.log(doubledValu https://lnkd.in/gbec6TSU
To view or add a comment, sign in
-
Mastering JavaScript map(): Hidden Pitfalls and Smarter Patterns JavaScript’s Array.prototype.map() is simple on the surface yet surprisingly deep once you inspect how callbacks, types, coercion, and encoding work under the hood. One of the most infamous examples — [1,2,3].map(parseInt) — looks harmless but produces confusing output that often appears in interviews. This guide breaks everything down clearly: how map() really works, why parseInt misbehaves, how NaN is detected, how wrapper objects make "text".length possible, and why emoji “length” is unintuitive. Each section includes modern examples and best-practice patterns. map() Actually Works 1.1 Syntax and Basic Behavior map() creates a brand-new array using your callback’s return values. The original array is never modified. const transformed = sourceList.map( (itemValue, itemPosition, originalList) => { return /* computed value */; }, optionalThisArgument ); const baseNumbers = [2, 5, 10]; const doubledValues = baseNumbers.map(num => num * 2); console.log(doubledValu https://lnkd.in/gbec6TSU
To view or add a comment, sign in
-
🔄 JavaScript Type Conversion — Turning One Type Into Another! 😎 In JavaScript, Type Conversion means changing a value from one data type to another — for example, from a string to a number, or from a number to a string. There are two main types of conversions you should know 👇 --- ⚙️ 1. Implicit Conversion (Type Coercion) JavaScript does this automatically when needed. Example: console.log("5" + 2); // "52" → number turns into string console.log("5" - 2); // 3 → string turns into number 🧠 JS tries to “help” you by converting types automatically — but sometimes this can cause surprises! 😅 --- ⚙️ 2. Explicit Conversion (Manual Conversion) You do it yourself using functions or methods. Examples: Number("10"); // Converts string to number → 10 String(20); // Converts number to string → "20" Boolean(0); // Converts number to boolean → false ✅ More reliable because you control when and how it happens. --- 💬 Quick Tip: Use typeof to check what type your value currently is 👇 typeof "Hello" // "string" typeof 42 // "number" --- 💡 In Short: Type conversion helps your program stay flexible and smart — but always be aware of how JavaScript converts things behind the scenes! #JavaScript #CodingTips #WebDevelopment #JSBeginners #LearnJS #Frontend
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting — “It’s not magic, it’s just how JS works!” ✨ Ever seen your code work even before you declared a variable or function? That’s not sorcery, that’s Hoisting 😎 ⸻ 🧠 What is Hoisting? In simple terms — JavaScript moves declarations (not initializations) to the top of their scope before execution. Let’s see how 👇 ⸻ 🧩 Example 1: var is hoisted but initialized as undefined console.log(name); // ❓ undefined var name = "Vivek"; Behind the scenes: var name; console.log(name); // undefined name = "Vivek"; 🧠 JS declares the variable first, then runs your code line by line. ⸻ 🧩 Example 2: let and const are hoisted too — but they live in the ⚠️ Temporal Dead Zone console.log(age); // ❌ ReferenceError let age = 25; They’re hoisted but not initialized, so you can’t access them before the declaration line. ⸻ 🧩 Example 3: Functions get fully hoisted! sayHello(); // ✅ Works fine! function sayHello() { console.log("Hello World!"); } 🧠 Function declarations are hoisted with their definitions, while function expressions are not: greet(); // ❌ TypeError var greet = function() { console.log("Hi!"); }; ⸻ 💬 Pro Tip: Always declare your variables before using them — not because you have to, but because your future self will thank you later 😅 ⸻ #JavaScript #WebDevelopment #Frontend #CodingTips #ReactJS #Hoisting
To view or add a comment, sign in
-
-
The infamous {this} keyword in JavaScript is one that we all struggle with. after a lot of fighting with this keyword to understand, I finally cracked it! 😁 Basically, the This keyword points to the object but with exceptions and there are a lot of other small quirks. In the global scope or just in the document, adding This, will reference the Global object. that object will be the window object if you're working with normal frontend Javascript. in Node, it refers to module.exports. Inside of an object, it will reference its object. Inside of a function, will reference the global object once again. but if inside an object, that it will reference that object. Arrow function don't take This keyword, but when referenced, it will refer to the object of its scope. Inside of a constructor, however, it will reference a new object instantiated from the constructor. we use it to create new methods to use inside the new object. In strict mode, {this} becomes undefined in the global scope. so it will not refer to either window or module.exports. so you can only use {this} within context only. to refer to a local object, or use it for instantiation. 🫡
To view or add a comment, sign in
-
-
Going back to basics 🌱 How Javascript executes your code inside the JS Engine ? Let’s say you have a "landing page" that needs a bit of interactivity maybe a "button click". So, you add a JavaScript file to make it all work smoothly. Now, these are are steps that will occure behind the scene - 1. The "Javascript engine" first reads your code from top to bottom, checking if there are any "syntax errors". Then it converts the code into a structured format called an "Abstract Syntax Tree (AST)" basically something the computer can understand. 2. Interpretation : This is where the Javascript engine’s interpreter (like "Ignition" in Chrome’s V8 engine) turns your code into "bytecode" for faster execution. (No need to stress about these , just know this step helps your code run faster, we will explore it more later.) 3. Optimization (JIT) : If you remember, we already discussed "Just-in-time (JIT)" Compilation in an earlier post that’s exactly what happens here. While your page is running, the Javascript engine keeps an eye on which parts of your code run frequently for example, a function that executes every time a button is clicked. When it notices such patterns, the JIT Compiler steps in and converts those parts into machine code, so the next time they run, it happens much faster. 4. Execution : Now, whenever you interact with your page like "clicking a button", the engine runs the already optimised machine code directly. That’s how things happen when you add Javascript to your page. But...but..but , if there is no Javascript file, will the JavaScript engine still work???? #Javascript #Frontend
To view or add a comment, sign in
-
-
🚀 JavaScript Lesson: Understanding Hoisting Ever wondered why you can use a variable before it’s declared in JavaScript? That’s because of Hoisting — one of the most misunderstood concepts in JS! 🧠 What is Hoisting? Hoisting means JavaScript moves declarations (not assignments) to the top of their scope during the compilation phase. In simple terms — JS reads your code twice: First pass: Sets up memory for variables and functions. Second pass: Executes line by line. 🧩 1️⃣ var Hoisting Example console.log(a); // 👉 undefined var a = 10; console.log(a); // 👉 10 📝 Explanation: var a is hoisted to the top, but only the declaration, not the assignment. So, before assigning, a exists but has the value undefined. 🧩 2️⃣ let Hoisting Example console.log(b); // ❌ ReferenceError let b = 20; 📝 Explanation: let is also hoisted, but it stays in a Temporal Dead Zone (TDZ) — meaning you can’t access it before it’s declared. This protects you from accidental use of uninitialized variables. 🧩 3️⃣ const Hoisting Example console.log(c); // ❌ ReferenceError const c = 30; 📝 Explanation: Like let, const is hoisted but locked in the TDZ until its declaration line. It also must be initialized at the time of declaration. 🧩 4️⃣ Function Hoisting greet(); // ✅ Works! function greet() { console.log("Hello, Cognothink Community!"); } 📝 Explanation: Function declarations are fully hoisted — both name and body. That’s why you can call them before they’re defined. ⚡ Function Expressions (with var, let, or const) sayHi(); // ❌ Error var sayHi = function() { console.log("Hi!"); }; 📝 Explanation: This behaves like variable hoisting — only the variable name is hoisted, not the function itself.
To view or add a comment, sign in
-
Announcing Attractive.js, a new JavaScript-free JavaScript library This article was originally published on Rails Designer After last week's introduction of Perron, I am now announcing another little “OSS present”: a JavaScript-free JavaScript library. 🎁 Say what? 👉 If you want to check out the repo and star ⭐ it, that would make my day! 😊 Attractive.js lets you add interactivity to your site using only HTML attributes (hence the name attribute active). No JavaScript code required. Just add data-action and, optionally, data-target attributes to your elements, and… done! Something like this: <button data-action="addClass#bg-black" data-target="#door"> Paint it black </button> <p id="door"> Paint me black </p> Or if you want to toggle a CSS class, you write: data-action="toggleClass#bg-black". Or toggle multiple CSS classes: data-action="toggleClass#bg-black,text-white". Other actions include addAttribute, form#submit and copy#my-api-key. Attractive, right? 😅 I designed Attractive.js to be a little sister of Stimulus, hence the similar data-* https://lnkd.in/gifb59x9
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