Day 31/50 – JavaScript Interview Question? Question: What is the difference between import and require()? Simple Answer: import is ES6 module syntax that's statically analyzed at compile time and supports tree-shaking. require() is CommonJS syntax used in Node.js, dynamically evaluated at runtime. import statements must be at the top level, while require() can be used conditionally. 🧠 Why it matters in real projects: Modern bundlers like Webpack and Vite use import for tree-shaking (removing unused code), significantly reducing bundle sizes. Understanding both is crucial since Node.js packages often use CommonJS while frontend code uses ES modules. 💡 One common mistake: Mixing import and require() syntax in the same file, or trying to use import conditionally inside if-statements (not allowed). Also, forgetting that require() is synchronous while dynamic import() is asynchronous. 📌 Bonus: // ES6 Modules (import) import React from 'react'; import { useState, useEffect } from 'react'; import * as utils from './utils'; import type { User } from './types'; // TypeScript // CommonJS (require) const express = require('express'); const { Router } = require('express'); // Key differences: // 1. Static vs Dynamic import { func } from './module'; // ✓ Top-level only const mod = require('./module'); // ✓ Can be anywhere if (condition) { import { func } from './module'; // ✗ SyntaxError const mod = require('./module'); // ✓ Works } // 2. Dynamic import (async ES6 feature) const module = await import('./module.js'); // ✓ Async loading // 3. Tree-shaking (import only) import { usedFunction } from 'lodash-es'; // Bundler removes unused functions ✓ const _ = require('lodash'); // Entire library included ✗ // 4. Named exports handling // ES6 export const name = 'Alice'; export default function() {} // CommonJS module.exports = { name: 'Alice' }; module.exports.name = 'Alice'; exports.name = 'Alice'; // Shorthand #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
ES6 import vs Node.js require differences
More Relevant Posts
-
Day 35/50 – JavaScript Interview Question? Question: What is the new keyword and what happens when you use it? Simple Answer: The new keyword creates an instance of a constructor function or class. It performs four steps: creates an empty object, sets the prototype, binds this to the new object, and returns the object (unless the constructor explicitly returns another object). 🧠 Why it matters in real projects: Understanding new is fundamental to JavaScript's prototypal inheritance and OOP patterns. It's crucial when working with classes, custom data structures, and understanding how frameworks like React create component instances. 💡 One common mistake: Forgetting new when calling a constructor, causing this to refer to the global object (or undefined in strict mode) instead of creating a new instance. Also, not knowing that arrow functions can't be used as constructors. 📌 Bonus: // Constructor function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; // Using new keyword const alice = new Person('Alice', 30); // What happens behind the scenes: function Person(name, age) { // 1. const this = Object.create(Person.prototype); // 2. this.__proto__ = Person.prototype; this.name = name; // 3. Bind properties to this this.age = age; // 4. return this; (implicit) } // Common mistakes: // ✗ Forgetting new const bob = Person('Bob', 25); // undefined, this = window! console.log(window.name); // "Bob" - polluted global! // ✓ With new const charlie = new Person('Charlie', 35); // ✓ // Arrow functions can't be constructors const PersonArrow = (name) => { this.name = name; }; const dave = new PersonArrow('Dave'); // ✗ TypeError! // ES6 Classes (syntactic sugar over prototypes) class Employee extends Person { constructor(name, age, title) { super(name, age); // Must call before using this this.title = title; } } // Custom return value overrides function Custom() { this.name = 'Test'; return { custom: true }; // This is returned instead } const obj = new Custom(); console.log(obj); // { custom: true } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #OOP #Constructors
To view or add a comment, sign in
-
🚀 Day 14 of JavaScript Daily Series JavaScript Template Literals — Backticks, ${}, Multi-line Strings (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ka one of the most modern & powerful features seekhenge → 👉 Template Literals (introduced in ES6) Yeh code ko 2x clean, readable aur easy bana dete hain! 💡 What Are Template Literals? (Simple English) Template literals are special strings written using backticks (``) They allow: ✔ Multi-line strings ✔ Variables inside strings ✔ Cleaner formatting ✔ Better readability 🧠 Hinglish Explanation Pehle hum strings ko " " quotes se likhte the, aur variables ko add karne ke liye + + laga-laga ke hath dukh jaata tha. Template literals bolte hain: “Ritesh bhai, tension mat lo… sab easy bana dete hain!” 😄 🧱 1️⃣ Backticks (``) — The New & Better String Format Example: let name = "Ritesh"; let msg = `Hello ${name}, welcome to JavaScript!`; console.log(msg); ✔ No + + ✔ Automatic spacing ✔ Clean and readable 🔁 2️⃣ ${} — Variable / Expression Insert Karna Aap backticks ke andar kisi bhi variable ko easily daal sakte ho: let price = 499; console.log(`Your final price is ₹${price}`); Expressions bhi kaam karte hain: console.log(`2 + 2 = ${2 + 2}`); 📜 3️⃣ Multi-line Strings — No Need for \n Pehle hum: let msg = "Hello\nWorld"; Ab: let msg = ` This is line 1 This is line 2 This is line 3 `; ✔ Best for UI text ✔ Emails ✔ Multi-line messages ✔ Readable content 📱 Real-Life Example — Instagram Notification Message let user = "AapanRasoi"; let followers = 1200; let message = ` 🔔 New Activity! Hey ${user}, you gained ${followers} followers today! Keep growing! 🚀 `; console.log(message); Perfect for: ✔ Notification messages ✔ Email templates ✔ Chat messages ✔ JSX-style strings 🧠 Why Template Literals Are a Game-Changer? ✔ No messy string concatenation ✔ More readable ✔ Easy variable insertion ✔ Perfect for dynamic UI ✔ Used heavily in React, Node.js, APIs, everything! 🎯 Quick Summary FeatureUseBackticksCleaner strings${}Insert variables & expressionsMulti-lineCreate structured text easily
To view or add a comment, sign in
-
here's some important JavaScript questions to crack interviews 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱? - Refers to the object that is currently executing the function - In global scope, this is the window object (in browsers) - Arrow functions do not have their own this 𝟮. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗮𝗹 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲? - JS objects inherit properties and methods from other objects via a prototype chain - Every object has a hidden __proto__ property pointing to its prototype - ES6 class syntax is just cleaner syntax over prototypal inheritance 𝟯. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝗽𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (...)? - Spread expands an array or object: const newArr = [...arr, 4, 5] - Rest collects remaining arguments into an array: function fn(a, ...rest) {} - Same syntax, different context position determines behavior - Great for copying arrays/objects without mutation 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴? - Extract values from arrays or objects into variables cleanly - Array: const [first, second] = [1, 2] - Object: const { name, age } = user - Supports default values: const { name = 'Guest' } = user 𝟱. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻? - Instead of adding listeners to each child element, add one listener to the parent - Uses event bubbling events travel up the DOM tree - More memory efficient for large lists or dynamic content - Check event.target inside the handler to identify which child was clicked 𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗰𝗮𝗹𝗹(), 𝗮𝗽𝗽𝗹𝘆()? - All three explicitly set the value of this - call() invokes immediately, passes args one by one - apply() invokes immediately, passes args as an array 𝟳. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻? - Caching the result of a function call so it doesn't recompute for the same input - Improves performance for expensive or repeated operations - Commonly implemented using closures and objects/Maps 𝟴. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗛𝗶𝗴𝗵𝗲𝗿-𝗢𝗿𝗱𝗲𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? - Functions that take other functions as arguments or return them - Examples: .map(), .filter(), .reduce(), .forEach() - Core concept in functional programming with JavaScript 𝟵. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗮𝗻𝗱 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆? - Shallow copy copies only the top level nested objects are still referenced - Object.assign() and spread {...obj} create shallow copies - Deep copy duplicates everything including nested levels 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗼𝗽𝘁𝗶𝗼𝗻𝗮𝗹 𝗰𝗵𝗮𝗶𝗻𝗶𝗻𝗴 (?.) 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹𝗶𝘀𝗵 𝗰𝗼𝗮𝗹𝗲𝘀𝗰𝗶𝗻𝗴 (??)? - ?. safely accesses nested properties without throwing if something is null/undefined - user?.address?.city returns undefined instead of crashing - ?? returns the right side only if the left is null or undefined Follow the Frontend Circle By Sakshi channel on WhatsApp: https://lnkd.in/gj5dp3fm 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝘂𝘀 𝗵𝗲𝗿𝗲 → https://lnkd.in/geqez4re
To view or add a comment, sign in
-
⚛️ JSX Explained — The Heart of React UI One of the first things developers notice when learning React is something that looks like HTML inside JavaScript. That syntax is called JSX. JSX makes it easier to build and visualize user interfaces directly within your JavaScript code. 🔹 What is JSX? JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows developers to write UI code that looks like HTML while still having the full power of JavaScript. Example: const element = <h1>Hello, Developer 👋</h1>; This code tells React what the UI should look like. Behind the scenes, JSX gets converted into JavaScript function calls. ⚙️ What Happens Behind the Scenes? Browsers cannot understand JSX directly. Tools like Babel transform JSX into normal JavaScript. Example conversion: JSX: <h1>Hello World</h1> Converted JavaScript: React.createElement("h1", null, "Hello World"); This transformation allows React to efficiently render UI elements. 🧠 Why JSX is Powerful JSX provides several advantages: ✔ Readable UI code ✔ Combines logic and UI in one place ✔ Easier component development ✔ Improved developer productivity Instead of separating HTML and JavaScript, JSX integrates them. 🔄 Using JavaScript Inside JSX JSX allows JavaScript expressions using curly braces {}. Example: const name = "Rahul"; function App() { return <h1>Hello {name}</h1>; } React dynamically renders the value of the variable. 📦 JSX with Components JSX makes it easy to use components like HTML tags. Example: function Welcome() { return <h2>Welcome to React</h2>; } function App() { return ( <div> <Welcome /> </div> ); } This approach allows developers to build modular UI systems. 🚨 Common JSX Rules JSX follows a few important rules: ✔ Always return a single parent element ✔ Use className instead of class ✔ Close all tags properly ✔ JavaScript expressions go inside {} Example: return ( <div> <h1>Hello</h1> <p>Welcome to React</p> </div> ); ❌ Common Beginner Mistakes ❌ Returning multiple root elements ❌ Forgetting to close tags ❌ Using class instead of className ❌ Writing statements instead of expressions inside {} 💡 Pro Developer Thinking Experienced developers treat JSX as a UI description language. Instead of thinking: “Write HTML in JavaScript” Think: “Describe UI with components and logic”. This mindset helps build clean, scalable React applications. 🎯 Final Thought JSX is what makes React development intuitive and powerful. It allows developers to combine structure, logic, and components in a way that feels natural. Once you master JSX, building complex interfaces becomes much easier. #ReactJS #JSX #FrontendDevelopment #JavaScript #WebDevelopment #MERNStack #FullStackDeveloper https://lnkd.in/d6qMwEik
To view or add a comment, sign in
-
-
🔥 JavaScript Deep Dive: Understanding this, call(), apply(), and bind() One of the most important concepts in JavaScript is understanding how function context works. Many developers get confused with the behavior of the this keyword and how it changes depending on how a function is called. To control the value of this, JavaScript provides three powerful methods: call(), apply(), and bind(). Understanding these concepts is essential for writing clean, reusable, and predictable JavaScript code, especially when working with callbacks, event handlers, and modern frameworks. 📌 1️⃣ this Keyword In JavaScript, this refers to the object that is executing the current function. const user = { name: "Developer", greet() { console.log(`Hello ${this.name}`) } } user.greet() Output Hello Developer Here, this refers to the user object because the method is called using user.greet(). ⚡ 2️⃣ call() – Execute a function with a specific context The call() method invokes a function immediately and allows us to set the value of this. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } greet.call(user) We can also pass arguments: function greet(city){ console.log(`${this.name} from ${city}`) } const user = { name: "Developer" } greet.call(user, "Meerut") ⚡ 3️⃣ apply() – Similar to call but arguments are passed as an array function greet(city, country){ console.log(`${this.name} from ${city}, ${country}`) } const user = { name: "Developer" } greet.apply(user, ["Meerut", "India"]) ⚡ 4️⃣ bind() – Creates a new function with a fixed this Unlike call() and apply(), the bind() method does not execute the function immediately. Instead, it returns a new function with the specified this value. function greet(){ console.log(`Hello ${this.name}`) } const user = { name: "Developer" } const greetUser = greet.bind(user) greetUser() 💡 Understanding the difference • call() executes the function immediately and arguments are passed normally (comma separated). • apply() also executes the function immediately, but arguments are passed as an array. • bind() does not execute the function immediately. Instead, it returns a new function with the this value permanently bound, which can be executed later. ⚡ Why this concept matters Understanding function context is crucial for: • Reusing functions across objects • Controlling behavior of callbacks • Writing modular and maintainable code • Working effectively with event handlers and asynchronous code Mastering these JavaScript fundamentals helps developers build more predictable and scalable applications. #JavaScript #WebDevelopment #Programming #FrontendDevelopment #Coding #SoftwareDevelopment #DeveloperJourney
To view or add a comment, sign in
-
JavaScript Was Hard I’d hear from so many people that JavaScript is confusing because of its inconsistencies. But once I learned these concepts, it became so much easier to me : 𝟭. 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 𝗮𝗻𝗱 𝗗𝗮𝘁𝗮 𝗧𝘆𝗽𝗲𝘀: -> Declaration (`var`, `let`, `const`) -> Primitive data types (strings, numbers, booleans, null, undefined) -> Complex data types (arrays, objects, functions) -> Type coercion and conversion 𝟮. 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗮𝗻𝗱 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀: -> Arithmetic operators (+, -, *, /, %) -> Assignment operators (=, +=, -=, *=, /=, %=) -> Comparison operators (==, ===, !=, !==, <, >, <=, >=) -> Logical operators (&&, || , !) -> Ternary operator (conditional operator) 𝟯. 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝗙𝗹𝗼𝘄: -> Conditional statements (`if`, `else if`, `else`) -> Switch statement -> Loops (`for`, `while`, `do-while`) -> Break and continue statements 𝟰. 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀: -> Function declaration and expression -> Arrow functions -> Parameters and arguments -> Return statement -> Scope (global scope, function scope, block scope) -> Closures -> Callback functions 𝟱. 𝗔𝗿𝗿𝗮𝘆𝘀 𝗮𝗻𝗱 𝗢𝗯𝗷𝗲𝗰𝘁𝘀: -> Creation and initialization -> Accessing and modifying elements -> Array methods (push, pop, shift, unshift, splice, slice, concat, etc.) -> Object properties and methods -> JSON (JavaScript Object Notation) 𝟲. 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝗮𝗻𝗱 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗲𝘀: -> Class syntax (constructor, methods, static methods) -> Inheritance -> Prototypal inheritance -> Object.create() and Object.setPrototypeOf() 𝟳. 𝗘𝗿𝗿𝗼𝗿 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: -> Try...catch statement -> Throwing errors -> Error objects (Error, SyntaxError, TypeError, etc.) -> Error handling best practices 𝟴. 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: -> Callbacks -> Promises (creation, chaining, error handling) -> Async/await syntax -> Fetch API -> setTimeout() and setInterval() 𝟵. 𝗗𝗢𝗠 𝗠𝗮𝗻𝗶𝗽𝘂𝗹𝗮𝘁𝗶𝗼𝗻: -> Selecting DOM elements -> Modifying element properties and attributes -> Creating and removing elements -> Traversing the DOM 𝟭𝟬. 𝗘𝘃𝗲𝗻𝘁 𝗛𝗮𝗻𝗱𝗹𝗶𝗻𝗴: -> Adding event listeners -> Event objects -> Event propagation (bubbling and capturing) -> Event delegation 𝟭𝟭. 𝗠𝗼𝗱𝘂𝗹𝗲𝘀 𝗮𝗻𝗱 𝗠𝗼𝗱𝘂𝗹𝗮𝗿𝗶𝘇𝗮𝘁𝗶𝗼𝗻: -> ES6 modules (import/export) -> CommonJS modules (require/module.exports) -> Module bundlers (Webpack, Rollup) 𝟭𝟮. 𝗕𝗿𝗼𝘄𝘀𝗲𝗿 𝗖𝗼𝗺𝗽𝗮𝘁𝗶𝗯𝗶𝗹𝗶𝘁𝘆 𝗮𝗻𝗱 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲: -> Cross-browser compatibility -> Performance optimization techniques -> Minification and code splitting -> Lazy loading If you're struggling with JavaScript, understanding these topics can make the journey a lot easier! I've Created MERN Stack Guide for beginners to experienced, 𝗚𝗲𝘁 𝘁𝗵𝗲 𝗚𝘂𝗶𝗱𝗲 𝗵𝗲𝗿𝗲 - https://lnkd.in/dauSXK5R Follow Ashish Misal Codes on IG: https://lnkd.in/dJqGy5_g Keep Coding, Keep Building!
To view or add a comment, sign in
-
🚀 Day 17 of JavaScript Daily Series JavaScript Events — click, input, change, keyup (Super Easy Hinglish + Real-Life Web Examples) Aaj hum JavaScript ka woh topic seekhenge jo websites ko truly interactive banata hai: 👉 Events Buttons click hona, input type karna, dropdown change hona, search bar me typing — yeh sab EVENTS ki wajah se possible hota hai. 💡 What Are Events? (Simple English) Events are actions that happen on a webpage. Examples: ✔ User clicks a button ✔ User types in a textbox ✔ User changes a dropdown ✔ User presses a key ✔ Mouse moves JavaScript can listen to these events and respond to them. 🧠 Hinglish Explanation Socho website ek shop hai. Customer koi bhi action kare → click, bolna, dekhna, move hona… Shopkeeper (JavaScript) turant react karta hai. “Click kiya? Chalo button ka color badal deta hoon.” “Typing shuru? Chalo search results dikhata hoon.” Today’s 4 Most Important Events 1️⃣ click 2️⃣ input 3️⃣ change 4️⃣ keyup 1️⃣ click Event — Jab User Button/Element Click Kare 📱 Example: Button text change <button id="btn">Login</button> let btn = document.getElementById("btn"); btn.addEventListener("click", function () { btn.innerText = "Logging in..."; }); Real-life use: ✔ Login button ✔ Buy Now button ✔ Like 👍 button 2️⃣ input Event — Jab User Kuch Type Kare 📱 Example: Live search bar <input id="search" placeholder="Search here..." /> <p id="output"></p> let search = document.getElementById("search"); let output = document.getElementById("output"); search.addEventListener("input", () => { output.innerText = `You typed: ${search.value}`; }); Real-life use: ✔ Search bar ✔ Live filters ✔ Form inputs 3️⃣ change Event — Jab Value Change Ho (Dropdown, Checkbox) 📱 Example: Theme selector <select id="theme"> <option value="light">Light</option> <option value="dark">Dark</option> </select> let theme = document.getElementById("theme"); theme.addEventListener("change", () => { console.log(`Theme changed to: ${theme.value}`); }); Real-life use: ✔ Country → State dropdown ✔ Dark/Light mode ✔ Payment method selection 4️⃣ keyup Event — Jab User Key Chhodta Hai 📱 Example: Password strength indicator <input id="pass" placeholder="Enter password" /> <p id="strength"></p> let pass = document.getElementById("pass"); pass.addEventListener("keyup", () => { if (pass.value.length < 6) { strength.innerText = "Weak Password"; } else { strength.innerText = "Strong Password 💪"; } }); Real-life use: ✔ OTP boxes ✔ Password checker ✔ Live validation 🔥 Quick Summary Table EventTriggerReal UseclickButton clickedActions & UI changesinputTypingSearch, formschangeValue changedDropdowns, checkboxeskeyupKey releasedValidation, search 🧠 Why Events Are Important? ✔ Website becomes interactive ✔ Real-time UI updates ✔ Forms validation ✔ Buttons functionality ✔ Every real web app uses events (React/Node bhi!) Without events → Website = Static poster.
To view or add a comment, sign in
-
🚀 Day 13 of JavaScript Daily Series JavaScript Strings — slice, substring, toUpperCase, trim (Super Easy Hinglish + Real-Life Examples) Aaj hum JavaScript ke 4 most useful string methods seekhenge. Yeh daily life coding me 100% use hote hain — chahe forms ho, search bars ho, validation ho ya UI formatting. 📝 What is a String? (Simple English Definition) A string is a sequence of characters used to store text like names, messages, sentences, etc. Example: let name = "Ritesh Singh"; 1️⃣ slice() — Cut & Extract Part of the String 🔹 Definition Returns a portion of string from start index to end index (end not included). 🧠 Hinglish Explanation Socho tum movie clip ka ek scene cut karke nikalna chahte ho → yahi slice karta hai. 📱 Real-Life Example Instagram username crop karna: let username = "aapanrasoi_official"; let shortName = username.slice(0, 10); console.log(shortName); // "aapanraso" 2️⃣ substring() — Extract Part of String (Like slice, but safer) 🔹 Definition Works like slice but doesn’t accept negative indexes. 🧠 Hinglish Explanation Slice ka hi shareef version — negative cheezein nahi leta. 😄 📱 Example let text = "JavaScript"; console.log(text.substring(4, 10)); // "Script" 3️⃣ toUpperCase() — Convert to CAPITAL Letters 🔹 Definition Returns the string in uppercase. 🧠 Hinglish Explanation Whatsapp pe aise lagta hai jaise koi chillaa kar message bhej raha ho. 😆 📱 Example let city = "varanasi"; console.log(city.toUpperCase()); // "VARANASI" 4️⃣ trim() — Remove Extra Spaces 🔹 Definition Removes spaces from start and end. 🧠 Hinglish Explanation Form bharte time users extra space daal dete hain, trim unko clean kar deta hai. 📱 Real-Life Example (Form Input Clean) let email = " ritesh@gmail.com "; console.log(email.trim()); // "ritesh@gmail.com" 🔥 Quick Summary Table MethodKaamReal Useslice()Part nikalnaUsername / Title Shortensubstring()Safe extractionWord pickingtoUpperCase()Text ko caps meLabels / Highlightstrim()Extra space hatanaForm inputs 🧠 Why These 4 Methods Matter? ✔ Clean data ✔ Better UI ✔ Faster string manipulation ✔ Interviews me 100% pooch lete hain
To view or add a comment, sign in
-
🚀 JavaScript Objects – Interview Q&A (Frontend Focused) 1️⃣ What is an object in JavaScript? An object is a collection of key–value pairs used to store structured data. Keys are strings (or symbols), and values can be any data type. 2️⃣ How do you create an object in JavaScript? // Object literal const obj = { name: "JS" }; // Using constructor const obj2 = new Object(); // Using Object.create const obj3 = Object.create(null); 3️⃣ How do you access object properties? obj.name; // Dot notation obj["name"]; // Bracket notation 👉 Bracket notation is useful for dynamic keys. 4️⃣ Difference between dot notation and bracket notation? DotBracketStatic keysDynamic keysFaster & cleanerRequired for special characters 5️⃣ How do you loop through an object? for (let key in obj) { console.log(key, obj[key]); } Object.keys(obj).forEach(key => console.log(key)); 6️⃣ What are Object.keys(), Object.values(), and Object.entries()? Object.keys() → array of keys Object.values() → array of values Object.entries() → array of [key, value] 7️⃣ Are objects mutable in JavaScript? ✅ Yes. Objects are mutable and passed by reference. const a = { x: 1 }; const b = a; b.x = 2; // a.x is also 2 8️⃣ How do you clone an object? // Shallow copy const copy = { ...obj }; const copy2 = Object.assign({}, obj); ⚠️ Nested objects still share references. 9️⃣ Difference between shallow copy and deep copy? Shallow copy → Copies only first level Deep copy → Copies all nested levels const deep = JSON.parse(JSON.stringify(obj)); 🔟 What is this inside an object? this refers to the current object calling the method. const user = { name: "Sweta", greet() { return this.name; } }; 1️⃣1️⃣ What is object destructuring? const { name, role } = user; Used for cleaner code and readability. 1️⃣2️⃣ What is the difference between Object.freeze() and Object.seal()? freeze() → Cannot add, remove, or update properties seal() → Can update existing properties only 1️⃣3️⃣ How do you check if a property exists? "name" in user; user.hasOwnProperty("name"); 1️⃣4️⃣ Real-world use of objects? ✅ API responses ✅ Component props & state ✅ Configuration files ✅ Form handling ✅ State management (Redux / Pinia) 💡 Interview Tip: Strong understanding of objects helps you master immutability, state management, and performance optimization in React & Vue. 👍 Like • 💬 Comment • 🔁 Share if this helped #JavaScript #FrontendInterview #WebDevelopment #React #Vue #CodingInterview #LinkedInLearning
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