Introduction to JavaScript and TypeScript

Université de Toulon

LIS UMR CNRS 7020

2024-11-03

What is JavaScript?

  • Importance of JavaScript in Modern Web Development:
    • JavaScript is a versatile and powerful programming language that is essential for creating interactive and dynamic web applications.
    • It is supported by all modern web browsers, making it a universal language for web development.
    • JavaScript enables developers to create rich user interfaces, handle user interactions, and communicate with servers asynchronously.
  • Definition and Role in Web Development:
    • JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification.
    • It is primarily used for client-side scripting to enhance the functionality and interactivity of web pages.
    • JavaScript can also be used on the server-side with environments like Node.js, allowing for full-stack development using a single language.

Client vs. Server-side JavaScript

  • Client-side vs. Server-side JavaScript:
    • Client-side JavaScript:
      • Runs in the user’s web browser.
      • Manipulates the Document Object Model (DOM) to update the content and style of web pages dynamically.
      • Handles user events such as clicks, form submissions, and keyboard input.
      • Examples: Form validation, interactive maps, animations.
    • Server-side JavaScript:
      • Runs on a web server using environments like Node.js (so in Remix).
      • Handles server-side logic, database interactions, and API requests.
      • Generates dynamic content and serves it to the client.
      • Examples: RESTful APIs, real-time chat applications, server-side rendering.

History and Evolution of JavaScript

  • Brief History of JavaScript:
    • JavaScript was created by Brendan Eich in 1995 while working at Netscape Communications Corporation.
    • JavaScript was designed to be a lightweight scripting language for adding interactivity to web pages.
  • Key Milestones in Its Evolution:
    • 1995: JavaScript 1.0 released with Netscape Navigator 2.0.
    • 1996: Microsoft introduced JScript with Internet Explorer 3.0, leading to cross-browser compatibility issues.
    • 1997: ECMAScript standardization (ECMA-262) by Ecma International to ensure consistency across different implementations.
    • 2024: ECMAScript 2024 (ES15).

Key Features

  • Dynamic Typing:
    • JavaScript is dynamically typed, meaning variables can hold values of any type without explicit type declarations.
    • This flexibility allows for rapid development and prototyping but requires careful handling to avoid type-related errors.
  • First-class Functions:
    • Functions in JavaScript are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from functions.
    • This feature enables powerful programming paradigms such as functional programming and higher-order functions.
  • Event-driven Programming:
    • JavaScript is inherently event-driven, allowing developers to write code that responds to user actions, network events, and other asynchronous events.
    • Event listeners and callbacks are used to handle events and execute code in response to them.

Use Cases

  • Web Development: Enhancing the interactivity and functionality of web pages through DOM manipulation, form validation, and AJAX requests.
  • Server-side Scripting: Building scalable and efficient server-side applications using Node.js, Express.js, and other frameworks.
  • Mobile App Development: Creating cross-platform mobile applications using frameworks like React Native and Ionic.
  • Desktop App Development: Building desktop applications with Electron, which allows JavaScript, HTML, and CSS to be used for creating native desktop apps.
  • Game Development: Developing browser-based games using libraries like Phaser and Three.js.
  • Internet of Things (IoT): Writing JavaScript code for IoT devices using platforms like Node-RED.

JavaScript in a Web Browser

  • JavaScript can be executed directly in the browser.

  • You can include JavaScript code in HTML files using the <script> tag.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript Example</title>
    </head>
    <body>
        <h1>Welcome to JavaScript</h1>
        <p>This is a simple example of embedding JavaScript in an HTML document.</p>
    
        <script>
            console.log("Hello, World!");
        </script>
        <!-- You can also link to an external JavaScript file using the <script> tag with the src attribute. -->
        <!--
        <script src="script.js"></script>
        -->
    </body>
    </html>
  • To open the console in most browsers, press F12 or Ctrl+Shift+I and navigate to the “Console” tab.

On a Server with Node.js

  • Node.js allows you to run JavaScript on the server-side.

  • Install Node.js from nodejs.org.

  • Run JavaScript files using the node command.

    // save as app.js
    console.log("Hello, Node.js!");
    node app.js

Declaring Variables

  • Using var, let, and const:
    • let: Block-scoped, can be updated but not redeclared.

    • const: Block-scoped, cannot be updated or redeclared.

      var name = "Alice";
      let age = 30;
      const isStudent = true;
    • var: Function-scoped, can be redeclared and updatedd (avoid using var in modern JavaScript).

Data Types and Values

  • Primitive Types:
    • string, number, boolean, null, undefined, symbol

      let name = "Alice"; // string
      let age = 30; // number
      let isStudent = true; // boolean
      let unknown = null; // null
      let notDefined; // undefined
      let uniqueId = Symbol("id"); // symbol
  • Reference Types:
    • object, array, function

      let person = { name: "Alice", age: 30 }; // object
      let numbers = [1, 2, 3]; // array
      function greet() { console.log("Hello!"); } // function
  • Differences Between Primitive and Reference Values:
    • Primitive values are stored directly in the variable.
    • Reference values store a reference to the memory location where the object is stored.

Comments

  • Single-line and Multi-line Comments:
    • Single-line comment: // This is a comment

    • Multi-line comment: /* This is a multi-line comment */

      // This is a single-line comment
      let x = 10; /* This is a multi-line comment */

Expressions and Statements

  • Understanding Expressions and Statements:
    • Expression: Produces a value (e.g., 2 + 2, name = "Alice")

    • Statement: Performs an action (e.g., let x = 10;, if (x > 5) { ... })

      let sum = 2 + 2; // Expression
      console.log(sum); // Statement

Operators

  • Arithmetic, Comparison, Logical, and Assignment Operators:
    • Arithmetic: +, -, *, /, %
    • Comparison: ==, ===, !=, !==, >, <, >=, <=
    • Logical: &&, ||, !
    • Assignment: =, +=, -=, *=, /=

