Day-4 var vs let vs const (JavaScript) Why did JavaScript introduce let and const? 🤔 Because var had some serious problems. 🔹 1️⃣ Scope if (true) { var x = 10; let y = 20; const z = 30; } console.log(x); // ✅ 10 console.log(y); // ❌ ReferenceError console.log(z); // ❌ ReferenceError 👉 var → function scoped 👉 let & const → block scoped 🔹 2️⃣ Hoisting Behavior console.log(a); // undefined var a = 10; console.log(b); // ❌ ReferenceError let b = 20; 👉 var is hoisted & initialized as undefined 👉 let / const are hoisted but in Temporal Dead Zone 🔹 3️⃣ Re-declaration & Re-assignment var p = 1; var p = 2; // ✅ allowed let q = 1; // let q = 2; ❌ not allowed const r = 1; // r = 2; ❌ not allowed 👉 var → re-declare & re-assign 👉 let → re-assign only 👉 const → neither 🔹 4️⃣ Best Practices ✅ Use const by default ✅ Use let when value changes ❌ Avoid var in modern JavaScript #WebDevelopment #JavaScript #VarLetConst #FrontendDevelopement #BestPractices
JavaScript var vs let vs const: Understanding Scope, Hoisting, and Best Practices
More Relevant Posts
-
What is Hoisting in JavaScript? Hoisting is JavaScript's default behavior of moving variable and function declarations to the top of their scope before execution. This means you can sometimes use variables or functions before they are declared in the code. 1️⃣ Variable Hoisting with var console.log(a); // undefined var a = 10; Behind the scenes, JavaScript interprets it like this: var a; console.log(a); // undefined a = 10; 👉 The declaration is hoisted, but not the assignment. 2️⃣ Hoisting with let and const console.log(a); // ❌ ReferenceError let a = 10; Variables declared with let and const are hoisted but placed in the Temporal Dead Zone (TDZ), meaning they cannot be accessed before initialization. 3️⃣ Function Hoisting Function declarations are fully hoisted. greet(); function greet() { console.log("Hello JavaScript"); } This works because the entire function definition is hoisted. #javascript #webdevelopment #frontenddeveloper #mernstack #codinginterview #softwareengineering
To view or add a comment, sign in
-
📊 Day 9 – Poll Answer & Explanation console.log(1 < 2 < 3); console.log(3 > 2 > 1); 🧠 Concept: Type Coercion & Comparison Evaluation in JavaScript In JavaScript, comparisons are evaluated **from left to right**. When a **boolean** is used in another comparison, JavaScript converts it to a **number**. true → 1 false → 0 🔍 Step-by-step explanation ✅ First Expression 1 < 2 < 3 Step 1 1 < 2 ✔️ true Step 2 true < 3 true → 1 1 < 3 ✔️ true Output: true ⚠️ Second Expression 3 > 2 > 1 Step 1 3 > 2 ✔️ true Step 2 true > 1 true → 1 1 > 1 ❌ false Output: false 🖨️ Final Output true false 🎯 Key Takeaway JavaScript **does not support chained comparisons like math**. 3 > 2 > 1 is evaluated as: (3 > 2) > 1 true > 1 1 > 1 false 💡 Tip: Use logical AND for correct comparison. console.log(3 > 2 && 2 > 1); // true #JavaScript #JSConcepts #TypeCoercion #TrickyQuestions #Frontend #PollAnswer
To view or add a comment, sign in
-
📊 Day 8 – Poll Answer & Explanation const obj = { a: "foo", b: function () { console.log(this.a); }, }; const c = obj.b; obj.b(); c(); 🧠 Concept: this binding in JavaScript In JavaScript, this is determined by how a function is called, not where it is defined. 🔍 Step-by-step explanation ✅ Method call obj.b(); b is called using the object So this refers to obj this === obj this.a // "foo" ✔️ Output: foo ⚠️ Function reference const c = obj.b; Only the function reference is copied The object context is lost ❌ Normal function call c(); Called as a regular function this points to: window (browser, non-strict mode) undefined (strict mode) this.a // undefined ❌ Output: undefined 🖨️ Final Output foo undefined 🎯 Key Takeaway this depends on the call-site, not the function definition. When a method is assigned to a variable and called, it loses its object context. 💡 Tip: Use bind, call, or apply if you want to preserve this. const c = obj.b.bind(obj); c(); // foo #JavaScript #ThisKeyword #JSConcepts #TrickyQuestions #Frontend #PollAnswer
To view or add a comment, sign in
-
JavaScript Tip 💡: Use the Array "at()" method to access last Array element easily! The "at()" method in JavaScript provides a simpler way to access elements in an array, especially the last one. Traditionally, getting the last element required using arr[arr.length - 1], but .at(-1) now handles this directly and more cleanly. With "at()", positive indices retrieve elements from the start, while negative indices count backward from the end. This makes .at(-1) a straightforward and readable alternative for accessing the last item in an array. Hope this helps ✅️ Do Like 👍 & Repost 🔄 #html #css #javascript #typescript #react
To view or add a comment, sign in
-
Because events in JavaScript ""bubble"" up the DOM tree, you can attach a single event listener to the parent container and use event.target to figure out which child was clicked. JavaScript // Attach ONE listener to the parent <ul> document.getElementById('item-list').addEventListener('click', (event) => { // Check if the clicked element was a button if (event.target.tagName === 'BUTTON') { const itemId = event.target.dataset.id; console.log(`Item ${itemId} clicked!`); } }); This uses drastically less memory and automatically handles new items added to the list dynamically—no need to attach new listeners when the DOM updates! #JavaScript #WebPerformance #CodingInterviews #FrontendDev #TechTips"
To view or add a comment, sign in
-
-
Just finished building a Metric/Imperial Unit Converter (HTML, CSS, JavaScript). Live demo: https://lnkd.in/dpzCZvHR Git repo: https://lnkd.in/dMKr56_d Repo: https://lnkd.in/dMKr56_d For this project, I focused on: - Clean separation between structure (HTML), styling (CSS), and logic (JavaScript) - DOM manipulation and event handling - Input validation and reset functionality - Writing conversion logic in a simple, readable way What I liked most was implementing the JavaScript logic - debugging and refining the behavior until everything worked as expected. Small project, but solid step forward. #code #scrimba #javascript #html #css
To view or add a comment, sign in
-
-
Today I practiced generating my checkout page dynamically using JavaScript. Instead of writing all the HTML manually, I used JavaScript to create the elements and display products on the page. It made me realize how powerful the DOM is when building real applications. I also fixed a small but confusing bug with radio buttons. When I selected an option for one product, it affected other products too. I learned that radio buttons are grouped by their "name" attribute — so each product needs its own unique name. What I learned today: JavaScript can build your entire UI dynamically. Small bugs usually teach big lessons. Understanding how things work is more important than just making them work. Slowly but surely improving every day. #Day4OfTakingJavaScriptSeriously The radio selector input is the circle with black dot inside
To view or add a comment, sign in
-
-
Yesterday poll answer and explanation console.log([2] == [2]); // false 👀 In JavaScript arrays are objects (reference types). So, when both sides are objects (reference types), JavaScript does not compare their values. Instead, it compares their memory references. console.log([2] == 2); // true 🤯 So here, left operand is an object (reference type) and right operand is a (primitive type) is number. In this case, type coercion happens. The reference type is first converted into a primitive. [2].toString() // "2" and it becomes "2" == 2 With ==, JavaScript converts string to number: Number("2") == 2, It becomes 2 == 2 So the final output is, false, true Hope this explanation is helpful to someone 😊 #JavaScript #FrontendDeveloper #WebDevelopment #LearningJavaScript #InterviewPrep
To view or add a comment, sign in
-
📚 Today I Learned: Scope Chain in JavaScript The scope chain in JavaScript is used to resolve variable values. When a variable is used, JavaScript looks for it in a specific order. 🔹 How it works: 1️⃣ JavaScript first checks the current scope. 2️⃣ If the variable is not found, it checks the outer (parent) scope. 3️⃣ This process continues until it reaches the global scope. 💻 Example: let a = 10; function outer() { let b = 20; function inner() { let c = 30; console.log(a, b, c); } inner(); } outer(); ✅ The inner() function can access c, b, and a because of the scope chain. #javascript #webdevelopment #frontenddeveloper #learninginpublic
To view or add a comment, sign in
-
Parser-blocking JavaScript is often an overlooked issue in frontend performance. When the browser encounters a synchronous <script> tag: • HTML parsing pauses • DOM construction stops • Script executes • Rendering is delayed This issue can easily be missed, but it is measurable in DevTools. I conducted an experiment, recorded the Performance trace, and documented how using defer alters the entire timeline. The difference is immediate and visible. #WebPerformance #JavaScript #FrontendDevelopment #HTML
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