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.
Understanding Block-Level Variables in JavaScript ES6
More Relevant Posts
-
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
To view or add a comment, sign in
-
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
-
-
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
-
-
Day - 37 (Web development) Finally Decode JavaScript’s this Keyword: Master call, apply, and bind for Advanced Control 🧠 The this keyword is the most common source of confusion in JavaScript, and interviewers love to test on it. It’s not a static variable; its value is dynamically determined by how a function is called, not where it is defined. Mastering this is the critical step to graduating from writing simple scripts to building complex, reliable applications, especially when dealing with object methods, event listeners, and module exports. This masterclass provides the definitive framework for understanding this in any context and then introduces the three powerful methods—call, apply, and bind—that give you complete control over its binding. The Foundational Learning: The Four Rules of this The turning point for mastering this is understanding its four binding rules. Forget where the function is written; focus on the context of its execution: Default Binding (Global/Window): In non-strict mode, if a function is called without any surrounding context (e.g., a simple function call like greet()), this points to the global object (window in a browser). In Strict Mode, it points to undefined. Implicit Binding (Object Method): If a function is called as a method of an object (e.g., user.greet()), this points to the owner of the function call, which is the user object. New Binding (Constructor): If a function is called with the new keyword (e.g., new User()), this points to the newly created object instance. Explicit Binding (Call, Apply, Bind): This is where you manually force the value of this using one of the three binding methods. Taking Control: The Power of Explicit Binding The video then dives into the crucial techniques for manually setting the this context, which are frequently used in advanced frameworks and libraries: call(): Executes a function immediately, setting the value of this to the first argument, and passing any remaining arguments individually. (e.g., func.call(thisObject, arg1, arg2)). apply(): Executes a function immediately, setting the value of this to the first argument, and passing any remaining arguments as a single array. (e.g., func.apply(thisObject, [arg1, arg2])). bind(): Creates a brand new function with the this context permanently set to the provided argument. The original function is not executed immediately; the new function can be called later. Mastering the rules of this and wielding the power of call, apply, and bind is essential for writing flexible, reusable code and for confidently crushing your next technical interview. Watch the full masterclass and finally conquer the this keyword: https://lnkd.in/d-EmveGq #JavaScript #ThisKeyword #CallApplyBind #WebDevelopment #CodingInterview #DeveloperSkills #TechEducation
JavaScript this Keyword Explained | Call, apply, bind | Javascript Full Course #22
https://www.youtube.com/
To view or add a comment, sign in
-
Most JavaScript developers know how to write functions—but struggle to understand how they actually behave. Why does this change inside callbacks? Why do arrow functions “fix” scope issues? Why can some functions run before they're written? Our latest deep dive explains it clearly by breaking down: • Function Declarations vs Function Expressions • How hoisting really works • Arrow functions and lexical this • Arguments object differences • Real-world mistakes and best practices • When to use which function type If JavaScript ever felt unpredictable, this guide will permanently fix that. https://lnkd.in/dXcAjYqA #JavaScript #WebDevelopment #CodingTips #FrontendDevelopment #LearnJavaScript #ProgrammingBasics #DevCommunity #SoftwareEngineering
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
-
-
Templates in JavaScript: JavaScript Feature Spotlight: Template Literals & Tagged Templates Writing clean and dynamic strings in JavaScript has never been easier! Let’s explore Template Literals and Tagged Templates. Template Literals Template literals use backticks (`) to embed variables and expressions directly inside strings: const name = "Sameer"; console.log(`Hello, ${name}! Welcome to LinkedIn.`); // Hello, Sameer! Welcome to LinkedIn. No more messy concatenation with +! Tagged Templates Tagged templates give you more power—they allow a function to process a template literal before outputting it. function highlight(strings, name) { return `${strings[0]} **${name}**!`; } const name = "Sameer"; console.log(highlight`Hello, ${name}`); // Hello, **Sameer**! Perfect for custom formatting, localization, or security (like sanitizing inputs). Pro Tip: Tagged templates are underused but incredibly powerful for building dynamic and safe strings in your apps. #JavaScript #WebDevelopment #Frontend #TemplateLiterals #TaggedTemplates #CodingTips #CleanCode #DevCommunity
To view or add a comment, sign in
-
What is JSX and how is it converted into JavaScript? JSX: Syntax extension for JavaScript, mainly used with React. HTML in JS: Allows writing HTML-like code inside JavaScript for easier readability and maintenance. Expressions: Embed JavaScript expressions in JSX using {}. Example of JSX: The name written in curly braces { } signifies JSX const name = "Learner"; const element = ( <h1> Hello, {name}.Welcome to Rajshahi . </h1> ); Browsers can’t understand JSX directly. Instead, tools like Babel transpile it into plain JavaScript using React.createElement(). const element = <h1>Hello, Rajshahi!</h1>; Babel converts it into: const element = React.createElement("h1", null, "Hello, World!");
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