Comparison Operators: == vs ===

  • == (Equality Operator):
    • Compares two values for equality after converting both values to a common type (type coercion).

    • Example:

      console.log(5 == '5'); // Output: true
    • In the example above, the string '5' is converted to the number 5 before comparison.

  • === (Strict Equality Operator):
    • Compares two values for equality without converting them to a common type (no type coercion).

    • Example:

      console.log(5 === '5'); // Output: false
    • In the example above, the comparison returns false because the types of the values are different (number vs. string).

let a = 10;
let b = 5;
let sum = a + b; // Arithmetic
let isEqual = (a === b); // Comparison
let isBothTrue = (a > 0 && b > 0); // Logical
a += 5; // Assignment

Strings

A string is a sequence of characters enclosed in single quotes (') or double quotes ("). It’s a fundamental data type in JavaScript used to represent text.

let str = "Hello, World!";

// Length of the string
console.log(str.length); // Output: 13

// Convert to uppercase
console.log(str.toUpperCase()); // Output: HELLO, WORLD!

// Extract a substring
console.log(str.slice(7, 12)); // Output: World

// Split the string into an array of words
let words = str.split(" ");
console.log(words); // Output: ["Hello,", "World!"]

String Methods and Properties

Common Methods:

  • length: Returns the length of the string.
  • toUpperCase(): Converts the string to uppercase.
  • toLowerCase(): Converts the string to lowercase.
  • concat(str1, str2, ...): Concatenates strings.
  • indexOf(searchValue, fromIndex): Returns the index of the first occurrence of a substring.
  • lastIndexOf(searchValue, fromIndex): Returns the index of the last occurrence of a substring.
  • slice(start, end): Extracts a section of a string.
  • substring(start, end): Extracts a section of a string.
  • substr(start, length): Extracts a section of a string.
  • split(separator): Splits a string into an array of substrings.
  • replace(searchValue, newValue): Replaces occurrences of a substring.
  • trim(): Removes whitespace from both ends of a string.
  • charAt(index): Returns the character at a specific index.
  • charCodeAt(index): Returns the Unicode of the character at a specific index.

String Manipulation Techniques

Concatenation:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe

Template Literals (String Interpolation):

let age = 30;
let message = `My name is ${firstName} ${lastName} and I am ${age} years old.`;
console.log(message); // Output: My name is John Doe and I am 30 years old.

Using Regular Expressions in JavaScript

Regular expressions (regex) are patterns used to match character combinations in strings. JavaScript provides the RegExp object for working with regular expressions.

const regex = /hello/;
const result = regex.test('hello world');
console.log(result); // Output: true

const negativeResult = regex.test('goodbye world');
console.log(negativeResult); // Output: false

Creating Regular Expressions

  • Literal Notation: javascript const regex = /hello/;

  • Constructor Notation: javascript const regex = new RegExp('hello');

Common Methods

  • test Method: javascript const regex = /hello/; const result = regex.test('hello world'); console.log(result); // Output: true

  • exec Method: javascript const regex = /hello/; const result = regex.exec('hello world'); console.log(result); // Output: ["hello", index: 0, input: "hello world", groups: undefined]

String Methods with Regex

```javascript
const text = 'The rain in Spain stays mainly in the plain.';
const regex = /ain/g;

// match
const matches = text.match(regex);
console.log(matches); // Output: ["ain", "ain", "ain", "ain"]

// replace
const newText = text.replace(regex, 'ain\'t');
console.log(newText); // Output: The rain't in Spain't stays mainly in the plain't.

// search
const position = text.search(regex);
console.log(position); // Output: 5

// split
const parts = text.split(regex);
console.log(parts); // Output: ["The r", " in Sp", " stays m", "ly in the pl", "."]
```

Regular Expression Patterns

  • Character Classes:
    • \d: Matches any digit (0-9)
    • \w: Matches any word character (a-z, A-Z, 0-9, _)
    • \s: Matches any whitespace character
  • Quantifiers:
    • *: Matches 0 or more times
    • +: Matches 1 or more times
    • ?: Matches 0 or 1 time
    • {n}: Matches exactly n times
    • {n,}: Matches n or more times
    • {n,m}: Matches between n and m times
  • Anchors:
    • ^: Matches the beginning of the string
    • $: Matches the end of the string
  • Groups and Ranges:
    • (abc): Matches the exact sequence “abc”
    • [a-z]: Matches any lowercase letter
    • [A-Z]: Matches any uppercase letter
    • [0-9]: Matches any digit
  • Escaping Special Characters:
    • \.: Matches a literal dot
    • \\: Matches a literal backslash
const regex = /\d{3}-\d{2}-\d{4}/;
const ssn = '123-45-6789';
console.log(regex.test(ssn)); // Output: true

Arrays

  • Definition: An array is a data structure that can hold multiple values at once. These values can be of any type, including numbers, strings, objects, and even other arrays. Arrays are zero-indexed, meaning the first element is at index 0.

    const numbers = [1, 2, 3, 4, 5];
    
    ```javascript
      const numbers = [1, 2, 3, 4, 5];
    • Common array methods: push, pop, shift, unshift, map, filter, reduce, etc.

      // Adding elements
      numbers.push(6); // [1, 2, 3, 4, 5, 6]
      
      // Removing elements
      numbers.pop(); // [1, 2, 3, 4, 5]
      
      // Adding elements to the beginning
      numbers.unshift(0); // [0, 1, 2, 3, 4, 5]
      
      // Removing elements from the beginning
      numbers.shift(); // [1, 2, 3, 4, 5]

Array Functional Programming

  • Mapping Elements: Creates a new array populated with the results of calling a provided function on every element in the calling array.

    const numbers = [1, 2, 3, 4, 5];
    const doubled = numbers.map(num => num * 2); // [2, 4, 6, 8, 10]
    console.log(doubled); // Output: [2, 4, 6, 8, 10]
  • Filtering Elements: Creates a new array with all elements that pass the test implemented by the provided function.

    const even = numbers.filter(num => num % 2 === 0); // [2, 4]
    console.log(even); // Output: [2, 4]
  • Chaining Methods: Combining multiple array methods to perform complex operations.

    const result = numbers
      .filter(num => num % 2 === 0) // Filter even numbers
      .map(num => num * 2) // Double the filtered numbers
      .reduce((acc, num) => acc + num, 0); // Sum the doubled numbers
    console.log(result); // Output: 12 (2*2 + 4*2)

Objects

  • Definition of an Object:
    • An object in JavaScript is a collection of key-value pairs where each key is a string (also called a property name) and each value can be any data type, including other objects. Objects are used to store and manipulate data in a structured way.
  • Object Creation and Manipulation Techniques:
    • Creating objects using object literals.

    • Adding, updating, and deleting properties.

      const person = {
        name: 'Alice',
        age: 25
      };
      // Adding a property
      person.job = 'Developer';
      // Updating a property
      person.age = 26;
      // Deleting a property
      delete person.job;
      console.log(person); // Output: { name: 'Alice', age: 26 }

Accessing Properties

  • Using dot notation and bracket notation.

    // Dot notation
    console.log(person.name); // Output: Alice
    // Bracket notation
    console.log(person['age']); // Output: 26

Nested Objects

  • Creating and accessing nested objects.

    const company = {
      name: 'Tech Corp',
      address: {
        street: '123 Main St',
        city: 'Techville'
      }
    };
    console.log(company.address.city); // Output: Techville

Object Methods

  • Adding methods to objects.

    const car = {
      brand: 'Toyota',
      model: 'Corolla',
      start: function() {
        console.log('Car started');
      }
    };
    car.start(); // Output: Car started

Iterating Over Object Properties

  • Using for...in loop to iterate over object properties.

    for (let key in person) {
      console.log(`${key}: ${person[key]}`);
    }
    // Output:
    // name: Alice
    // age: 26

Destructuring Assignment

  • Using Destructuring for Objects and Arrays
    • Extracting values from objects and arrays.

      // Object destructuring
      const person = { name: 'Alice', age: 25 };
      const { name, age } = person;
      console.log(name, age); // Output: Alice 25
      
      // Array destructuring
      const numbers = [1, 2, 3];
      const [first, second, third] = numbers;
      console.log(first, second, third); // Output: 1 2 3

Spread and Rest Operators

  • Using Spread and Rest Operators for Objects and Arrays
    • Spread operator: Expanding elements of an array or object.

    • Rest operator: Collecting all remaining elements into an array.

      // Spread operator with arrays
      const arr1 = [1, 2, 3];
      const arr2 = [...arr1, 4, 5];
      console.log(arr2); // Output: [1, 2, 3, 4, 5]
      
      // Spread operator with objects
      const obj1 = { name: 'Alice', age: 25 };
      const obj2 = { ...obj1, job: 'Developer' };
      console.log(obj2); // Output: { name: 'Alice', age: 25, job: 'Developer' }
      
      // Rest operator
      function sum(...numbers) {
        return numbers.reduce((acc, num) => acc + num, 0);
      }
      console.log(sum(1, 2, 3, 4)); // Output: 10

Introduction to the DOM

  • The Document Object Model (DOM) is a programming interface for HTML and XML documents.
  • It represents the page’s structure as a tree of nodes.
  • Each node represents a different part of the document, such as an element, attribute, or text.

Tree Structure of the DOM

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sample Document</title>
</head>
<body>
    <h1>Welcome to the DOM</h1>
    <p>This is a simple HTML document.</p>
    <div id="container">
        <p class="text">First paragraph</p>
        <p class="text">Second paragraph</p>
    </div>
</body>
</html>

graph TD
    A[Document]
    A --> B[html]
    B --> C[head]
    C --> D[meta]
    D --> D1{{charset=UTF-8}}
    C --> E[meta]
    E --> E1{{name=viewport}}
    E --> E2{{content=width=device-width, initial-scale=1.0}}
    C --> F[title]
    F --> F1("'Sample Document'")
    B --> G[body]
    G --> H[h1]
    H --> H1("'Welcome to the DOM'")
    G --> I[p]
    I --> I1("'This is a simple HTML document.'")
    G --> J[div]
    J --> J1{{id=container}}
    J --> K[p]
    K --> K1{{class=text}}
    K --> K2("'First paragraph'")
    J --> L[p]
    L --> L1{{class=text}}
    L --> L2("'Second paragraph'")

Accessing the DOM

  • The document object represents the entire HTML document and provides methods and properties for working with the DOM.
  • The DOM can be accessed and manipulated using JavaScript to create dynamic and interactive web applications.
  • Common tasks include selecting elements, modifying content, handling events, and creating new elements.
  • The main methods for selecting elements are getElementById, getElementsByTagName, getElementsByClassName, querySelector, and querySelectorAll.

Selecting Elements (document Object)

// Select the entire document
const udocumentElement = document;

// Select the HTML element
const htmlElement = document.documentElement;

// Select the body element
const bodyElement = document.body;

Selecting Elements by ID, Tag Name, and Class Name

  • getElementById: Selects an element by its ID.
  • getElementsByTagName: Selects elements by their tag name.
  • getElementsByClassName: Selects elements by their class name.
const elementById = document.getElementById('myId');
const elementsByTagName = document.getElementsByTagName('p');
const elementsByClassName = document.getElementsByClassName('myClass');

Selecting Elements by CSS Selector

  • querySelector: Selects the first element matching a CSS selector.
  • querySelectorAll: Selects all elements matching a CSS selector.
// Select the first element matching the selector
const firstElement = document.querySelector('.myClass');

// Select all elements matching the selector
const allElements = document.querySelectorAll('p');

Selecting Elements in JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Selection Example</title>
</head>
<body>
    <h1 id="header">Welcome to JavaScript</h1>
    <p class="myClass">This is a paragraph.</p>
    <p class="myClass">This is another paragraph.</p>

    <script>
        // Select the entire document
        const documentElement = document;

        // Select the HTML element
        const htmlElement = document.documentElement;

        // Select the body element
        const bodyElement = document.body;

        // Select an element by ID
        const elementById = document.getElementById('header');
        console.log(elementById.textContent); // Output: Welcome to JavaScript

        // Select elements by tag name
        const elementsByTagName = document.getElementsByTagName('p');
        console.log(elementsByTagName.length); // Output: 2

        // Select elements by class name
        const elementsByClassName = document.getElementsByClassName('myClass');
        console.log(elementsByClassName.length); // Output: 2

        // Select the first element matching the selector
        const firstElement = document.querySelector('.myClass');
        console.log(firstElement.textContent); // Output: This is a paragraph.

        // Select all elements matching the selector
        const allElements = document.querySelectorAll('p');
        console.log(allElements.length); // Output: 2
    </script>
</body>
</html>

Modifying the DOM

  • The Document Object Model (DOM) can be modified using JavaScript to update the content, structure, and style of web pages.
  • The main methods for modifying elements are textContent, innerHTML, setAttribute, getAttribute, removeAttribute, createElement, appendChild, insertBefore, and removeChild.

Modifying Element Content:

// Modify text content
element.textContent = 'New text';

// Modify inner HTML
element.innerHTML = '<strong>Bold text</strong>';

Modifying Element Attributes:

// Set an attribute
element.setAttribute('href', 'https://example.com');

// Get an attribute value
const hrefValue = element.getAttribute('href');

// Remove an attribute
element.removeAttribute('disabled');

Creating New Elements:

const newElement = document.createElement('p');
newElement.textContent = 'This is a new paragraph.';

Adding and Removing Elements:

// Append a child element
parent.appendChild(child);

// Insert a child element before another
parent.insertBefore(newChild, existingChild);

// Remove a child element
parent.removeChild(child);

Modifying Element Styles:

// Set a style property
element.style.color = 'red';
element.style.fontSize = '20px';

// Add or remove a class
element.classList.add('myClass');
element.classList.remove('myClass');

Understanding Events in JavaScript

  • Events are actions or occurrences that happen in the browser, such as clicks, key presses, or page loads.
  • JavaScript can listen for these events and execute code in response.
  • Event handling involves attaching event listeners to elements to respond to user interactions.
  • Common events include click, mouseover, keydown, submit, and load.

Event Listeners

  • Using addEventListener to Handle Events:
    • The addEventListener method attaches an event handler to an element.
    • Syntax: element.addEventListener(event, function, useCapture)
    ```javascript const button = document.querySelector(‘button’); button.addEventListener(‘click’, () => { alert(‘Button clicked!’); });

Event Listener Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Listener Example</title>
</head>
<body>
    <!-- A button element that the user can click -->
    <button>Click Me!</button>

    <script>
        // Select the button element
        const button = document.querySelector('button');

        // Attach an event listener to the button
        button.addEventListener('click', () => {
            // This function will run when the button is clicked
            alert('Button clicked!');
        });
    </script>
</body>
</html>

Default Behavior

  • Preventing Default Behavior with preventDefault:
    • Some events have default behaviors (e.g., form submission, link navigation).

    • The preventDefault method prevents the default action of the event.

      const link = document.querySelector('a');
      link.addEventListener('click', (event) => {
          event.preventDefault();
          alert('Link click prevented!');
      });

Event Propagation

  • Understanding Event Propagation and Using stopPropagation:
    • Event propagation determines the order in which event handlers are executed.

    • Three phases: capturing, target, and bubbling.

    • The stopPropagation method stops the event from propagating further.

      const parent = document.querySelector('.parent');
      const child = document.querySelector('.child');
      
      parent.addEventListener('click', () => {
          alert('Parent clicked!');
      });
      
      child.addEventListener('click', (event) => {
          event.stopPropagation();
          alert('Child clicked!');
      });

Event Delegation

  • Using Event Delegation for Efficient Event Handling:
    • Event delegation involves attaching a single event listener to a parent element to manage events for multiple child elements.

    • This approach is efficient for handling events on dynamically added elements.

      const list = document.querySelector('ul');
      list.addEventListener('click', (event) => {
          if (event.target.tagName === 'LI') {
              alert(`Item ${event.target.textContent} clicked!`);
          }
      });

Mouse Events

  • Handling Mouse Events:
    • Common mouse events: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove.

      const box = document.querySelector('.box');
      box.addEventListener('mouseover', () => {
          box.style.backgroundColor = 'blue';
      });
      box.addEventListener('mouseout', () => {
          box.style.backgroundColor = 'red';
      });

Class Toggle

  • Toggling Classes on Elements:
    • The classList property provides methods to add, remove, and toggle classes.

      const button = document.querySelector('button');
      button.addEventListener('click', () => {
          button.classList.toggle('active');
      });

Scroll & Resize Events

  • Handling Scroll and Resize Events:
    • The scroll event is fired when the document view or an element is scrolled.

    • The resize event is fired when the document view is resized.

      window.addEventListener('scroll', () => {
          console.log('Page scrolled!');
      });
      
      window.addEventListener('resize', () => {
          console.log('Window resized!');
      });

Keyboard Events

  • Handling Keyboard Events:
    • Common keyboard events: keydown, keyup, keypress.

      document.addEventListener('keydown', (event) => {
          console.log(`Key pressed: ${event.key}`);
      });

Form Events

  • Handling Form Events:
    • Common form events: submit, change, input, focus, blur.

      const form = document.querySelector('form');
      form.addEventListener('submit', (event) => {
          event.preventDefault();
          alert('Form submitted!');
      });

Working with Dates in JavaScript

  • JavaScript provides the Date object to work with dates and times. The Date object offers various methods to create, manipulate, and format dates.
  • Common tasks include creating dates, getting date components, setting date components, formatting dates, and performing date calculations.

Creating Dates

  • Current Date and Time: javascript const now = new Date(); console.log(now); // Output: current date and time

  • Specific Date and Time: javascript const specificDate = new Date('2023-10-01T10:00:00'); console.log(specificDate); // Output: Sun Oct 01 2023 10:00:00 GMT+0000 (UTC)

  • Using Date Components: javascript const dateFromComponents = new Date(2023, 9, 1, 10, 0, 0); // Note: Month is 0-indexed console.log(dateFromComponents); // Output: Sun Oct 01 2023 10:00:00 GMT+0000 (UTC)

Date Methods

  • Getting Date Components: javascript const date = new Date(); console.log(date.getFullYear()); // Output: 2023 console.log(date.getMonth()); // Output: 9 (October, 0-indexed) console.log(date.getDate()); // Output: 1 console.log(date.getHours()); // Output: current hour console.log(date.getMinutes()); // Output: current minute console.log(date.getSeconds()); // Output: current second

  • Setting Date Components: javascript const date = new Date(); date.setFullYear(2024); date.setMonth(11); // December date.setDate(25); console.log(date); // Output: Wed Dec 25 2024

  • Formatting Dates: javascript const date = new Date(); const formattedDate = date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }); console.log(formattedDate); // Output: October 1, 2023

