HTML,CSS,JS 3 Javascript

ECMAScript

alert("HEllo")

alt text


alt text


Principles of Writing Consistent, Idiomatic JavaScript : https://github.com/rwaldron/idiomatic.js/


datatypes in java script

alt text

JavaScript has the following data types:

  1. Primitive:

    • String ("hello")
    • Number (42)
    • Boolean (true, false)
    • Null (null)
    • Undefined (undefined)
    • Symbol (Symbol("id"))
    • BigInt (123n)
  2. Non-Primitive:

    • Object ({}, arrays, functions, etc.)

Primitive vs Non Primitive

Primitive:

  • Immutable, stored by value.

  • Examples: String, Number, Boolean, Null, Undefined, Symbol, BigInt.

  • Example:

    let a = 10;
    let b = a; // Copies value
    b = 20; // Does not affect `a`
    

Non-Primitive:

  • Mutable, stored by reference.
  • Examples: Object, Array, Function.
  • Example:
    let obj1 = { name: "John" };
    let obj2 = obj1; // Shares reference
    obj2.name = "Doe"; // Changes affect `obj1`
    

Variables

prompt keyword

alt text


In JavaScript, variables are used to store data values. You can declare them using:

Always name variables by camel casing

1. var (Old way):

alt text

  • Function-scoped.

  • Can be redeclared and updated.

  • Hoisted but not block-scoped.

  • Example:

    var x = 10;
    var x = 20; // Redeclaration allowed
    

2. let (Modern way):

  • Block-scoped.

  • Can be updated but not redeclared in the same scope.

  • Example:

    let y = 10;
    y = 20; // Allowed
    let y = 30; // Error
    

3. const (For constants):

  • Block-scoped.

  • Cannot be updated or redeclared.

  • Example:

    const z = 10;
    z = 20; // Error
    

Summary:

  • Use let for variables that change.
  • Use const for fixed values.
  • Avoid var unless needed for older code.

Rules for variables

Here are the basic rules for variables in JavaScript:

  1. Variable Names:

    • Must start with a letter (a-z, A-Z), underscore (_), or dollar sign ($).
      Example: _name, $value, age.
    • Cannot start with a number.
  2. Case-Sensitive:

    • name and Name are different.
  3. No Reserved Keywords:

    • Avoid using keywords like let, const, if, etc.
      Example: let let = 5; // ❌ Error
  4. Meaningful Names:

    • Use descriptive names (e.g., userAge, not x).
  5. Avoid Special Characters:

    • No spaces or symbols except _ and $.
      Example: user-name // ❌ Invalid
  6. Declaration Before Use:

    • Always declare variables before using them.

Strings in Java

alt text

word.length

var name = "yash";
name.length;

output = 4


Exercise tweet count:

alt text

String slicing

alt text

Exericse 2 : slice the tweet

alt text

alternative

alt text

var name = "yash";
name = name.toUpperCase();
name = name.toLowerCase();

1. How to Create Strings

  • Use single quotes ('), double quotes ("), or template literals (`).

    let single = 'Hello';
    let double = "World";
    let template = `Hello, ${double}`; // Template literal
    

2. Common String Methods

  • length: Get string length.
    let str = "Hello";
    console.log(str.length); // 5
    
  • toUpperCase() / toLowerCase(): Change case.
    console.log(str.toUpperCase()); // "HELLO"
    console.log(str.toLowerCase()); // "hello"
    
  • includes(): Check if a substring exists.
    console.log(str.includes("ell")); // true
    
  • slice(start, end): Extract a substring.
    console.log(str.slice(1, 4)); // "ell"
    
  • replace(): Replace part of a string.
    console.log(str.replace("l", "z")); // "Hezlo"
    

3. Template Literals

  • Use backticks (`) to embed variables and expressions.

    let name = "John";
    console.log(`Hello, ${name}!`); // "Hello, John!"
    

4. Escape Characters

  • Use \ to escape special characters.

    let quote = 'I\'m learning JavaScript!';
    console.log(quote); // I'm learning JavaScript!
    

Arithmatic operations in js

In JavaScript, arithmetic operations are used to perform mathematical calculations. Here are the basic ones:

1. Operators

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division6 / 32
%Modulus (Remainder)5 % 21
**Exponentiation (Power)2 ** 38

2. Increment & Decrement

  • Increment (++): Increases value by 1.

    let x = 5;
    x++; // x is now 6
    
  • Decrement (--): Decreases value by 1.

    let x = 5;
    x--; // x is now 4
    

3. Shortcuts for Updating Values

  • Add and assign: x += 3 (same as x = x + 3)
  • Subtract and assign: x -= 3 (same as x = x - 3)
  • Multiply and assign: x *= 3
  • Divide and assign: x /= 3

Example:

let a = 10, b = 3;
console.log(a + b);  // 13
console.log(a - b);  // 7
console.log(a * b);  // 30
console.log(a / b);  // 3.33
console.log(a % b);  // 1

alt text


Functions in JavaScript

alt text

In JavaScript, functions are reusable blocks of code that perform a specific task. Here’s a quick overview:


1. Function Declaration

  • Syntax:

    function functionName(parameters) {
      // code to execute
      return result; // optional
    }
    
  • Example:

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

2. Function Expression

  • Assign a function to a variable.

    const multiply = function (x, y) {
      return x * y;
    };
    console.log(multiply(4, 5)); // 20
    

3. Arrow Functions (ES6)

  • A concise way to write functions.

    const subtract = (a, b) => a - b;
    console.log(subtract(10, 4)); // 6
    

4. Default Parameters

  • Set default values for function arguments.

    function greet(name = "Guest") {
      return `Hello, ${name}!`;
    }
    console.log(greet()); // Hello, Guest!
    console.log(greet("Alice")); // Hello, Alice!
    

5. Anonymous Functions

  • Functions without a name, often used in callbacks.

    setTimeout(function () {
      console.log("Hello after 2 seconds!");
    }, 2000);
    

Example:

function sayHello(name) {
  console.log(`Hello, ${name}!`);
}
sayHello("John"); // Hello, John!

alt text