Monday, May 27, 2024

Javascript Course : Part - 3

 

21. Closures

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.

javascript
function outerFunction() { let outerVariable = "I'm outside!"; function innerFunction() { console.log(outerVariable); // Can access outerVariable } return innerFunction; } let closure = outerFunction(); closure(); // Outputs: I'm outside!

22. The this Keyword

The this keyword refers to the context in which a function is called.

javascript
let person = { name: 'Alice', greet: function() { console.log(`Hello, my name is ${this.name}`); } }; person.greet(); // Outputs: Hello, my name is Alice let greet = person.greet; greet(); // Outputs: Hello, my name is undefined (or could cause an error in strict mode)

To preserve the context of this, you can use bind, call, or apply.

bind

javascript
let boundGreet = person.greet.bind(person); boundGreet(); // Outputs: Hello, my name is Alice

23. Immediately Invoked Function Expressions (IIFE)

IIFE is a function that runs as soon as it is defined.

javascript
(function() { console.log("This is an IIFE"); })(); // Outputs: This is an IIFE

24. The Event Loop

JavaScript has a single-threaded event loop that manages the execution of asynchronous operations.

javascript
console.log('Start'); setTimeout(() => { console.log('Timeout'); }, 0); Promise.resolve().then(() => { console.log('Promise'); }); console.log('End'); // Output order: Start, End, Promise, Timeout

25. JSON

JSON (JavaScript Object Notation) is a format for storing and transporting data.

Parsing JSON

javascript
let jsonString = '{"name": "John", "age": 30}'; let obj = JSON.parse(jsonString); console.log(obj.name); // Outputs: John

Stringifying JSON

javascript
let obj = {name: "John", age: 30}; let jsonString = JSON.stringify(obj); console.log(jsonString); // Outputs: {"name":"John","age":30}

26. Regular Expressions

Regular expressions are patterns used to match character combinations in strings.

javascript
let text = "The quick brown fox"; let pattern = /quick/; let result = pattern.test(text); console.log(result); // Outputs: true

27. Browser Storage

Local Storage

Local storage allows you to store data on the user's browser.

javascript
localStorage.setItem('name', 'Alice'); let name = localStorage.getItem('name'); console.log(name); // Outputs: Alice localStorage.removeItem('name');

Session Storage

Session storage is similar to local storage, but data is cleared when the page session ends.

javascript
sessionStorage.setItem('name', 'Bob'); let name = sessionStorage.getItem('name'); console.log(name); // Outputs: Bob sessionStorage.removeItem('name');

28. setTimeout and setInterval

These functions are used to execute code after a delay or repeatedly at specified intervals.

setTimeout

javascript
setTimeout(() => { console.log('This runs after 2 seconds'); }, 2000);

setInterval

javascript
let count = 0; let intervalId = setInterval(() => { count++; console.log(`Count: ${count}`); if (count === 5) { clearInterval(intervalId); } }, 1000);

29. Debouncing and Throttling

Debouncing and throttling are techniques to control how often a function is executed.

Debouncing

Debouncing ensures a function is executed only after a specified delay has passed since it was last invoked.

javascript
function debounce(func, delay) { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => { func.apply(this, args); }, delay); }; } window.addEventListener('resize', debounce(() => { console.log('Resized'); }, 500));

Throttling

Throttling ensures a function is executed at most once in a specified period.

