Important Topic Of Javascript With Syntax Example

Important Topic Of Javascript With Syntax Example

Basic Syntax and Structure

Functions

  function greet(name) {
    return `Hello, ${name}`;
  }
  • Function Expressions: Functions defined as part of expressions.
  const greet = function(name) {
    return `Hello, ${name}`;
  };
  • Arrow Functions: Shorter syntax, with lexical this.
  const greet = (name) => `Hello, ${name}`;
  function map(arr, fn) {
    return arr.map(fn);
  }

Objects and Arrays

  • Object Literals: Key-value pairs representing structured data.
  const person = {
    name: 'John',
    age: 30,
  };
  • Array Methods: Methods for manipulating arrays.
  const numbers = [1, 2, 3, 4];
  numbers.push(5); // Adds to the end
  • Destructuring: Extracting values from arrays or objects.
  const { name, age } = person;
  const [first, second] = numbers;

DOM Manipulation

  • Selecting Elements:
  const element = document.getElementById('myId');
  const elements = document.querySelectorAll('.myClass');
  • Modifying Elements:
  element.textContent = 'New Content';
  element.style.color = 'red';
  • Event Handling:
  element.addEventListener('click', () => {
    console.log('Element clicked');
  });

Event Loop and Asynchronous Programming

  • Event Loop: Handles asynchronous operations in JavaScript, allowing non-blocking behavior.
  • Callbacks:
  setTimeout(() => {
    console.log('Executed after 1 second');
  }, 1000);
  • Promises:
  const promise = new Promise((resolve, reject) => {
    // asynchronous operation
  });

  promise.then(result => {
    // handle success
  }).catch(error => {
    // handle error
  });
  • Async/Await:
  async function fetchData() {
    const response = await fetch('url');
    const data = await response.json();
    console.log(data);
  }

Scope and Closures

  • Scope: Defines the accessibility of variables:
  • Global Scope: Variables accessible everywhere.
  • Function Scope: Variables accessible within a function.
  • Block Scope: Variables accessible within a block (let, const).
  • Closures: Functions that retain access to their scope even when the function is executed outside that scope.
  function outer() {
    const outerVar = 'I am outside!';
    function inner() {
      console.log(outerVar);
    }
    return inner;
  }

  const innerFn = outer();
  innerFn(); // Logs: 'I am outside!'

ES6+ Features

  • Template Literals:
  const greeting = `Hello, ${name}`;
  • Default Parameters:
  function greet(name = 'Guest') {
    return `Hello, ${name}`;
  }
  • Rest and Spread Operators:
  function sum(...args) {
    return args.reduce((acc, curr) => acc + curr, 0);
  }

  const arr1 = [1, 2, 3];
  const arr2 = [...arr1, 4, 5, 6];
  • Modules:
  // Exporting
  export const myVar = 42;
  export function myFunction() {}

  // Importing
  import { myVar, myFunction } from './myModule';

Error Handling

  • Try-Catch:
  try {
    // Code that may throw an error
  } catch (error) {
    // Handle the error
  } finally {
    // Execute code after try or catch
  }
  • Throwing Errors:
  function divide(a, b) {
    if (b === 0) {
      throw new Error('Division by zero');
    }
    return a / b;
  }

JavaScript Objects and Prototypes

  • Prototypal Inheritance: Objects can inherit properties and methods from other objects.
  function Person(name) {
    this.name = name;
  }

  Person.prototype.greet = function() {
    return `Hello, ${this.name}`;
  };

  const john = new Person('John');
  john.greet(); // 'Hello, John'
  • Object-Oriented Programming: Using classes and constructors.
  class Person {
    constructor(name) {
      this.name = name;
    }

    greet() {
      return `Hello, ${this.name}`;
    }
  }

  const jane = new Person('Jane');
  jane.greet(); // 'Hello, Jane'

APIs and AJAX

  • Fetch API:
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  • XMLHttpRequest:
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://api.example.com/data', true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      console.log(JSON.parse(xhr.responseText));
    }
  };
  xhr.send();
  • Working with JSON:
  const jsonString = '{"name": "John", "age": 30}';
  const jsonObject = JSON.parse(jsonString);

  const newJsonString = JSON.stringify(jsonObject);

Front-End Frameworks and Libraries

  • React: A library for building user interfaces with components.
  • Angular: A framework for building complex, single-page applications.
  • Vue: A progressive framework for building user interfaces.

Back-End Development

  • Node.js: A runtime for executing JavaScript on the server.
  const http = require('http');

  const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, world!\n');
  });

  server.listen(3000, '127.0.0.1', () => {
    console.log('Server running at http://127.0.0.1:3000/');
  });
  • Express.js: A web framework for Node.js.
  const express = require('express');
  const app = express();

  app.get('/', (req, res) => {
    res.send('Hello, world!');
  });

  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Web Storage

  • LocalStorage and SessionStorage:
  localStorage.setItem('key', 'value');
  const value = localStorage.getItem('key');
  localStorage.removeItem('key');

  sessionStorage.setItem('key', 'value');
  const value = sessionStorage.getItem('key');
  sessionStorage.removeItem('key');
  • Cookies:
  document.cookie = "username=John Doe; expires=Thu, 18 Dec 2024 12:00:00 UTC; path=/";

Build Tools and Package Managers

npm and Yarn: Tools for managing project dependencies.

  npm install package-name
  yarn add package-name
  • Webpack and Babel: Tools for bundling and transpiling JavaScript code.

Testing

  • Unit Testing: Writing tests for individual units of code.
  const sum = (a, b) => a + b;
  module.exports = sum;

  const sum = require('./sum');
  test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
  });
  • Integration Testing: Testing how different parts of an application work together.

Performance Optimization

  • Minification and Compression: Reducing file sizes for faster load times.
  • Lazy Loading: Loading resources only when they are needed.
  • Debouncing and Throttling: Controlling the rate of function execution to improve performance.

Security

  • Cross-Site Scripting (XSS): Preventing malicious code injection by sanitizing input.
  • Cross-Site Request Forgery (CSRF): Protecting against unauthorized actions by using tokens.

Web Components

  • Custom Elements: Creating reusable custom HTML elements.
  class MyElement extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
    }
  }

  customElements.define('my-element', MyElement);
  • Shadow DOM: Encapsulating styles and markup to avoid conflicts.
  const shadow = this.attachShadow({ mode: 'open' });
  shadow.innerHTML = `<style>h1 { color: red; }</style><h1>Hello Shadow DOM</h1>`;

Progressive Web Apps (PWAs)

  • Service Workers: Enabling offline capabilities and caching.
  self.addEventListener('install', event => {
    event.waitUntil(
      caches.open('v1').then(cache => {
        return cache.addAll([
          '/',
          '/index.html',
          '/style.css',
          '/app.js',
        ]);
      })
    );
  });

  self.addEventListener('fetch', event => {
    event.respondWith(
      caches.match(event.request).then(response => {
        return response || fetch(event.request);
      })
    );
  });
  • Web App Manifest: Providing metadata for web apps.
  {
    "name": "My App",
    "short_name": "App",
    "start_url": "/",
    "display": "standalone",
    "background_color": "#ffffff",
    "theme_color": "#000000",
    "icons": [
      {
        "src": "/icon.png",
        "sizes": "192x192",
        "type": "image/png"
      }
    ]
  }

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *