The this keyword
The
this keyword in JavaScript refers to the current object that the
function is operating on. It is commonly used in object methods to access properties and methods of the
object.
Explanation:
- In a
method of an object, this refers to the object itself.
- In a
regular function, this refers to the global object (in browsers, it's the
window object).
Example:
PRACTICAL
const person = {
firstName: 'John',
lastName: 'Doe',
fullName: function()
{
return
this.firstName + ' ' + this.lastName;
}
};
console.log(person.fullName()); // Output: John Doe
In this example, the this keyword inside the fullName method
refers to the person object. When person.fullName() is called, this.firstName
and this.lastName access the firstName and lastName properties of the person
object, and the result is "John Doe".
Key points:
- Inside
the method, this refers to the object (person).
- this
allows you to dynamically access properties of the object.
2. An arrow function
An arrow function in JavaScript
is a shorter and more concise way to write functions. It uses the => syntax.
Arrow functions are often used for their simplicity and to avoid issues with
the this keyword, as they do not bind their own this value; instead, they
inherit it from the surrounding scope.
Syntax:
const functionName = (parameters)
=> {
// function body
};
Example:
PRACTICAL
#addition program using arrow
const addition = (a, b) => {
return a + b;
};
// Example usage
console.log(addition(5, 10));
// Output: 15
JavaScript Functions
In JavaScript, a function is a
block of code designed to perform a particular task. You can define a function
once and then call it whenever needed. Functions allow you to avoid repeating
code.
Why Functions?
With functions you can reuse
code
You can write code that can be
used many times.
You can use the same code with
different arguments, to produce different results.
Basic Syntax of a Function:
function functionName(parameters)
{
// Function body
// Code to be executed
}
- functionName:
The name of the function.
- parameters:
Values you pass into the function (optional).
- Function
body: The code that runs when the function is called.
Example 1: Simple
Function
function greet() {
console.log("Hello, World!");
}
greet(); // Calling the
function
- In
this example, the function simply prints "Hello, World!" when
called.greet
Example 2: Function
with Parameters
A function can accept
parameters that allow it to work with different values each time it is called.
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); //
Output: 8
console.log(add(10, 20)); //
Output: 30
Global and Local Variables in
JavaScript:
1.
Global Variable: A variable declared outside of any function or block. It is accessible
from anywhere in the program, including inside functions.
// Global
variable
let courseName = 'hello dcs';
function myFunction() {
console.log(courseName);
}
myFunction()
2.
Local Variable: A variable declared within a function or block. It is only accessible
within that function or block and cannot be accessed from outside.
function myFunction() {
let carName = "Volvo";
console.log(carName);
// code here CAN use carName
}
myFunction();
JavaScript Error:
An error in JavaScript
occurs when something goes wrong while the code is running. It can be caused by
a mistake in the syntax, logic, or operations of the program.
Types of JavaScript Errors:
- Syntax
Errors:
- These
happen when the JavaScript code is written incorrectly, like missing
parentheses or semicolons.
- Example:
let x = 5 // Missing semicolon
console.log(x);
- Reference
Errors:
- These
occur when you try to use a variable or function that hasn't been
declared.
- Example:
console.log(y); // Error: y is not defined
- Type
Errors:
- These
happen when a value is not of the expected type, like trying to call a
method on undefined.
- Example:
let num = 10;
num.toUpperCase(); // Error: num is not a string
- Range
Errors:
- These
occur when a value is out of range, like an invalid array index.
- Example:
let arr = [1, 2, 3];
console.log(arr[5]); // Error: undefined (out of range)
How to
Handle Errors:
You can handle errors using a
try...catch block to prevent the program from crashing.
Example:
try {
let result = someUndefinedFunction();
// This will cause an error
} catch (error) {
console.log("Error caught: " + error.message); // Handles the error
}
Key Points:
- Syntax
Errors: Mistakes in the code structure.
- Reference
Errors: Using undeclared variables or functions.
- Type
Errors: Using values in the wrong way (e.g., calling a method on a
number).
- Range
Errors: Accessing values out of range (e.g., array index).
Errors can be avoided by writing
correct code, but when they occur, you can use try...catch to handle them
gracefully!
Cookies in JavaScript:
Cookies are small pieces
of data that are stored in the browser and can be used to remember information
(like user preferences or login status) across different web pages or sessions.
How Cookies Work:
- Cookies
are stored on the user's computer by the browser.
- They
are sent with every HTTP request to the server.
- Cookies
can store simple data, like text or numbers, and have an expiration date.
Setting a Cookie:
To set a cookie, we use
document.cookie.
Syntax:
document.cookie =
"key=value; expires=expiration_date; path=/";
- key:
The name of the cookie.
- value:
The value of the cookie.
- expires:
The date and time when the cookie will expire.
- path:
The path where the cookie is valid (often / for the entire website).
Example: Setting and Getting a
Cookie
PRACTICAL
// Set a cookie
document.cookie =
"username=JohnDoe; expires=Thu, 31 Dec 2025 12:00:00 UTC; path=/";
// Get the cookie value
let cookies = document.cookie;
console.log(cookies); // Output: "username=JohnDoe"
Explanation:
- Setting
the Cookie:
- The
cookie username=JohnDoe is created with an expiration date of 31 Dec
2025.
- The
path=/ part means the cookie is available across the entire site.
- Getting
the Cookie:
- The
value of all cookies is stored in document.cookie.
- The
console.log(cookies) will print out all cookies stored in the browser.
Cookies Expiration:
- If
you don’t set an expires attribute, the cookie will be stored only for the
current session (until the browser is closed).
- To
set a specific expiration date, you can use the Date object to
create a future date.
Key Points:
- Cookies
store small pieces of data in the user's browser.
- You
can set, get, and delete cookies.
- Cookies
are useful for remembering user preferences, login states, etc.
- Cookies
can have an expiration date and are limited in size (usually 4 KB).
Web Storage in JavaScript:
Web Storage allows you to store
data in the browser, which persists even after the browser is closed and
reopened. It's a simple way to store small amounts of data on the client side.
There are two types of Web
Storage:
- Local
Storage: Stores data with no expiration time. Data is saved until
explicitly deleted.
- Session
Storage: Stores data for the duration of the page session. Data is
deleted when the browser tab or window is closed.
1. Local Storage:
- Local
Storage allows you to store data that persists even after the browser
is closed or restarted.
- It
can hold data as key-value pairs.
Syntax:
- localStorage.setItem(key,
value) — Stores data.
- localStorage.getItem(key)
— Retrieves data.
- localStorage.removeItem(key)
— Removes data.
- localStorage.clear()
— Clears all data.
Example: Using Local Storage
// Set an item
localStorage.setItem("username",
"JohnDoe");
// Get an item
let username =
localStorage.getItem("username");
console.log(username); // Output: "JohnDoe"
// Remove an item
localStorage.removeItem("username");
// Clear all items
localStorage.clear();
2. Session Storage:
- Session
Storage stores data for the duration of the page session.
- It
is cleared when the page is closed.
Syntax:
- sessionStorage.setItem(key,
value) — Stores data.
- sessionStorage.getItem(key)
— Retrieves data.
- sessionStorage.removeItem(key)
— Removes data.
- sessionStorage.clear()
— Clears all data.
Example: Using Session Storage
// Set an item in session
storage
sessionStorage.setItem("sessionID",
"12345");
// Get an item
let sessionID =
sessionStorage.getItem("sessionID");
console.log(sessionID); // Output: "12345"
// Remove an item
sessionStorage.removeItem("sessionID");
// Clear all items
sessionStorage.clear();
Key Differences Between Local
Storage and Session Storage:
- Local
Storage: Data persists until explicitly deleted, even if the browser
is closed.
- Session
Storage: Data is cleared when the browser or tab is closed.
Key Points:
- Web
Storage is client-side storage, meaning data is stored in the
user's browser.
- Local
Storage is for long-term storage, while Session Storage is for
temporary storage during a session.
- Both
storage types store data as key-value pairs.
Key Differences:
Local Storage |
Session Storage |
Data remains even after the
browser is closed. |
Data is deleted when the
browser tab or window is closed. |
Data must be explicitly
deleted. |
Data is automatically deleted. |
comparison:
Cookies vs. Web Storage
Feature |
Cookies |
Local Storage |
Session Storage |
Storage Limit |
~4KB |
~5MB |
~5MB |
Expiration |
Set by developer |
Persistent |
Session-based |
Sent with HTTP Request |
Yes |
No |
No |
Accessibility |
Both client and server |
Client-only |
Client-only |
f
The Geolocation API allows
a website to access your current location (latitude and longitude) with your
permission. This is commonly used in apps like maps or weather websites.
How It Works:
- The
browser asks for your permission to get your location.
- If permission
is granted, the website gets your coordinates.
- The
website can use this information to provide location-based services.
Locate the User's Position
The HTML Geolocation API is used to get the geographical position
of a user.
Since this can compromise privacy, the position is not available
unless the user approves it.
The getCurrentPosition() method is used to return the
user's position.
2. Drag-and-Drop API
The Drag-and-Drop
API lets users move items (drag) and place them in specific areas (drop).
This is used in file upload
systems or games where objects are rearranged.
How It Works:
- You
click and hold an item to drag it.
- Move
it to a specific area called the "drop zone."
- Release
the item to "drop" it into the new area.
Summary
- Geolocation
API: Determines the user's location for location-based features.
- Drag-and-Drop
API: Enables interactive actions like moving items and rearranging
elements.
0 Comments