Data Analytics
29.1K subscribers
499 photos
15 videos
46 files
294 links
Dive into the world of Data Analytics – uncover insights, explore trends, and master data-driven decision making.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Data Analytics
function oldFetch(url, callback) { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.status === 200) { callback(JSON.parse(xhr.response)); } else { callback(null, xhr.status); } }; xhr.send();…
# 📚 JavaScript Tutorial - Part 6/10: Modules & Modern JavaScript
#JavaScript #ES6 #Modules #Webpack #ModernJS

Welcome to Part 6 of our JavaScript series! Today we'll explore code organization with modules and modern JavaScript features that revolutionized frontend development.

---

## 🔹 JavaScript Modules
### 1. Module Systems Comparison
| System | Syntax | Environment | Features |
|--------------|-----------------|--------------|----------|
| ES Modules | import/export | Modern browsers, Node.js | Native standard |
| CommonJS | require/module.exports | Node.js | Legacy Node |
| AMD | define/require | Browser | Async loading |

### 2. ES Modules (ES6)
#### Exporting:
// Named exports (multiple per file)
export const API_URL = 'https://api.example.com';
export function fetchData() { /* ... */ }

// Default export (one per file)
export default class User { /* ... */ }


#### Importing:
// Named imports
import { API_URL, fetchData } from './utils.js';

// Default import
import User from './models/User.js';

// Mixed imports
import User, { API_URL } from './config.js';

// Import everything
import * as utils from './utils.js';


### 3. HTML Integration
<script type="module">
import { initApp } from './app.js';
initApp();
</script>


---

## 🔹 Modern JavaScript Features
### 1. Block-Scoped Declarations (ES6)
let x = 10;    // Block-scoped variable
const PI = 3.14; // Block-scoped constant


### 2. Template Literals (ES6)
const name = 'Ali';
console.log(`Hello ${name}! Today is ${new Date().toLocaleDateString()}`);


### 3. Arrow Functions (ES6)
const add = (a, b) => a + b;
[1, 2, 3].map(n => n * 2);


### 4. Destructuring (ES6)
// Array destructuring
const [first, second] = [1, 2];

// Object destructuring
const { name, age } = user;


### 5. Spread/Rest Operator (ES6)
// Spread
const nums = [1, 2, 3];
const newNums = [...nums, 4, 5];

// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}


### 6. Optional Chaining (ES2020)
const street = user?.address?.street; // No error if null


### 7. Nullish Coalescing (ES2020)
const limit = config.maxItems ?? 10; // Only if null/undefined


---

## 🔹 JavaScript Tooling
### 1. Package Management with npm/yarn
npm init -y                 # Initialize project
npm install lodash # Install package
npm install --save-dev webpack # Dev dependency


### 2. Module Bundlers
#### Webpack Configuration (webpack.config.js):
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};


### 3. Babel (JavaScript Compiler)
#### .babelrc Configuration:
{
"presets": ["@babel/preset-env"],
"plugins": ["@babel/plugin-transform-runtime"]
}


### 4. ESLint (Code Linter)
#### .eslintrc.json Example:
{
"extends": "eslint:recommended",
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "single"]
}
}


---

## 🔹 Practical Example: Modular App Structure
project/
├── src/
│ ├── index.js # Entry point
│ ├── utils/ # Helper modules
│ │ ├── api.js # API functions
│ │ └── dom.js # DOM helpers
│ ├── components/ # UI components
│ │ ├── header.js
│ │ └── modal.js
│ └── styles/
│ └── main.css # Imported in JS
├── package.json # npm config
├── webpack.config.js # Bundler config
└── .babelrc # Compiler config


Example Component (`components/header.js`):
export function createHeader(title) {
const header = document.createElement('header');
header.innerHTML = `<h1>${title}</h1>`;
return header;
}


Main Entry Point (`index.js`):
import { createHeader } from './components/header.js';
import { fetchPosts } from './utils/api.js';

document.body.appendChild(createHeader('My Blog'));

async function init() {
const posts = await fetchPosts();
console.log('Loaded posts:', posts);
}

init();


---
2