Date Calculations

  • Adding/Subtracting Time: javascript const date = new Date(); date.setDate(date.getDate() + 7); // Add 7 days console.log(date); // Output: Date 7 days from now

  • Difference Between Dates: javascript const startDate = new Date('2023-10-01'); const endDate = new Date('2023-10-10'); const differenceInTime = endDate - startDate; const differenceInDays = differenceInTime / (1000 * 3600 * 24); console.log(differenceInDays); // Output: 9

Conditional Statements

  • Control structures are used to control the flow of a program based on specified conditions.
  • Common control structures in JavaScript include if statements, else statements, else if statements, switch statements, and loops.
  • These structures allow you to make decisions, repeat code, and handle different scenarios in your programs.
  • Conditional statements are used to perform different actions based on different conditions.
    • if statement: Executes a block of code if a specified condition is true.
    • else statement: Executes a block of code if the same condition is false.
    • switch statement: Evaluates an expression and executes code based on matching case labels.

Conditions in JavaScript

  • Basic if Statements:
    • The if statement executes a block of code if a specified condition is true.

    • Syntax: javascript if (condition) { // code to be executed if condition is true }

      let age = 18;
      if (age >= 18) {
          console.log("You are an adult.");
      }

if…else and else if Conditions

  • Using if…else Statements:
    • The if...else statement executes one block of code if a condition is true, and another block if it is false.

    • Syntax: javascript if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }

      let age = 16;
      if (age >= 18) {
          console.log("You are an adult.");
      } else {
          console.log("You are a minor.");
      }
  • Using else if Statements:
    • The else if statement specifies a new condition to test if the first condition is false.

    • Syntax: javascript if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if both conditions are false }

      let score = 85;
      if (score >= 90) {
          console.log("Grade: A");
      } else if (score >= 80) {
          console.log("Grade: B");
      } else {
          console.log("Grade: C");
      }

