Variables in JavaScript In JavaScript, variables can be declared using var, let, or const. 1. var – Function Scoped The var keyword was the original way to declare variables in JavaScript. A variable declared with var is function-scoped, meaning it can be accessed anywhere inside the function where it is defined — even outside of a block like an if statement. Example: function testVar() { if (true) { var message = "Hello, world!"; // declared with var } console.log(message); // accessible here because var is function-scoped } testVar(); // Output: "Hello, world!" Here, the variable message is accessible outside the if block because var does not have block scope—it only respects function boundaries. 2. let and const – Block Scoped Introduced in ES6 (ECMAScript 2015), both let and const are block-scoped. That means variables declared with these keywords can only be accessed within the block { } where they are defined. let allows you to reassign the variable later. const creates a read-only (constant) variable that cannot be reassigned once set. Example: function testBlockScope() { if (true) { let name = "Adnan"; // block-scoped const age = 25; // block-scoped and read-only console.log(name, age); // Accessible here → Adnan 25 } // console.log(name); // Error! 'name' is not defined outside the block // console.log(age); // Error! 'age' is not defined outside the block } testBlockScope(); In this case, name and age are not accessible outside the if block because both let and const follow block scope rules.
JavaScript Variables: Var, Let, Const Explained
More Relevant Posts
-
Today I revised two powerful concepts in JavaScript --Functions and the DOM(Document Object Model). 1. FUNCTIONS whenever a piece of code is repeating, we can wrap it inside a function and call it whenever needed. Functions make our code reusable, clean, and easy to manage. There's also a modern type called Arrow Function, which are great for writing short and simple logic or quick calculations. I also explored some important array methods which are used along functions: (I) for each(): executes a function on each element of array/object but doesn't return new array. (II) map(): similar to forEach, but it returns a new array after applying the function. (III) filter(): return a new array containing elements that satisfy a specific condition. (IV) reduce(): takes two parameters(previous & current) and combines all elements into a single result, often used for calculations. NOTE: Higher order functions are those which take another function as parameter or they return a function. eg: forEach loop 2. DOM(Document Object Model) The DOM allows us to interact with and manipulate HTML elements in JavaScript. We can select elements in different ways: (I)document.getElementById() (II)document.getElementByClassName() (III)document.getElementByTagName() (IV)document.querySelector() Each method help us to target HTML elements by their ID, class, or tag name. Some useful DOM properties I revised: (I) tagName: finds the tag name of an element. (II) innerText: gets or changes the visible text of an element. (III) innerHTML: gets or changes the HTML content of n element. (IV) textContent: similar to innerText, but it can also access hidden text.
To view or add a comment, sign in
-
A couple weeks ago, I spent an unholy amount of time debugging something that should simply have worked. Admittedly, JavaScript/TypeScript can have weird behaviors sometimes but the culprit this time? ```this``` Yeah. JavaScript’s ‘this’ keyword. I wanted to do a deep copy of an object (a hassle on its own) and I needed to define a method in the newly copied object that accepts a field from the object. My mistake was using an arrow function rather than a regular function, which apparently refers to a different execution context. It turned to a learning experience for me and I decided to put together something others can learn from, published in JavaScript in Plain English https://lnkd.in/e7tcBtub Kindly read, share your thoughts, or simply let me know if you’ve ever had a similar issue before and how you dealt with it.
To view or add a comment, sign in
-
Today I learned about two very important concepts in JavaScript --string and arrays. 1. STRINGS A strong is a sequence of characters used to represent text. eg: let str = "Vineet Nagar"; we can store text, numbers, or any characters inside it. (I) str.length: gives the total number of characters. (II) We can access any character using its index (like str[1] or str charAt(1).) => Common String Methods: (I) /n: moves text to a new line (II)\t: adds extra space or tab. (III)toUpperCase()/toLowerCase(): converts text to upper or lower case. (IV)trim(): removes extra spaces from the start and end. (V)slice(start, end): extracts a part of the string. (VI)concat(): joins two strings. (VII)replace(old, new): replaces a specific part of string . (VIII)charAt(index): returns the character at a given position. NOTE: Strings are immutable, meaning we can't directly change a specific character in them. 2. ARRAYS An array is a collection of items(numbers, strings, etc). eg: let arr = [96, 75, 48, 83, 66]; Each item has an index starting from 0. Unlike strings, arrays are mutable, so we can add, remove, or modify elements. => Common Array Methods: (I)push(): adds an element at the end. (II)pop(): removes the last element. (III)toString(): converts the array into a string. (IV)concat(): joins two arrays. (V)unshift(): adds an element at the beginning. (VI)shift(): removes the first element. (VII)slice(): returns a portion of the array. (VIII)splice(start, deletecount, newitem): removes and/or adds elements in between. NOTE: Arrays are mutable.
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’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
-
🧠 What Is the Call Stack in JavaScript? If you’ve ever wondered how JavaScript keeps track of what’s running, meet the Call Stack — the brain behind function execution. 🔍 How It Works The call stack is a data structure that works on a Last In, First Out (LIFO) principle — meaning the last function that goes in is the first one to come out. Since JavaScript is single-threaded, it executes one task at a time using this stack. Here’s how it flows 👇 1️⃣ Function Call: When a function is invoked, it’s pushed onto the top of the stack. 2️⃣ Execution: If it calls another function, that new one gets pushed on top. 3️⃣ Completion: When a function finishes, it’s popped off, and JavaScript moves back to the previous one. This continues until the stack is empty. 📦 Example in Action function greet() { console.log("Hello"); } function welcome() { greet(); console.log("Welcome!"); } welcome(); 🧩 Call Stack Flow: welcome() is pushed. Inside welcome(), greet() is called → pushed. greet() logs “Hello” → popped. welcome() logs “Welcome!” → popped. And the stack is empty again ✅ ⚠️ Stack Overflow If functions keep calling themselves recursively without a stop condition, the stack grows endlessly — leading to a “Maximum call stack size exceeded” error. 💥 That’s what we call a Stack Overflow. 💡 Why It Matters Understanding the call stack helps you: Debug errors like Maximum call stack size exceeded Trace function execution order Write better recursive functions Grasp asynchronous behavior (callbacks, promises, async/await)
To view or add a comment, sign in
-
Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code 1. Shorthand for if with multiple OR(||) conditions if (car === 'audi' || car === 'BMW' || car === 'Tesla') { //code } In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example. if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) { //code } if(obj && obj.tele && obj.tele.stdcode) { console.log(obj.tele .stdcode) } Use optional chaining (?.) to replace this snippet. console.log(obj?.tele?.stdcode); if (name !== null || name !== undefined || name !== '') { let second = name; } The simple way to do it is... const second = name || ''; switch (number) { case 1: return 'Case one'; case 2: return 'Case two'; default: return; } Use a map/ object const data = { 1: 'Case one', 2: 'Case two' }; //Access it using data[num] function example(value) { return 2 * value; } Use the arrow function const example = (value) => 2 * https://lnkd.in/gjf7ViX5
To view or add a comment, sign in
-
Change your old methods for writing a JavaScript Code - Shorthand's for JavaScript Code 1. Shorthand for if with multiple OR(||) conditions if (car === 'audi' || car === 'BMW' || car === 'Tesla') { //code } In a traditional way, we used to write code in the above pattern. but instead of using multiple OR conditions we can simply use an array and includes. Check out the below example. if (['audi', 'BMW', 'Tesla', 'grapes'].includes(car)) { //code } if(obj && obj.tele && obj.tele.stdcode) { console.log(obj.tele .stdcode) } Use optional chaining (?.) to replace this snippet. console.log(obj?.tele?.stdcode); if (name !== null || name !== undefined || name !== '') { let second = name; } The simple way to do it is... const second = name || ''; switch (number) { case 1: return 'Case one'; case 2: return 'Case two'; default: return; } Use a map/ object const data = { 1: 'Case one', 2: 'Case two' }; //Access it using data[num] function example(value) { return 2 * value; } Use the arrow function const example = (value) => 2 * https://lnkd.in/gjf7ViX5
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
var can lead to unexpected behavior due to its function scope, while let and const provide safer, predictable block scoping.