#js #7 **Function Declaration vs Function Expression in JavaScript** 🔹 Function Declaration Definition: A function declaration defines a named function using the function keyword. function greet() { console.log("Hello"); } ✅ Features: Must have a name Hoisted (can be called before it is defined) Declared as a separate statement Example (Hoisting): greet(); // works function greet() { console.log("Hello"); } 🔹 Function Expression Definition: A function expression is when a function is assigned to a variable. const greet = function () { console.log("Hello"); }; ✅ Features: Can be anonymous (no name) Not hoisted (cannot be used before definition) Treated like a value Example: greet(); // ❌ Error const greet = function () { console.log("Hello"); } #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
Function Declaration vs Function Expression in JavaScript: Hoisting and Naming
More Relevant Posts
-
#js #12 **What is Scope and Scope Chain in Javascript** 🧠 1. What is Scope? 👉 Scope means: Where a variable can be accessed in your code 📦 Types of Scope 🔹 1. Global Scope 👉 Variables declared outside any function let a = 10; function test() { console.log(a); } test(); // 10 ✔ a is accessible everywhere 🔹 2. Function Scope 👉 Variables declared inside a function function test() { let b = 20; console.log(b); } test(); // console.log(b); ❌ Error ✔ b is only accessible inside test() 🔹 3. Block Scope 👉 Variables declared with let and const inside {} { let c = 30; const d = 40; } // console.log(c); ❌ Error ✔ Only accessible inside the block 🎯 Simple Understanding 👉 Scope = visibility of variables 🔗 2. What is Scope Chain? 👉 Scope Chain means:When JavaScript looks for a variable, it searches from inside → outside → global 🔄 How Scope Chain Works Example: let a = 10; function outer() { let b = 20; function inner() { let c = 30; console.log(a, b, c); } inner(); } outer(); 🧩 Step-by-step lookup Inside inner(): Looks for c → found ✅ Looks for b → not in inner → goes to outer → found ✅ Looks for a → not in inner/outer → goes to global → found ✅ 📊 Visual Flow inner() → outer() → global 👉 This chain is called scope chain ❌ What if variable not found? function test() { console.log(x); } test(); // ❌ ReferenceError 👉 JS searches everywhere → not found → error 🧑🍳 Real-Life Analogy Think of searching keys 🔑: Check your pocket Check your bag Check your room 👉 If not found → error 😄 ⚠️ Important Points Scope is decided at the time of writing code (lexical scope) Inner functions can access outer variables Outer cannot access inner variables 🧾 Final Summary Scope: Defines where variables are accessible Scope Chain:Order in which JS searches variables Inner → outer → global 💡 One-line takeaway 👉Scope defines access, and scope chain defines how JavaScript searches for variables #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
#js #14 **What is Function Hoisting?** 👉 Function hoisting means: JavaScript moves function declarations to the top of their scope during the memory phase 🔹 1. Function Declaration (Fully Hoisted) sayHello(); function sayHello() { console.log("Hello"); } ✅ Output: Hello 🤔 Why does this work? Because internally JavaScript treats it like: function sayHello() { console.log("Hello"); } sayHello(); 👉 The entire function (code + body) is hoisted ✔ You can call it before declaration 🔹 2. Function Expression (NOT fully hoisted) sayHi(); var sayHi = function() { console.log("Hi"); }; ❌ Output: TypeError: sayHi is not a function 🤔 Why? Internally: var sayHi = undefined; // hoisted sayHi(); // ❌ undefined() sayHi = function() { console.log("Hi"); }; 👉 Only the variable is hoisted, not the function 🔹 3. let / const Function Expression sayBye(); let sayBye = function() { console.log("Bye"); }; ❌ Output: ReferenceError 🤔 Why? Because of TDZ (Temporal Dead Zone) sayBye is hoisted But not initialized So you cannot access it before declaration 🧩 How it works internally (Memory Phase) Example: function a() {} var b = function() {}; let c = function() {}; 👉 Memory creation: a → full function stored ✅ b → undefined c → uninitialized (TDZ) 🧑🍳 Simple analogy Think of it like tools 🧰: Function Declaration 👉 Full tool ready before work starts Function Expression 👉 Only box is there, tool comes later let/const 👉 Box is locked (TDZ) until opened 🎯 Important Points Function declarations are fully hoisted Function expressions behave like variables var → undefined let/const → TDZ Only declarations (not assignments) are hoisted 🧾 Final Summary Function declaration → fully hoisted Function expression → partially hoisted let/const → TDZ applies 💡 One-line takeaway 👉Only function declarations are completely hoisted; function expressions follow variable hoisting rules #Javascript #ObjectOrientedProgramming #SoftwareDevelopment
To view or add a comment, sign in
-
💡JavaScript Interview Question💡 Predict the output of the below code and explain in detail. const result = ("b" + "a" + +"cteri" + "a").toLowerCase(); console.log(result); 𝗔𝗻𝘀𝘄𝗲𝗿: The above code prints "banana" as the output. This is because in JavaScript unary + operator converts a string into a number for example, +"5" will return 5 but If the string to be converted is not a number then NaN is returned so in the above code +"cteria" will result in NaN So, "b" + "a" => "ba" "ba" + +"cteria" => "baNaN" "baNaN" + "a" => "baNaNa" ("baNaNa").toLowerCase() => "banana" So, even If you write ("b" + "a" + + "a" + "a").toLowerCase(), it will still result into "banana". 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
To view or add a comment, sign in
-
-
5 JavaScript tricks that made me go "wait... WHAT?" I've been coding for 4 years. These still surprised me. ① Optional Chaining (?.) No more "cannot read property of undefined" crashes. user?.profile?.avatar ✔️ ② Nullish Coalescing (??) Only falls back when value is null or undefined. const name = user.name ?? "Guest" ✔️ ③ Array Destructuring with Skip Skip elements you don't need. const [first, , third] = [1, 2, 3] ✔️ ④ Object Shorthand Stop repeating yourself. { name: name } → { name } ✔️ ⑤ Promise.all() Run multiple async calls at the same time. 10x faster than awaiting one by one. ✔️ JavaScript is weird. But once it clicks — it's magic. ✨ Which one did YOU not know? Drop the number 👇 #JavaScript #WebDevelopment #MERNStack #ReactJS #CodingTips
To view or add a comment, sign in
-
-
🧠 Understanding the “this” Keyword in JavaScript (Simple Explanation) The this keyword is one of the most confusing parts of JavaScript. Early on, I used to assume this always refers to the current function — but that’s not actually true. 👉 The value of this depends on how a function is called, not where it is written. Let’s break it down 👇 🔹 1. Global Context console.log(this); In browsers, this refers to the window object. 🔹 2. Inside a Regular Function function show() { console.log(this); } Here, this depends on how the function is invoked. 🔹 3. Inside an Object Method const user = { name: "John", greet() { console.log(this.name); } }; user.greet(); // "John" Here, this refers to the object calling the method. 🔹 4. Arrow Functions Arrow functions do NOT have their own this. They inherit this from the surrounding (lexical) scope. 🔹 5. call, apply, bind These methods allow you to manually control what this refers to. 💡 One thing I’ve learned: Understanding this becomes much easier when you focus on how the function is called, not where it is defined. Curious to hear from other developers 👇 What part of JavaScript confused you the most when you were learning? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🔍 JavaScript Quirk: this behaves differently than you think This is one of the most confusing parts of JavaScript 👇 const user = { name: "Avinash", greet: function () { console.log(this.name); } }; user.greet(); // ? ✅ Output: "Avinash" Here, this refers to the object calling the function. Now look at this 👇 const greet = user.greet; greet(); // ? 💥 Output: undefined Why? Because this is no longer bound to user. In this case, this refers to the global object (or undefined in strict mode). Now the tricky part 👇 const user = { name: "Avinash", greet: () => { console.log(this.name); } }; user.greet(); // ? 💥 Output: undefined Why? Arrow functions don’t have their own this. They inherit it from their surrounding scope. 🚨 NEVER use this inside arrow functions for object methods. 💡 Takeaway: ✔ this depends on HOW a function is called ✔ Regular functions → dynamic this ✔ Arrow functions → lexical this ✔ Arrow + this in methods = bug waiting to happen 👉 Master this = fewer hidden bugs 🔁 Save this for later 💬 Comment "this" if it clicked ❤️ Like if this helped #javascript #frontend #webdevelopment #codingtips #js #developer
To view or add a comment, sign in
-
Have you come across something like this: 'this.setState({ [e.target.name]: e.target.value });' and wondered why those square brackets '[]' are there? If you are transitioning from basic JavaScript to React, this syntax can look a bit like an array hidden inside an object. But do not let it fool you. It is actually a powerful ES6 feature called Computed Property Names. Here is why those brackets are the secret sauce of efficient React forms. In standard JavaScript objects, if you write a key, it is treated as a literal string. If you write 'e.target.name: e.target.value' without the brackets, React will literally create a key named 'e.target.name' in your state. It will not care that your input’s name is 'username' or 'email.' It would just create a messy, broken state object. When you wrap a key in square brackets, you are telling JavaScript to evaluate the code inside the brackets first and use the result as the key name. If you type in an input where name='email', JavaScript sees '[e.target.name]' and resolves it to the string 'email'. This turns your code from a rigid list of instructions into a flexible, dynamic system. The biggest benefit here is scalability. It allows you to follow the DRY (Don't Repeat Yourself) principle. Without square brackets, you would need a separate handler function for every single input field. With them, you can write one universal 'handleChange' function that works for two inputs or two hundred. It keeps your code centralized and eliminates the risk of copy-paste bugs. As long as your input's name attribute matches the key in your 'this.state', you are golden. It is a simple ES6 trick that makes handling complex forms significantly easier. #ReactJS #Javascript #SoftwareEngineering #WebDevelopment #CodingTips #ES6
To view or add a comment, sign in
-
-
🚀 Understanding JSX in React — Syntax & Rules Simplified! If you're working with React, JSX is everywhere. But JSX is not HTML—it’s JavaScript with a syntax extension. 💡 What is JSX? JSX (JavaScript XML) lets you write UI like this: const element = <h1>Hello, World!</h1>; 👉 Behind the scenes, React converts this into: React.createElement("h1", null, "Hello, World!"); ⚙️ How JSX works 👉 JSX is compiled into JavaScript 👉 It describes what the UI should look like 👉 React uses it to create Virtual DOM 🧠 Key Rules of JSX (Very Important!) 🔹 1. Return a single parent element // ❌ Wrong return ( <h1>Hello</h1> <p>World</p> ); // ✅ Correct return ( <> <h1>Hello</h1> <p>World</p> </> ); 🔹 2. Use className instead of class <div className="container"></div> 🔹 3. JavaScript inside {} const name = "React"; <h1>Hello {name}</h1> 🔹 4. Self-closing tags <img src="image.png" /> 🔹 5. Inline styles as objects <div style={{ color: "red" }}></div> 🧩 Real-world use cases ✔ Building UI components ✔ Rendering dynamic data ✔ Conditional UI rendering ✔ Mapping lists 🔥 Best Practices (Most developers miss this!) ✅ Keep JSX clean and readable ✅ Extract complex logic outside JSX ✅ Use fragments instead of unnecessary divs ❌ Avoid writing heavy logic inside JSX ⚠️ Common Mistake // ❌ Too much logic inside JSX return <h1>{user.isLoggedIn ? "Welcome" : "Login"}</h1>; 👉 Fine for small cases, but extract logic for complex UI 💬 Pro Insight JSX is not about writing HTML in JS— 👉 It’s about describing UI in a declarative way 📌 Save this post & follow for more deep frontend insights! 📅 Day 6/100 #ReactJS #FrontendDevelopment #JavaScript #JSX #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
💡 JavaScript Essentials: Closures & Hoisting Explained Simply If you're working with JavaScript, especially in frameworks like Angular or React, understanding closures and hoisting is a must. Here’s a quick breakdown 👇 🔹 Closures A closure is created when a function remembers its outer scope even after that outer function has finished execution. 👉 Why it matters? Helps in data encapsulation Used in callbacks, event handlers, and async code Powers concepts like private variables Example: function outer() { let count = 0; return function inner() { count++; console.log(count); } } const counter = outer(); counter(); // 1 counter(); // 2 🔹 Hoisting Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 Key points: var is hoisted and initialized with undefined let and const are hoisted but stay in the Temporal Dead Zone Function declarations are fully hoisted Example: console.log(a); // undefined var a = 10; console.log(b); // ReferenceError let b = 20; 🚀 Takeaway Closures help you retain state, while hoisting explains how JavaScript reads your code before execution. Mastering these will level up your debugging skills and help you write cleaner, predictable code. #JavaScript #WebDevelopment #Frontend #Angular #React #Coding #Developers
To view or add a comment, sign in
-
Day 4/100 of JavaScript 🚀 Today’s focus: Functions in JavaScript Functions are reusable blocks of code used to perform specific tasks Some important types with example code: 1. Parameterized function → takes input function greet(name) { return "Hello " + name; } greet("Apsar"); 2. Pure function → same input always gives same output, no side effects function add(a, b) { return a + b; } add(2, 3); 3. Callback function → function passed into another function function processUser(name, callback) { callback(name); } processUser("Apsar", function(name) { console.log("User:", name); }); 4.Function expression → function stored in a variable const multiply = function(a, b) { return a * b; }; 5.Arrow function → shorter syntax const square = (n) => n * n; Key understanding: Functions are first-class citizens in JavaScript — they can be passed, returned, and stored like values #Day4 #JavaScript #100DaysOfCode
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