Complex Conditions

  • Combining Conditions with Logical Operators:
    • Logical operators (&&, ||, !) are used to combine multiple conditions.

      let age = 20;
      let hasID = true;
      if (age >= 18 && hasID) {
          console.log("You can enter.");
      } else {
          console.log("You cannot enter.");
      }

Type Coercion

  • Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). This can happen in various operations, including comparisons and arithmetic operations.

  • String to Number: javascript let str = "123"; let num = str - 0; // Implicit conversion to number console.log(num); // Output: 123

  • Number to String: javascript let num = 123; let str = num + ""; // Implicit conversion to string console.log(str); // Output: "123"

  • Boolean Coercion: javascript console.log(Boolean(0)); // Output: false console.log(Boolean(1)); // Output: true console.log(Boolean("")); // Output: false console.log(Boolean("hello")); // Output: true

Type Coercion in Conditions

  • JavaScript automatically converts data types when evaluating conditions. This can lead to unexpected results if not properly understood.

    let value = "0";
    if (value) {
        console.log("This is true.");
    } else {
        console.log("This is false.");
    }
    // Output: This is true.

Avoiding Unintended Type Coercion

  • Use strict equality (===) and inequality (!==) operators to avoid type coercion in comparisons.

    let value = "0";
    if (value === 0) {
        console.log("This is true.");
    } else {
        console.log("This is false.");
    }
    // Output: This is false.

