const observer = new MutationObserver(() => {
const heading = document.querySelector(".title-shortlink-container");
if (heading) {
// Create the button element
const button = document.createElement("button");
button.textContent = "Copy Text";
button.style.marginLeft = "10px"; // Add some spacing from the container
// Insert the button next to the .title-shortlink-container
heading.insertAdjacentElement("afterend", button);
// Add an event listener to copy the text
button.addEventListener("click", () => {
const textToCopy = heading.textContent.trim(); // Get only the container's text
navigator.clipboard.writeText(textToCopy).then(() => {
alert("Text copied: " + textToCopy);
}).catch(err => {
console.error("Failed to copy text: ", err);
});
});
observer.disconnect(); // Stop observing once the element is found
}
});
// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });
Code Explanation :
Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
If the Heading is not null. Then we create the button and styles.
The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
Button action create a function in addEventListener.
Get the link by heading.textContent and store in textToCopy
For copy the text use navigator.clipboard.writeText(textToCopy)
Then pop alert for the event.
if error catch throw error message.
Problem faced (dynamically loaded content)
First i use DOMContentLoaded. It cannot work in wiki.
Then i use Polling (Setintervel for a Certain time). It works partcially.
Then i use MutationObserver. I works perfectly to all pages.
const observer = new MutationObserver(() => {
const heading = document.querySelector(".title-shortlink-container");
if (heading) {
// Create the button element
const button = document.createElement("button");
button.textContent = "Copy Text";
button.style.marginLeft = "10px"; // Add some spacing from the container
// Insert the button next to the .title-shortlink-container
heading.insertAdjacentElement("afterend", button);
// Add an event listener to copy the text
button.addEventListener("click", () => {
const textToCopy = heading.textContent.trim(); // Get only the container's text
navigator.clipboard.writeText(textToCopy).then(() => {
alert("Text copied: " + textToCopy);
}).catch(err => {
console.error("Failed to copy text: ", err);
});
});
observer.disconnect(); // Stop observing once the element is found
}
});
// Observe the document for dynamic changes
observer.observe(document.body, { childList: true, subtree: true });
Code Explanation :
Use Document. querySelector for get the element of the .title-shortlink-container class. This class is for shortURL className and assign to variable Heading.
If the Heading is not null. Then we create the button and styles.
The Button is placed next to link. Use heading.insertAdjacentElement(“afterend”, button);
Button action create a function in addEventListener.
Get the link by heading.textContent and store in textToCopy
For copy the text use navigator.clipboard.writeText(textToCopy)
Then pop alert for the event.
if error catch throw error message.
Problem faced (dynamically loaded content)
First i use DOMContentLoaded. It cannot work in wiki.
Then i use Polling (Setintervel for a Certain time). It works partcially.
Then i use MutationObserver. I works perfectly to all pages.
Spike testing is a type of performance testing that evaluates how a system responds to sudden, extreme increases in load. Unlike stress testing, which gradually increases the load, spike testing simulates abrupt surges in traffic to identify system vulnerabilities, such as crashes, slow response times, and resource exhaustion.
In this blog, we will explore spike testing in detail, covering its importance, methodology, and full implementation using K6.
Why Perform Spike Testing?
Spike testing helps you
Determine system stability under unexpected traffic surges.
Identify bottlenecks that arise due to rapid load increases.
Assess auto-scaling capabilities of cloud-based infrastructures.
Measure response time degradation during high-demand spikes.
Ensure system recovery after the sudden load disappears.
http_req_duration → Measures response time impact.
vus_max → Peak virtual users during the spike.
errors → Percentage of failed requests due to overload.
Best Practices for Spike Testing
Monitor application logs and database performance during the test.
Use auto-scaling mechanisms for cloud-based environments.
Combine spike tests with stress testing for better insights.
Analyze error rates and recovery time to ensure system stability.
Spike testing is crucial for ensuring application stability under sudden, unpredictable traffic surges. Using K6, we can simulate spikes in both requests per second and concurrent users to identify bottlenecks before they impact real users.
Stress testing is a critical aspect of performance testing that evaluates how a system performs under extreme loads. Unlike load testing, which simulates expected user traffic, stress testing pushes a system beyond its limits to identify breaking points and measure recovery capabilities.
In this blog, we will explore stress testing using K6, an open-source load testing tool, with detailed explanations and full examples to help you implement stress testing effectively.
Why Stress Testing?
Stress testing helps you
Identify the maximum capacity of your system.
Detect potential failures and bottlenecks.
Measure system stability and recovery under high loads.
Ensure infrastructure can handle unexpected spikes in traffic.
K6 provides various executors to simulate different traffic patterns. For stress testing, we mainly use
ramping-vus – Gradually increases virtual users to a high level.
constant-vus – Maintains a fixed high number of virtual users.
spike – Simulates a sudden surge in traffic.
Example 1: Basic Stress Test with Ramping VUs
This script gradually increases the number of virtual users, holds a peak load, and then reduces it.
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
stages: [
{ duration: '1m', target: 100 }, // Ramp up to 100 users in 1 min
{ duration: '3m', target: 100 }, // Stay at 100 users for 3 min
{ duration: '1m', target: 0 }, // Ramp down to 0 users
],
};
export default function () {
let res = http.get('https://test-api.example.com');
sleep(1);
}
Explanation
The test starts with 0 users and ramps up to 100 users in 1 minute.
Holds 100 users for 3 minutes.
Gradually reduces load to 0 users.
The sleep(1) function helps simulate real user behavior between requests.
Example 2: Constant High Load Test
This test maintains a consistently high number of virtual users.
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
vus: 200, // 200 virtual users
duration: '5m', // Run the test for 5 minutes
};
export default function () {
http.get('https://test-api.example.com');
sleep(1);
}
Explanation
200 virtual users are constantly hitting the endpoint for 5 minutes.
Helps evaluate system performance under sustained high traffic.
Example 3: Spike Testing (Sudden Traffic Surge)
This test simulates a sudden spike in traffic, followed by a drop.
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
stages: [
{ duration: '10s', target: 10 }, // Start with 10 users
{ duration: '10s', target: 500 }, // Spike to 500 users
{ duration: '10s', target: 10 }, // Drop back to 10 users
],
};
export default function () {
http.get('https://test-api.example.com');
sleep(1);
}
Explanation
Starts with 10 users.
Spikes suddenly to 500 users in 10 seconds.
Drops back to 10 users.
Helps determine how the system handles sudden surges in traffic.
Analyzing Test Results
After running the tests, K6 provides detailed statistics
Stress testing is vital to ensure application stability and scalability. Using K6, we can simulate different stress scenarios like ramping load, constant high load, and spikes to identify system weaknesses before they affect users.
IndexedDB is a powerful client-side database API for storing structured data in browsers. However, its API is complex, requiring transactions, object stores, and cursors to manage data. LocalBase simplifies IndexedDB by providing an intuitive, promise-based API.
In this blog, we’ll explore LocalBase, its features, and how to use it effectively in web applications.
What is LocalBase?
LocalBase is an easy-to-use JavaScript library that simplifies IndexedDB interactions. It provides a syntax similar to Firestore, making it ideal for developers familiar with Firebase.
Key Features
Promise based API
Simple CRUD operations
No need for manual transaction handling
Works seamlessly in modern browsers
Installation
You can install LocalBase via npm or use it directly in a script tag
Since LocalBase doesn’t support native where queries, you need to filter manually.
3. Handling Transactions
LocalBase handles transactions internally, so you don’t need to worry about opening and closing them. However, you should use .then() to ensure operations complete before the next action.
The Web storage api is a set of mechanisms that enable browsers to store key-value pairs. Before HTML5, application data had to be sorted in cookies, included in every server request. Its intended to be far more user-friendly than using cookies.
Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.
There are 2 types of web storage,
Local Storage
Session Storage
We already have cookies. Why additional objects?
Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most modern browsers allow at least 5 megabytes of data (or more) and have settings to configure that.
Also unlike cookies, the server can’t manipulate storage objects via HTTP headers. Everything’s done in JavaScript.The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can’t access data from each other.
In this guide, you will learn/refresh about LocalStorage.
LocalStorage
The localStorage is property of the window (browser window object) interface allows you to access a Storage object for the Document’s origin; the stored data is saved across browser sessions.
Data is kept for a longtime in local storage (with no expiration date.). This could be one day, one week, or even one year as per the developer preference ( Data in local storage maintained even if the browser is closed).
Local storage only stores strings. So, if you intend to store objects, lists or arrays, you must convert them into a string using JSON.stringfy()
Local storage will be available via the window.localstorage property.
What’s interesting about them is that the data survives a page refresh (for sessionStorage) and even a full browser restart (for localStorage).
Functionalities
// setItem normal strings
window.localStorage.setItem("name", "goku");
// getItem
const name = window.localStorage.getItem("name");
console.log("name from localstorage, "+name);
// Storing an Object without JSON stringify
const data = {
"commodity":"apple",
"price":43
};
window.localStorage.setItem('commodity', data);
var result = window.localStorage.getItem('commodity');
console.log("Retrived data without jsonified, "+ result);
// Storing an object after converting to JSON string.
var jsonifiedString = JSON.stringify(data);
window.localStorage.setItem('commodity', jsonifiedString);
var result = window.localStorage.getItem('commodity');
console.log("Retrived data after jsonified, "+ result);
// remove item
window.localStorage.removeItem("commodity");
var result = window.localStorage.getItem('commodity');
console.log("Data after removing the key "+ result);
//length
console.log("length of local storage " + window.localStorage.length);
// clear
window.localStorage.clear();
console.log("length of local storage - after clear " + window.localStorage.length);
When to use Local Storage
Data stored in Local Storage can be easily accessed by third party individuals.
So its important to know that any sensitive data must not sorted in Local Storage.
Local Storage can help in storing temporary data before it is pushed to the server.
Always clear local storage once the operation is completed.
The majority of local storage’s drawbacks aren’t really significant. You may still not use it, but your app will run a little slower and you’ll experience a tiny developer inconvenience. Security, however, is distinct. Knowing and understanding the security model of local storage is crucial since it will have a significant impact on your website in ways you might not have anticipated.
Local storage also has the drawback of being insecure. In no way! Everyone who stores sensitive information in local storage, such as session data, user information, credit card information (even momentarily! ), and anything else you wouldn’t want shared publicly on social media, is doing it incorrectly.
The purpose of local storage in a browser for safe storage was not intended. It was intended to be a straightforward key/value store for strings only that programmers could use to create somewhat more complicated single page apps.
General Preventions
For example, if we are using third party JavaScript libraries and they are injected with some scripts which extract the storage objects, our storage data won’t be secure anymore. Therefore it’s not recommended to save sensitive data as
Username/Password
Credit card info
JWT tokens
API keys
Personal info
Session ids
Do not use the same origin for multiple web applications. Instead, use subdomains since otherwise, the storage will be shared with all. Reason is, for each subdomain it will have an unique localstorage; and they can’t communicate between subdomain instances.
Once some data are stored in Local storage, the developers don’t have any control over it until the user clears it. If you want the data to be removed once the session ends, use SessionStorage.
Validate, encode and escape data read from browser storage
Binary insertion sort is a sorting algorithm similar to insertion sort, but instead of using linear search to find the position where the element should be inserted, we use binary search.
Thus, we reduce the number of comparisons for inserting one element from O(N) (Time complexity in Insertion Sort) to O(log N).
Best of two worlds
Binary insertion sort is a combination of insertion sort and binary search.
Insertion sort is sorting technique that works by finding the correct position of the element in the array and then inserting it into its correct position. Binary search is searching technique that works by finding the middle of the array for finding the element.
As the complexity of binary search is of logarithmic order, the searching algorithm’s time complexity will also decrease to of logarithmic order. Implementation of binary Insertion sort. this program is a simple Insertion sort program but instead of the standard searching technique binary search is used.
How Binary Insertion Sort works ?
Process flow
In binary insertion sort, we divide the array into two subarrays — sorted and unsorted. The first element of the array is in the sorted subarray, and the rest of the elements are in the unsorted one.
We then iterate from the second element to the last element. For the i-th iteration, we make the current element our “key.” This key is the element that we have to add to our existing sorted subarray.
Example
Consider the array 29, 10, 14, 37, 14
First Pass
Key = 1
Since we consider the first element is in the sorted array, we will be starting from the second element. Then we apply the binary search on the sorted array.
In this scenario, we can see that the middle element in sorted array (29) is greater than the key element 10. So the position of the key element is 0. Then we can shift the remaining elements by 1 position.
Increment the value of key.
Second Pass
Key = 2
Now the key element is 14. We will apply binary search in the sorted array to find the position of the key element.
In this scenario, by applying binary search, we can see key element to be placed at index 1 (between 10 and 29). Then we can shift the remaining elements by 1 position.
Third Pass
Key = 3
Now the key element is 37. We will apply binary search in the sorted array to find the position of the key element.
In this scenario, by applying binary search, we can see key element is placed in its correct position.
Fourth Pass
Key = 4
Now the key element is 14. We will apply binary search in the sorted array to find the position of the key element.
In this scenario, by applying binary search, we can see key element to be placed at index 2 (between 14 and 29). Then we can shift the remaining elements by 1 position.
Iterate the array from the second element to the last element.
Store the current element Arr[i] in a variable key.
Find the position of the element just greater than Arr[i] in the subarray from Arr[0] to Arr[i-1] using binary search. Say this element is at index pos.
Shift all the elements from index pos to i-1 towards the right.
Arr[pos] = key.
Complexity Analysis
Worst Case
For inserting the i-th element in its correct position in the sorted, finding the position (pos) will take O(log i) steps. However, to insert the element, we need to shift all the elements from pos to i-1. This will take i steps in the worst case (when we have to insert at the starting position).
We make a total of N insertions. so, the worst-case time complexity of binary insertion sort is O(N^2).
This occurs when the array is initially sorted in descending order.
Best Case
The best case will be when the element is already in its sorted position. In this case, we don’t have to shift any of the elements; we can insert the element in O(1).
But we are using binary search to find the position where we need to insert. If the element is already in its sorted position, binary search will take (log i) steps. Thus, for the i-th element, we make (log i) operations, so its best-case time complexity is O(N log N).
This occurs when the array is initially sorted in ascending order.
Average Case
For average-case time complexity, we assume that the elements of the array are jumbled. Thus, on average, we will need O(i /2) steps for inserting the i-th element, so the average time complexity of binary insertion sort is O(N^2).
Space Complexity Analysis
Binary insertion sort is an in-place sorting algorithm. This means that it only requires a constant amount of additional space. We sort the given array by shifting and inserting the elements.
Therefore, the space complexity of this algorithm is O(1) if we use iterative binary search. It will be O(logN) if we use recursive binary search because of O(log N) recursive calls.
Is Binary Insertion Sort a stable algorithm
It is a stable sorting algorithm, the elements with the same values appear in the same order in the final array as they were in the initial array.
Cons and Pros
Binary insertion sort works efficiently for smaller arrays.
This algorithm also works well for almost-sorted arrays, where the elements are near their position in the sorted array.
However, when the size of the array is large, the binary insertion sort doesn’t perform well. We can use other sorting algorithms like merge sort or quicksort in such cases.
Making fewer comparisons is also one of the strengths of this sorting algorithm; therefore, it is efficient to use it when the cost of comparison is high.
Its efficient when the cost of comparison between keys is sufficiently high. For example, if we want to sort an array of strings, the comparison operation of two strings will be high.
Bonus Section
Binary Insertion Sort has a quadratic time complexity just as Insertion Sort. Still, it is usually faster than Insertion Sort in practice, which is apparent when comparison takes significantly more time than swapping two elements.
What do Reddit, Discord, Medium, and LinkedIn have in common? They use what’s called a skeleton loading screen for their applications. A skeleton screen is essentially a wireframe of the application. The wireframe is a placeholder until the application finally loads.
Rise of skeleton loader.
The term “skeleton screen” was introduced in 2013 by product designer Luke Wroblewski in a blog post about reducing perceived wait time. In this lukew.com/ff/entry.asp?1797 post, he explains how gradually revealing page content turns user attention to the content being loaded, and off of the loading time itself.
Skeleton Loader
Skeleton loading screens will improve your application’s user experience and make it feel more performant. The skeleton loading screen essentially impersonates the original layout.
This lets the user know what’s happening on the screen. The user interprets this as the application is booting up and the content is loading.
In simplest terms, Skeleton Loader is a static / animated placeholder for the information that is still loading. It mimic the structure and look of the entire view.
Why not just a loading spinner ?
Instead of showing a loading spinner, we could show a skeleton screen that makes the user see that there is progress happening when launching and navigating the application.
They let the user know that some content is loading and, more importantly, provide an indication of what is loading, whether it’s an image, text, card, and so on.
This gives the user the impression that the website is faster because they already know what type of content is loading before it appears. This is referred to as perceived performance.
Skeleton screens don’t really make pages load faster. Instead, they are designed to make it feel like pages are loading faster.
When to use ?
Use on high-traffic pages where resources takes a bit long to load like account dashboard.
When the component contains good amount of information, such as list or card.
Could be replaced by spin in any situation, but can provide a better user experience.
Use when there’s more than 1 element loading at the same time that requires an indicator.
Use when you need to load multiple images at once, a skeleton screen might make a good placeholder. For these pages, consider implementing lazy loading first, which is a similar technique for decreasing perceived load time.
When not to use ?
Not to use for a long-running process, e.g. importing data, manipulation of data etc. (Operations on data intensive applications)
Not to use for fast processes that that take less than half a second.
Users still associate video buffering with spinners. Avoid skeleton screens any time a video is loading on your page.
For longer processes (uploads, download, file manipulation ) can use progress bar instead of skeleton loading.
As a replacement for poor performance: If you can further optimize your website to actually load content more quickly, always pursue that first.
Ensuring your applications perform well under high traffic is crucial. Join us for an interactive K6 Bootcamp, where we’ll explore performance testing, load testing strategies, and real-world use cases to help you build scalable and resilient systems.
What is K6 and Why Should You Learn It?
Modern applications must handle thousands (or millions!) of users without breaking. K6 is an open-source, developer-friendly performance testing tool that helps you
Simulate real-world traffic and identify performance bottlenecks. Write tests in JavaScript – no need for complex tools! Run efficient load tests on APIs, microservices, and web applications. Integrate with CI/CD pipelines to automate performance testing. Gain deep insights with real-time performance metrics.
By mastering K6, you’ll gain the skills to predict failures before they happen, optimize performance, and build systems that scale with confidence!
Bootcamp Details
Date: Feb 23 2024 – Sunday Time: 10:30 AM Mode: Online (Link Will be shared in Email after RSVP) Language:தமிழ்
Who Should Attend?
Developers – Ensure APIs and services perform well under load.
QA Engineers – Validate system reliability before production.
SREs / DevOps Engineers – Continuously test performance in CI/CD pipelines.
RSVP Now
Don’t miss this opportunity to master load testing with K6 and take your performance engineering skills to the next level!
Got questions? Drop them in the comments or reach out to me. See you at the bootcamp!
A REST API (Representational State Transfer) is a web service that allows different applications to communicate over the internet using standard HTTP methods like GET, POST, PUT, and DELETE. It follows REST principles, making it lightweight, scalable, and easy to use.
REST API Principles
Client-Server Architecture
A REST API follows a client-server architecture, where the client and server are separate. The client sends requests, and the server processes them and responds, allowing different clients like web and mobile apps to communicate with the same backend.
Statelessness
Before understanding statelessness, you need to understand statefulness.
Statefulness: The server stores and manages user session data, such as authentication details and recent activities.
Statelessness: The server does not store any information. Each request is independent, and the client must include all necessary data, like authentication details and query parameters, in every request.
This behavior makes the server scalable, reliable, and reduces server load.
Caching
Caching improves performance by storing responses that can be reused, reducing the need for repeated requests to the server. This minimizes response time and server load.
Uniform Interface
A uniform interface ensures consistency by using standard HTTP methods like GET, POST, PUT, and DELETE. This makes the API predictable and easy to use.
Layered System
A layered system divides tasks into separate layers, like security, caching, and user requests. The client only interacts with the top layer, making the system easier to manage and more flexible.
Start To Code
I use Node.js and some popular packages:
Express: A Node.js web framework used for building web applications and APIs.
Joi: A package used to validate user input, ensuring data integrity and security.
basic code
const express = require("express");
const app = express();
const joi = require("joi");
app.use(express.json());
//data
customers = [
{name : "user1", id : 1},
{name : "user2", id : 2},
{name : "user3", id : 3}
]
//listen
const port = process.env.PORT || 8080;
app.listen(port, ()=> console.log("listening on ",port));
//function
function validateUserName(customer){
schema = joi.object({
name : joi.string().min(3).required()
});
return schema.validate(customer)
}
GET
GET is used to retrieve data from the server. the response code is 200 if successful.
app.delete('/api/customer/:id', (req,res)=>{
const user = customers.find(user => user.id == req.params.id);
index = customers.indexOf(user);
if(!user){
console.log("test")
res.status(404).send("Data Not Found");
}
else{
customers.splice(index,1);
res.status(200).send("successfully deleted");
}
});
What I Learned
CRUD Operations with REST API
I learned the basics of REST API and CRUD operations, including the uniform methods GET, POST, PUT, PATCH, and DELETE.
Status Codes
REST APIs strictly follow status codes:
200 – OK
201 – Created successfully
400 – Bad request
204 – No content
404 – Page not found
Joi Package
For server-side validation, the Joi package is used. It helps verify user data easily.
Middleware
Using app.use(express.json()) as middleware ensures that for POST, PATCH, and PUT methods, JSON-formatted user data is parsed into an object accessible via req.body.
S/w Used : HTML, CSS, JavaScript with LocalStorage for storing data (little Bootstrap)
Framework Used : Text Editor
Description : A small addressbook which is having name, email, contact no, and city which is having CRUD operations.
Till Today :
From v1.0, design changed completely.
Code done for Adding new Contact with modal window.
And whenever new entry added that will get displayed in the table dynamically with del and edit buttons.
Delete button action also done.
Alignment I could not able to do well, so took chatGPT help.
To Do:
Edit action and Search are pending.
Add New screen is not getting closed after adding – has to be rectified.
Design should get changed in AddNew screen
Table – Headings font size should get changed. (As used bootstrap table class – th is not getting changed through css – have to research in it.
Some Code duplication is there, have to be optimized like keep in one function (inside validationPassed & addNewContact).
Technical WorkFlow:
function validationPassed : This function checks all the fields are not empty.
function getAddrBook : This function returns an Array which extracts the existing contacts from localStorage, if available, and parse it. Otherwise an empty array will be returned.
function addNewContact : If validationPassed, then new contact entry is created from 4 fields (Name, Email, ContactNo and City), together will form an object and pushed into addrBook array (got through getAddrBook) and will get saved into localStorage. showBook() function is getting called immediately to show the added contact.
function showBook() : This is actually a table where rows(contacts) with delete and edit buttons are getting added dynamically and will be shown.
function deleteCont(idx) : As the name suggests it will take the index of the array as input and delete the contact when the delete button pressed.
JavaScript is a versatile programming language primarily used to create dynamic and interactive features on websites. JavaScript is a scripting language that allows you to implement complex features on web pages. Browsers have Interpreters. It will converts JAVASCRIPT code to machine code. Browsers have its own interpreters like
Chrome – V8-engine
Edge – Chakra
JavaScript- Identifiers :
var message; –> Variable (Identifier) message = ‘Javascript’;
func sayHello() { console.log(‘Hello’) }
//sayHello Is the identifier for this function.
//variables , objects,functions,arrays ,classes names are identifiers in js.
SCOPE : In JavaScript, scope refers to the context in which variables and functions are accessible. It determines the visibility and lifetime of these variables and functions within your code. There are three main types of scope in JavaScript.
Global Scope:.
Variables declared outside any function or block have global scope.
These variables are accessible from anywhere in the code
example :
let globalVar = "I'm global";
function test() {
console.log(globalVar); // Accessible here
}
test();
console.log(globalVar); // Accessible here too
Function Scope
Variables declared within a function are local to that function.
They cannot be accessed from outside the function.
example :
function test() {
let localVar = "I'm local";
console.log(localVar); // Accessible here
}
test();
console.log(localVar); // Error: localVar is not defined
Block Scope:
Introduced with ES6, variables declared with let or const within a block (e.g., inside {}) are only accessible within that block
example :
{
let blockVar = "I'm block-scoped";
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Error: blockVar is not defined
Keywords | Reserved Words
Keywords are reserved words in JavaScript that cannot use to indicate variable labels or function names.
Variables
variables ==> stored values ==> it will stored to ram / It will create separate memory.so we need memory address for access the values.
Stores Anything : JavaScript will store any value in the variable.
Declaring Variable :
* Var
* let
* const
we can declare variable using above keywords:
Initialize Variable :
Using assignment operator to assign the value to the variables.
var text = "hello";
JavaScript is a versatile programming language primarily used to create dynamic and interactive features on websites. JavaScript is a scripting language that allows you to implement complex features on web pages. Browsers have Interpreters. It will converts JAVASCRIPT code to machine code. Browsers have its own interpreters like
Chrome – V8-engine
Edge – Chakra
JavaScript- Identifiers :
var message; –> Variable (Identifier) message = ‘Javascript’;
func sayHello() { console.log(‘Hello’) }
//sayHello Is the identifier for this function.
//variables , objects,functions,arrays ,classes names are identifiers in js.
SCOPE : In JavaScript, scope refers to the context in which variables and functions are accessible. It determines the visibility and lifetime of these variables and functions within your code. There are three main types of scope in JavaScript.
Global Scope:.
Variables declared outside any function or block have global scope.
These variables are accessible from anywhere in the code
example :
let globalVar = "I'm global";
function test() {
console.log(globalVar); // Accessible here
}
test();
console.log(globalVar); // Accessible here too
Function Scope
Variables declared within a function are local to that function.
They cannot be accessed from outside the function.
example :
function test() {
let localVar = "I'm local";
console.log(localVar); // Accessible here
}
test();
console.log(localVar); // Error: localVar is not defined
Block Scope:
Introduced with ES6, variables declared with let or const within a block (e.g., inside {}) are only accessible within that block
example :
{
let blockVar = "I'm block-scoped";
console.log(blockVar); // Accessible here
}
console.log(blockVar); // Error: blockVar is not defined
Keywords | Reserved Words
Keywords are reserved words in JavaScript that cannot use to indicate variable labels or function names.
Variables
variables ==> stored values ==> it will stored to ram / It will create separate memory.so we need memory address for access the values.
Stores Anything : JavaScript will store any value in the variable.
Declaring Variable :
* Var
* let
* const
we can declare variable using above keywords:
Initialize Variable :
Using assignment operator to assign the value to the variables.
var text = "hello";