javascript
function throttle(func, limit) { let inThrottle; return function(...args) { if (!inThrottle) { func.apply(this, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } window.addEventListener('resize', throttle(() => { console.log('Resized'); }, 1000));

30. Web APIs

Web APIs are interfaces provided by browsers to interact with various browser functions and services.

Geolocation API

javascript
navigator.geolocation.getCurrentPosition((position) => { console.log(position.coords.latitude, position.coords.longitude); });

Fetch API

javascript
fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

31. Working with Dates

JavaScript provides the Date object for handling dates and times.

javascript
let now = new Date(); console.log(now); // Outputs current date and time let specificDate = new Date('2023-05-25'); console.log(specificDate); // Outputs: Thu May 25 2023

32. Template Literals for HTML

Template literals can be used to create HTML strings.

javascript
let name = 'John'; let html = ` <div> <h1>Hello, ${name}!</h1> <p>This is a template literal</p> </div> `; document.body.innerHTML = html;

33. Form Handling

JavaScript can handle form submissions and validate inputs.

html
<!DOCTYPE html> <html> <head> <title>Form Handling</title> </head> <body> <form id="myForm"> <input type="text" id="name" placeholder="Enter your name"> <button type="submit">Submit</button> </form> <script> document.getElementById('myForm').addEventListener('submit', function(event) { event.preventDefault(); let name = document.getElementById('name').value; alert(`Hello, ${name}!`); }); </script> </body> </html>

34. Responsive Design

JavaScript can be used to make web pages responsive.

javascript
window.addEventListener('resize', () => { if (window.innerWidth < 600) { document.body.style.backgroundColor = 'lightblue'; } else { document.body.style.backgroundColor = 'white'; } });

35. Using External Libraries

You can enhance your JavaScript projects using external libraries like jQuery, Lodash, and Axios.

jQuery Example

html
<!DOCTYPE html> <html> <head> <title>jQuery Example</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button id="btn">Click me</button> <script> $('#btn').click(function() { alert('Button clicked!'); }); </script> </body> </html>

36. ES6 Modules

ES6 modules provide a way to organize and share code between files.

Creating a Module

javascript
// file: myModule.js export const name = 'Alice'; export function greet() { return 'Hello!'; }

Using a Module

javascript
// file: main.js import { name, greet } from './myModule.js'; console.log(name); // Outputs: Alice console.log(greet()); // Outputs: Hello!

37. Advanced Array Methods

Learn about more advanced array methods such as reduce, find, some, and every.

reduce

javascript
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((total, num) => total + num, 0); console.log(sum); // Outputs: 15

find

javascript
let users = [ {id: 1, name: 'Alice'}, {id: 2, name: 'Bob'} ]; let user = users.find(user => user.id === 2); console.log(user); // Outputs: {id: 2, name: 'Bob'}

some

javascript
let hasEven = numbers.some(num => num % 2 === 0); console.log(hasEven); // Outputs: true

every

javascript
let allPositive = numbers.every(num => num > 0); console.log(allPositive); // Outputs: true

38. Proxy and Reflect

Proxies allow you to intercept and redefine operations for objects.

javascript
let person = { name: 'Alice', age: 25 }; let handler = { get: function(target, property) { return property in target ? target[property] : 'Not found'; } }; let proxy = new

Javascript course - 2

 

11. Promises and Async/Await

Promises are used to handle asynchronous operations in JavaScript.

Promises

javascript
let promise = new Promise((resolve, reject) => { let success = true; // Change to false to see the rejection if (success) { resolve("Promise resolved!"); } else { reject("Promise rejected!"); } }); promise.then((message) => { console.log(message); // Outputs: Promise resolved! }).catch((error) => { console.error(error); });

Async/Await

Async/Await makes it easier to work with promises.

javascript
async function fetchData() { try { let response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); let data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } fetchData();

12. Classes

Classes in JavaScript are syntactic sugar over the existing prototype-based inheritance.

javascript
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { return `Hello, my name is ${this.name} and I am ${this.age} years old.`; } } let john = new Person('John', 30); console.log(john.greet()); // Outputs: Hello, my name is John and I am 30 years old.

13. Modules

Modules in JavaScript allow you to break up your code into separate files and import/export functions, objects, or primitives.

Exporting

javascript
// file: myModule.js export const name = 'Alice'; export function greet() { return 'Hello!'; }

Importing

javascript
// file: main.js import { name, greet } from './myModule.js'; console.log(name); // Outputs: Alice console.log(greet()); // Outputs: Hello!

14. Error Handling

Error handling in JavaScript is done using try, catch, finally, and throw.

javascript
try { let result = riskyOperation(); console.log(result); } catch (error) { console.error('Error:', error.message); } finally { console.log('Operation attempted'); } function riskyOperation() { throw new Error('Something went wrong!'); }

15. Higher-Order Functions

Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them.

Example: map

javascript
let numbers = [1, 2, 3, 4, 5]; let doubled = numbers.map(function(num) { return num * 2; }); console.log(doubled); // Outputs: [2, 4, 6, 8, 10]

Example: filter

javascript
let numbers = [1, 2, 3, 4, 5]; let even = numbers.filter(function(num) { return num % 2 === 0; }); console.log(even); // Outputs: [2, 4]

16. Arrow Functions

Arrow functions provide a concise syntax for writing functions.

javascript
let add = (a, b) => a + b; console.log(add(2, 3)); // Outputs: 5 let greet = name => `Hello, ${name}!`; console.log(greet('Alice')); // Outputs: Hello, Alice!

17. Destructuring

Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.

Array Destructuring

javascript
let [first, second, third] = [1, 2, 3]; console.log(first); // Outputs: 1 console.log(second); // Outputs: 2 console.log(third); // Outputs: 3

Object Destructuring

javascript
let person = {name: 'John', age: 30}; let {name, age} = person; console.log(name); // Outputs: John console.log(age); // Outputs: 30

18. Spread and Rest Operators

The spread operator allows an iterable to expand in places where zero or more arguments are expected.

Spread Operator

javascript
let arr = [1, 2, 3]; let newArr = [...arr, 4, 5, 6]; console.log(newArr); // Outputs: [1, 2, 3, 4, 5, 6]

The rest operator allows you to represent an indefinite number of arguments as an array.

Rest Operator

javascript
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3)); // Outputs: 6 console.log(sum(4, 5, 6, 7)); // Outputs: 22

19. Template Literals

Template literals allow you to embed expressions inside string literals using backticks `.

javascript
let name = 'John'; let greeting = `Hello, ${name}!`; console.log(greeting); // Outputs: Hello, John!

20. Fetch API

The Fetch API is used to make HTTP requests in JavaScript.

javascript
fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

This should give you a comprehensive overview of more advanced JavaScript concepts. Feel free to ask if you need more details or specific examples on any topic!

ChatGPT can make mistakes. Check important info.

1. Introduction to JavaScript

 

1. Introduction to JavaScript

JavaScript can be added to an HTML document using the <script> tag. Here's a simple example of a complete HTML document with JavaScript:

html
<!DOCTYPE html> <html> <head> <title>JavaScript Example</title> </head> <body> <h1>Hello, JavaScript!</h1> <p id="demo"></p> <script> document.getElementById("demo").innerHTML = "Hello, World!"; </script> </body> </html>

2. Variables

Variables are used to store data values. In JavaScript, you can declare a variable using var, let, or const.

javascript
var name = "John"; let age = 30; const pi = 3.14; console.log(name); // Outputs: John console.log(age); // Outputs: 30 console.log(pi); // Outputs: 3.14

3. Data Types

JavaScript has several data types, including:

  • String: "Hello"
  • Number: 123
  • Boolean: true or false
  • Array: [1, 2, 3]
  • Object: {name: "John", age: 30}
  • Null: null
  • Undefined: undefined

4. Functions

Functions are blocks of code designed to perform a particular task. You can define a function using the function keyword.

javascript
function greet(name) { return "Hello, " + name; } console.log(greet("Alice")); // Outputs: Hello, Alice

5. Events

JavaScript can react to events, such as when a user clicks a button.

html
<!DOCTYPE html> <html> <head> <title>JavaScript Events</title> </head> <body> <button onclick="displayDate()">Click me</button> <p id="demo"></p> <script> function displayDate() { document.getElementById("demo").innerHTML = new Date(); } </script> </body> </html>

6. Conditional Statements

Conditional statements control the flow of code based on conditions.

javascript
let time = 20; if (time < 18) { console.log("Good day"); } else { console.log("Good evening"); }

7. Loops

Loops can execute a block of code a number of times.

javascript
for (let i = 0; i < 5; i++) { console.log("The number is " + i); }

8. Arrays

Arrays are used to store multiple values in a single variable.

javascript
let fruits = ["Apple", "Banana", "Cherry"]; console.log(fruits[0]); // Outputs: Apple console.log(fruits.length); // Outputs: 3

9. Objects

Objects are collections of properties, and a property is an association between a name (or key) and a value.

javascript
let person = { firstName: "John", lastName: "Doe", age: 25, fullName: function() { return this.firstName + " " + this.lastName; } }; console.log(person.fullName()); // Outputs: John Doe

10. DOM Manipulation

JavaScript can be used to change HTML content.

html
<!DOCTYPE html> <html> <head> <title>DOM Manipulation</title> </head> <body> <h1 id="header">Hello, World!</h1> <button onclick="changeText()">Change Text</button> <script> function changeText() { document.getElementById("header").innerHTML = "Hello, JavaScript!"; } </script> </body> </html>

This should give you a good foundation to start with JavaScript. Feel free to ask if you have any specific questions or need further examples!

Wednesday, March 13, 2024

React Navigation for multiple pages

 In React Native, React Navigation is a popular library used for managing navigation in your application. It provides several navigation solutions, including Stack Navigator, Tab Navigator, Drawer Navigator, and more. Here's a basic example of setting up navigation for multiple pages using React Navigation:

  1. First, make sure you have React Navigation installed in your project. You can install it via npm or yarn:
bash
npm install @react-navigation/native

or

bash
yarn add @react-navigation/native
  1. Install dependencies for the navigator you want to use. For example, if you want to use Stack Navigator:
bash
npm install react-native-screens react-native-safe-area-context

or

bash
yarn add react-native-screens react-native-safe-area-context
  1. Now, let's create some screens for navigation. For this example, let's create two screens: HomeScreen and DetailScreen.
jsx
// HomeScreen.js import React from 'react'; import { View, Text, Button } from 'react-native'; const HomeScreen = ({ navigation }) => { return ( <View> <Text>This is the Home Screen</Text> <Button title="Go to Details" onPress={() => navigation.navigate('Details')} /> </View> ); }; export default HomeScreen;
jsx
// DetailScreen.js import React from 'react'; import { View, Text } from 'react-native'; const DetailScreen = () => { return ( <View> <Text>This is the Detail Screen</Text> </View> ); }; export default DetailScreen;
  1. Now, let's set up the navigation structure in your main component.
jsx
// App.js import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import HomeScreen from './HomeScreen'; import DetailScreen from './DetailScreen'; const Stack = createStackNavigator(); const App = () => { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={HomeScreen} /> <Stack.Screen name="Details" component={DetailScreen} /> </Stack.Navigator> </NavigationContainer> ); }; export default App;
  1. Finally, make sure to render your App component in your index.js file or wherever you have your root component.
jsx
// index.js import React from 'react'; import { AppRegistry } from 'react-native'; import App from './App'; import { name as appName } from './app.json'; const Main = () => <App />; AppRegistry.registerComponent(appName, () => Main);

Now you should have a basic navigation setup with two screens: HomeScreen and DetailScreen. When you press the button on the HomeScreen, it should navigate to the DetailScreen. You can extend this navigation structure further by adding more screens and configuring the navigator according to your app's requirements.

Monday, January 1, 2024

What is the purpose of JSX in React? Does it offer any performance benefits over writing plain HTML/CSS/JS?

 JSX in React is a syntax extension that allows you to write HTML-like code directly within JavaScript. Its purpose is to make the creation of React components more intuitive and simpler by combining the power of JavaScript with the structure of HTML.

JSX provides several advantages:

  1. Simplified Syntax: JSX makes it easier to visualize and write component structures by resembling HTML, which developers are generally more familiar with. It allows embedding JavaScript expressions within curly braces {} directly in the markup.

  2. Component Rendering: JSX simplifies the rendering of React components, enabling the use of familiar HTML-like tags to define UI components. This declarative style often leads to more readable and maintainable code.

  3. JavaScript Power: Being embedded within JavaScript, JSX allows leveraging the full power of JavaScript expressions, such as variables, loops, and conditional statements, directly within the markup.

Regarding performance benefits, JSX itself doesn’t offer direct performance improvements over writing plain HTML/CSS/JS. When JSX is transpiled (converted) into JavaScript by tools like Babel, it essentially transforms JSX into plain JavaScript function calls (React.createElement()). React then uses these function calls to construct the virtual DOM, which it uses for efficient updates.

React's performance gains come from its virtual DOM implementation, not directly from JSX. The virtual DOM enables React to efficiently update the actual DOM by first updating a lightweight representation of it. When changes occur, React compares the virtual DOM with the actual DOM and applies only the necessary updates, minimizing direct manipulations to the browser's DOM, which can be costly in terms of performance.

While JSX itself doesn’t improve performance, React's underlying mechanisms, combined with JSX's ease of use and developer ergonomics, contribute to creating more performant web applications.

Thursday, July 27, 2023

Securing your CDN: Why and how should you use SRI

 

Securing your Content Delivery Network (CDN) is essential to protect your website's visitors from potential security risks, such as content tampering and data breaches. One effective method to enhance the security of your CDN-served content is by using Subresource Integrity (SRI).

Subresource Integrity (SRI) is a security feature that allows you to ensure the integrity and authenticity of your CDN-hosted resources, such as JavaScript files, CSS stylesheets, and fonts. It works by adding an extra layer of validation to the way these resources are loaded on your website. When SRI is used, the browser checks the integrity of the resource before executing or rendering it, ensuring that it hasn't been altered or compromised in transit.

Here's why and how you should use SRI with your CDN:

1. Preventing Code Injection and Tampering: SRI helps prevent code injection attacks, where malicious actors can modify your CDN resources and introduce harmful code into your website. By ensuring the integrity of the resources, SRI prevents the browser from executing altered code.

2. Protecting User Data: If your website includes scripts from third-party sources (e.g., external libraries), using SRI ensures that these scripts are served from the intended sources. It prevents potential man-in-the-middle attacks and safeguards user data from being leaked or manipulated.

3. Ensuring Consistent User Experience: SRI ensures that your website's resources are loaded as intended, without any unauthorized modifications. This consistency is crucial for providing a reliable and trustworthy user experience.

How to Implement SRI:

  1. Generate Hashes for Your Resources: The first step is to generate the cryptographic hashes (specifically, SHA-256) for each of the resources you want to protect. These hashes will act as a unique fingerprint for the files.

  2. Add SRI Attributes to Resource Links: Once you have the hashes, add the "integrity" attribute to the HTML tags that reference the resources. The attribute's value should be in the following format:

    makefile
  1. integrity="sha256-abcdef1234567890..."
  2. Specify the Resource's Origin: For added security, it's recommended to include the "crossorigin" attribute in the resource link. This attribute helps define how the browser handles requests based on the resource's origin. For CDNs, you can use "anonymous" or "use-credentials" as the value.

Example of Using SRI with a Script Tag:

html
<script src="https://cdn.example.com/jquery.js" integrity="sha256-abcdef1234567890..." crossorigin="anonymous"></script>

Important Considerations:

  • Ensure that your CDN supports serving resources with SRI attributes. Most reputable CDNs provide this feature.

  • Periodically review and update the SRI hashes when the resources change to maintain their accuracy and effectiveness.

  • While SRI helps protect your users from some security risks, it's not a substitute for other security measures like HTTPS. Always use HTTPS to secure your entire website.

By using Subresource Integrity (SRI) with your CDN-served resources, you can significantly enhance the security of your website and protect your users from potential security threats arising from compromised resources.

Sponsered

 

© 2013 Psd to Html Blog. All rights resevered. Designed by Templateism

Back To Top