Explicit Type Conversion

  • Convert types explicitly to avoid confusion and ensure the correct type is used.

    let str = "123";
    let num = Number(str); // Explicit conversion to number
    console.log(num); // Output: 123
    
    let num2 = 123;
    let str2 = String(num2); // Explicit conversion to string
    console.log(str2); // Output: "123"

The switch Statement

  • Using switch Statements for Multiple Conditions:
    • The switch statement evaluates an expression and executes code based on matching case labels.

    • Syntax: javascript switch (expression) { case value1: // code to be executed if expression === value1 break; case value2: // code to be executed if expression === value2 break; default: // code to be executed if no case matches }

      let day = 3;
      switch (day) {
          case 1:
              console.log("Monday");
              break;
          case 2:
              console.log("Tuesday");
              break;
          case 3:
              console.log("Wednesday");
              break;
          default:
              console.log("Another day");
      }

Ternary Operation

  • Using the Ternary Operator for Concise Conditions:
    • The ternary operator (? :) is a shorthand for if...else statements.

    • Syntax: javascript condition ? expressionIfTrue : expressionIfFalse

      let age = 18;
      let message = age >= 18 ? "You are an adult." : "You are a minor.";
      console.log(message); // Output: You are an adult.

Short-Circuit Operation

  • Using Short-Circuit Evaluation in Conditions:
    • Short-circuit evaluation allows expressions to be evaluated only as necessary.

      let isLoggedIn = true;
      let user = isLoggedIn && "John Doe";
      console.log(user); // Output: John Doe
      
      let isAdmin = false;
      let access = isAdmin || "Access Denied";
      console.log(access); // Output: Access Denied

Loops

  • Loops are used to execute a block of code multiple times.
    • for loop: Executes a block of code a specific number of times.
    • while loop: Executes a block of code while a specified condition is true.
    • do...while loop: Executes a block of code at least once and then repeats it while a specified condition is true.
    • for...of loop: Iterates over the values of an iterable object.
    • for...in loop: Iterates over the properties of an object.

The for Loop and break/continue Statements

- The `for` loop is used to execute a block of code a specific number of times.
- Syntax:
    ```javascript
    for (initialization; condition; increment) {
            // code to be executed
    }
    ```

    ```javascript
    for (let i = 0; i < 5; i++) {
            console.log(i); // Output: 0, 1, 2, 3, 4
    }
    ```

Using break and continue Statements

- The `break` statement exits the loop immediately.
- The `continue` statement skips the current iteration and moves to the next one.

    ```javascript
    for (let i = 0; i < 5; i++) {
            if (i === 3) {
                    break; // Exit the loop when i is 3
            }
            console.log(i); // Output: 0, 1, 2
    }

    for (let i = 0; i < 5; i++) {
            if (i === 3) {
                    continue; // Skip the iteration when i is 3
            }
            console.log(i); // Output: 0, 1, 2, 4
    }
    ```

while and do…while Loops

  • Using while Loops:
    • The while loop executes a block of code as long as the specified condition is true.

    • Syntax: javascript while (condition) { // code to be executed }

      let i = 0;
      while (i < 5) {
              console.log(i); // Output: 0, 1, 2, 3, 4
              i++;
      }
  • Using do…while Loops:
    • The do...while loop executes a block of code once before checking the condition, and then repeats the loop as long as the condition is true.

    • Syntax: javascript do { // code to be executed } while (condition);

      let i = 0;
      do {
              console.log(i); // Output: 0, 1, 2, 3, 4
              i++;
      } while (i < 5);

for…in and for…of Loops

  • Using for…in Loops:
    • The for...in loop iterates over the enumerable properties of an object.

    • Syntax: javascript for (key in object) { // code to be executed }

      const person = { name: "Alice", age: 30, city: "New York" };
      for (let key in person) {
              console.log(key + ": " + person[key]); // Output: name: Alice, age: 30, city: New York
      }
  • Using for…of Loops:
    • The for...of loop iterates over the values of an iterable object (like an array or a string).

    • Syntax: javascript for (value of iterable) { // code to be executed }

      const numbers = [1, 2, 3, 4, 5];
      for (let number of numbers) {
              console.log(number); // Output: 1, 2, 3, 4, 5
      }

Functions in JavaScript

Functions are one of the fundamental building blocks in JavaScript. A function is a reusable block of code designed to perform a particular task.

Defining Functions

  • Function Declaration: javascript function greet(name) { return `Hello, ${name}!`; } console.log(greet('Alice')); // Output: Hello, Alice!

  • Function Expression: javascript const greet = function(name) { return `Hello, ${name}!`; }; console.log(greet('Bob')); // Output: Hello, Bob!

Parameters and Arguments

  • Parameters: Variables listed as a part of the function definition.

  • Arguments: Values passed to the function when it is invoked.

    function add(a, b) {
        return a + b;
    }
    console.log(add(2, 3)); // Output: 5

Default Parameters

  • Setting Default Values for Parameters: javascript function greet(name = 'Guest') { return `Hello, ${name}!`; } console.log(greet()); // Output: Hello, Guest!

Returning Values

  • Using the return Statement to Return Values from Functions: javascript function multiply(a, b) { return a * b; } console.log(multiply(4, 5)); // Output: 20

Function Scope

  • Understanding Local and Global Scope: ```javascript let globalVar = ‘I am global’;

    function checkScope() { let localVar = ‘I am local’; console.log(globalVar); // Output: I am global console.log(localVar); // Output: I am local }

    checkScope(); console.log(localVar); // Error: localVar is not defined ```

Anonymous Functions

  • Functions Without a Name: javascript setTimeout(function() { console.log('This is an anonymous function'); }, 1000);

Function Hoisting

  • Understanding Function Hoisting: ```javascript console.log(hoistedFunction()); // Output: This function is hoisted

    function hoistedFunction() { return ‘This function is hoisted’; } ```

Arrow Functions

  • Using Arrow Functions for Concise Syntax:
    • Arrow functions provide a shorter syntax for writing function expressions.

    • Syntax: javascript const functionName = (parameters) => { // code to be executed };

      const add = (a, b) => a + b;
      console.log(add(2, 3)); // Output: 5

Callback Functions

  • Functions Passed as Arguments to be Executed Later:
    • A callback function is a function passed into another function as an argument, which is then invoked inside the outer function.

      function greet(name, callback) {
              console.log("Hello, " + name);
              callback();
      }
      
      function sayGoodbye() {
              console.log("Goodbye!");
      }
      
      greet("Alice", sayGoodbye); // Output: Hello, Alice \n Goodbye!

Methods

  • Functions Defined Inside Objects:
    • Methods are functions that are properties of an object.

      const person = {
              name: "Alice",
              greet: function() {
                      console.log("Hello, " + this.name);
              }
      };
      
      person.greet(); // Output: Hello, Alice

Pure Functions

  • Functions that Always Return the Same Result for the Same Arguments:
    • Pure functions do not have side effects and always produce the same output for the same input.

      function add(a, b) {
              return a + b;
      }
      
      console.log(add(2, 3)); // Output: 5

Higher-Order Functions

  • Functions that Take Other Functions as Arguments or Return Functions:
    • Higher-order functions can accept functions as arguments and/or return functions.

      function higherOrderFunction(callback) {
              callback();
      }
      
      function sayHello() {
              console.log("Hello!");
      }
      
      higherOrderFunction(sayHello); // Output: Hello!

Immediately Invoked Function Expressions (IIFE)

  • Functions that Execute Immediately After Their Definition:
    • An IIFE is a function that runs as soon as it is defined.

    • Syntax: javascript (function() { // code to be executed })();

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

Recursion

  • Functions that Call Themselves:
    • Recursion is a technique where a function calls itself.

      function factorial(n) {
              if (n === 0) {
                      return 1;
              }
              return n * factorial(n - 1);
      }
      
      console.log(factorial(5)); // Output: 120

Modern JavaScript (ES6/7/8+)

New Syntax and Features

  • let/const, Arrow Functions, Template Literals, etc.:
    • let and const for block-scoped variables.

    • Arrow functions for concise function syntax.

    • Template literals for string interpolation.

      let name = "Alice";
      const age = 30;
      const greet = () => `Hello, ${name}. You are ${age} years old.`;
      console.log(greet()); // Output: Hello, Alice. You are 30 years old.

Promises and Async/Await

  • Handling Asynchronous Operations:
    • Promises represent the eventual completion (or failure) of an asynchronous operation.

    • async and await provide a way to write asynchronous code that looks synchronous.

      const fetchData = () => {
              return new Promise((resolve, reject) => {
                      setTimeout(() => {
                              resolve("Data fetched");
                      }, 2000);
              });
      };
      
      async function getData() {
              const data = await fetchData();
              console.log(data); // Output: Data fetched
      }
      
      getData();

Modules

  • Using Modules in JavaScript:
    • Modules allow you to break your code into separate files and import/export functionality.

      // module.js
      export const greet = (name) => `Hello, ${name}`;
      
      // main.js
      import { greet } from './module.js';
      console.log(greet("Alice")); // Output: Hello, Alice

Object-Oriented JavaScript

Introduction to Objects

  • Creating and Using Objects:
    • Objects are collections of key-value pairs.

      const person = {
              name: "Alice",
              age: 30,
              greet: function() {
                      console.log("Hello, " + this.name);
              }
      };
      
      person.greet(); // Output: Hello, Alice

Prototypes and Inheritance

  • Understanding Prototypes and Inheritance:
    • JavaScript uses prototypes for inheritance.

      function Person(name, age) {
              this.name = name;
              this.age = age;
      }
      
      Person.prototype.greet = function() {
              console.log("Hello, " + this.name);
      };
      
      const alice = new Person("Alice", 30);
      alice.greet(); // Output: Hello, Alice

Classes and Constructors

  • Using Classes and Constructors for Object-Oriented Programming:
    • ES6 introduced classes as a syntactical sugar over prototype-based inheritance.

      class Person {
              constructor(name, age) {
                      this.name = name;
                      this.age = age;
              }
      
              greet() {
                      console.log("Hello, " + this.name);
              }
      }
      
      const alice = new Person("Alice", 30);
      alice.greet(); // Output: Hello, Alice

Asynchronous JavaScript

Callbacks

  • Using Callbacks for Asynchronous Operations:
    • Callbacks are functions passed as arguments to be executed later.

      function fetchData(callback) {
              setTimeout(() => {
                      callback("Data fetched");
              }, 2000);
      }
      
      fetchData((data) => {
              console.log(data); // Output: Data fetched
      });

Promises

  • Using Promises to Handle Asynchronous Operations:
    • Promises represent the eventual completion (or failure) of an asynchronous operation.

      const fetchData = () => {
              return new Promise((resolve, reject) => {
                      setTimeout(() => {
                              resolve("Data fetched");
                      }, 2000);
              });
      };
      
      fetchData().then((data) => {
              console.log(data); // Output: Data fetched
      });

Async/Await

  • Using Async/Await for Cleaner Asynchronous Code:
    • async and await provide a way to write asynchronous code that looks synchronous.

      const fetchData = () => {
              return new Promise((resolve, reject) => {
                      setTimeout(() => {
                              resolve("Data fetched");
                      }, 2000);
              });
      };
      
      async function getData() {
              const data = await fetchData();
              console.log(data); // Output: Data fetched
      }
      
      getData();

Fetch API

  • Making Network Requests with the Fetch API:
    • The Fetch API provides a modern way to make network requests.

      async function fetchData() {
              const response = await fetch('https://api.example.com/data');
              const data = await response.json();
              console.log(data);
      }
      
      fetchData();

Objects and Arrays

Creating and Manipulating Objects

  • Object Creation and Manipulation Techniques:

      ```javascript
      const person = {
              name: "Alice",
              age: 30
      };
    
      person.city = "New York"; // Add property
      delete person.age; // Delete property
      console.log(person); // Output: { name: "Alice", city: "New York" }
      ```

Arrays and Array Methods

  • Working with Arrays and Common Array Methods:

      ```javascript
      const numbers = [1, 2, 3, 4, 5];
    
      numbers.push(6); // Add element
      numbers.pop(); // Remove last element
      numbers.shift(); // Remove first element
      numbers.unshift(0); // Add element at the beginning
      console.log(numbers); // Output: [0, 2, 3, 4, 5]
      ```

Destructuring Assignment

  • Using Destructuring for Objects and Arrays:

      ```javascript
      const person = { name: "Alice", age: 30 };
      const { name, age } = person;
      console.log(name, age); // Output: Alice 30
    
      const numbers = [1, 2, 3];
      const [first, second, third] = numbers;
      console.log(first, second, third); // Output: 1 2 3
      ```

Spread and Rest Operators

  • Using Spread and Rest Operators for Objects and Arrays:

      ```javascript
      const person = { name: "Alice", age: 30 };
      const updatedPerson = { ...person, city: "New York" };
      console.log(updatedPerson); // Output: { name: "Alice", age: 30, city: "New York" }
    
      const numbers = [1, 2, 3];
      const moreNumbers = [...numbers, 4, 5];
      console.log(moreNumbers); // Output: [1, 2, 3, 4, 5]
    
      function sum(...args) {
              return args.reduce((acc, curr) => acc + curr, 0);
      }
    
      console.log(sum(1, 2, 3)); // Output: 6
      ```

Modern JavaScript (ES6/7/8+)

  • New Syntax and Features

  • let/const

    • let: Block-scoped variable declaration.

    • const: Block-scoped constant declaration.

      let x = 10;
      const y = 20;
  • Arrow Functions

    • Concise syntax for writing functions.

    • Lexical this binding.

      const add = (a, b) => a + b;
  • Template Literals

    • Multi-line strings and string interpolation.

      const name = 'John';
      const greeting = `Hello, ${name}!`;
  • Destructuring Assignment

    • Extract values from arrays or properties from objects.

      const [a, b] = [1, 2];
      const {name, age} = {name: 'John', age: 30};
  • Default Parameters

    • Set default values for function parameters.

      function greet(name = 'Guest') {
        return `Hello, ${name}!`;
      }
  • Rest and Spread Operators

    • Rest: Collects all remaining elements into an array.

    • Spread: Expands an array into individual elements.

      function sum(...numbers) {
        return numbers.reduce((acc, num) => acc + num, 0);
      }
      const arr = [1, 2, 3];
      const newArr = [...arr, 4, 5];

Promises and Async/Await

  • Promises
    • Represent the eventual completion (or failure) of an asynchronous operation.

      const promise = new Promise((resolve, reject) => {
        setTimeout(() => resolve('Success!'), 1000);
      });
      promise.then(result => console.log(result));
  • Async/Await
    • Syntactic sugar for working with promises.

    • Makes asynchronous code look synchronous.

      async function fetchData() {
        try {
          const response = await fetch('https://api.example.com/data');
          const data = await response.json();
          console.log(data);
        } catch (error) {
          console.error('Error:', error);
        }
      }
      fetchData();

Modules

  • Using Modules in JavaScript
    • Import and export functionalities between files.

      // module.js
      export const add = (a, b) => a + b;
      
      // main.js
      import { add } from './module.js';
      console.log(add(2, 3));

Sure! Here’s a detailed outline for your JavaScript lecture slides on Object-Oriented JavaScript:

Object-Oriented JavaScript

Summary

  • Introduction to Objects: Creating and using objects.
  • Prototypes and Inheritance: Understanding prototypes and inheritance.
  • Classes and Constructors: Using classes and constructors for object-oriented programming.

Introduction to Objects

  • Creating and Using Objects
    • Objects are collections of key-value pairs.

      const person = {
        name: 'Alice',
        age: 25,
        greet: function() {
          console.log(`Hello, my name is ${this.name}`);
        }
      };
      person.greet(); // Output: Hello, my name is Alice

Prototypes and Inheritance

  • Understanding Prototypes
    • Every JavaScript object has a prototype.

    • Prototypes are used to share properties and methods between objects.

      function Person(name, age) {
        this.name = name;
        this.age = age;
      }
      Person.prototype.greet = function() {
        console.log(`Hello, my name is ${this.name}`);
      };
      const alice = new Person('Alice', 25);
      alice.greet(); // Output: Hello, my name is Alice
  • Inheritance
    • Objects can inherit properties and methods from other objects.

      function Employee(name, age, jobTitle) {
        Person.call(this, name, age);
        this.jobTitle = jobTitle;
      }
      Employee.prototype = Object.create(Person.prototype);
      Employee.prototype.constructor = Employee;
      Employee.prototype.work = function() {
        console.log(`${this.name} is working as a ${this.jobTitle}`);
      };
      const bob = new Employee('Bob', 30, 'Developer');
      bob.greet(); // Output: Hello, my name is Bob
      bob.work(); // Output: Bob is working as a Developer

Classes and Constructors

  • Using Classes and Constructors
    • ES6 introduced classes as a syntactical sugar over JavaScript’s existing prototype-based inheritance.

      class Person {
        constructor(name, age) {
          this.name = name;
          this.age = age;
        }
        greet() {
          console.log(`Hello, my name is ${this.name}`);
        }
      }
      class Employee extends Person {
        constructor(name, age, jobTitle) {
          super(name, age);
          this.jobTitle = jobTitle;
        }
        work() {
          console.log(`${this.name} is working as a ${this.jobTitle}`);
        }
      }
      const charlie = new Employee('Charlie', 35, 'Manager');
      charlie.greet(); // Output: Hello, my name is Charlie
      charlie.work(); // Output: Charlie is working as a Manager

Sure! Here’s a detailed outline for your JavaScript lecture slides on Asynchronous JavaScript:

Asynchronous JavaScript

Callbacks

  • Using Callbacks for Asynchronous Operations
    • A callback is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

      function fetchData(callback) {
        setTimeout(() => {
          const data = { name: 'John', age: 30 };
          callback(data);
        }, 1000);
      }
      function displayData(data) {
        console.log(`Name: ${data.name}, Age: ${data.age}`);
      }
      fetchData(displayData); // Output after 1 second: Name: John, Age: 30

Promises

  • Using Promises to Handle Asynchronous Operations
    • A promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

      const fetchData = new Promise((resolve, reject) => {
        setTimeout(() => {
          const data = { name: 'John', age: 30 };
          resolve(data);
        }, 1000);
      });
      fetchData
        .then(data => {
          console.log(`Name: ${data.name}, Age: ${data.age}`);
        })
        .catch(error => {
          console.error('Error:', error);
        });

Async/Await

  • Using Async/Await for Cleaner Asynchronous Code
    • async and await provide a way to work with promises that is more readable and easier to understand.

      async function fetchData() {
        try {
          const response = await new Promise((resolve, reject) => {
            setTimeout(() => {
              const data = { name: 'John', age: 30 };
              resolve(data);
            }, 1000);
          });
          console.log(`Name: ${response.name}, Age: ${response.age}`);
        } catch (error) {
          console.error('Error:', error);
        }
      }
      fetchData(); // Output after 1 second: Name: John, Age: 30

Fetch API

  • Making Network Requests with the Fetch API
    • The Fetch API provides a modern, promise-based way to make network requests.

      async function fetchUserData() {
        try {
          const response = await fetch('https://api.example.com/user');
          if (!response.ok) {
            throw new Error('Network response was not ok');
          }
          const data = await response.json();
          console.log(`Name: ${data.name}, Age: ${data.age}`);
        } catch (error) {
          console.error('Fetch error:', error);
        }
      }
      fetchUserData();