Javascript
  • intro.
  • 1 - Getting started
  • 2 - Basics
  • 3 - Functions and Scope
  • 4 - Advanced Concepts
  • 5 - JavaScript in the Browser
  • 6 - JavaScript and Browser Storage
  • 7 - Asynchronous JavaScript
  • 8 - Design Patterns
  • 9 - Frameworks Overview
  • 10 - Testing and Debugging
Powered by GitBook
On this page
  • Variables and Data Types
  • Variables in JavaScript
  • Variable Scope
  • Data Types
  • Reference Data Types
  • Type Conversion
  • Basic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Control Structures
  • Conditional Statements
  • Loops

2 - Basics

Chapter 2: JavaScript Basics

Variables and Data Types

Variables in JavaScript

  • Variables: Containers for storing data values.

  • Declaration Keywords:

    • var: Older way to declare variables (function-scoped).

    • let: Block-scoped, used in modern JavaScript.

    • const: Block-scoped, cannot be reassigned (constant value).

Declaring Variables

  • Syntax:

    let name = "John";  // Using let
    const age = 25;      // Using const
    var country = "USA"; // Using var (not recommended)
  • Examples:

    let score = 100;
    score = 150;  // Reassigning with let
    const pi = 3.14;
    // pi = 3.15;  // Error: Assignment to constant variable
  • Best Practices:

    • Use let for variables that will change.

    • Use const for variables that should not change.

    • Avoid var unless dealing with legacy code.

Variable Scope

  • Global Scope: Variables declared outside any function have global scope.

    • Example:

      let globalVar = "I am global";
      function showGlobal() {
        console.log(globalVar);  // Accessible here
      }
      showGlobal();
  • Local Scope: Variables declared inside a function.

    • Example:

      function localScope() {
        let localVar = "I am local";
        console.log(localVar);  // Accessible only inside this function
      }
      localScope();
      // console.log(localVar);  // Error: localVar is not defined
  • Block Scope: Variables declared with let or const inside {} are scoped to that block.

    • Example:

      if (true) {
        let blockScoped = "I am block scoped";
        console.log(blockScoped);  // Accessible here
      }
      // console.log(blockScoped);  // Error: blockScoped is not defined

Data Types

Primitive Data Types

  • String: Text data, wrapped in quotes.

    • Example:

      let greeting = "Hello, World!";
      console.log(typeof greeting);  // "string"
  • Number: Numeric values (integers and floats).

    • Example:

      let score = 99;
      console.log(typeof score);  // "number"
  • Boolean: Represents true or false.

    • Example:

      let isAvailable = true;
      console.log(typeof isAvailable);  // "boolean"
  • Undefined: A variable that has been declared but not assigned a value.

    • Example:

      let data;
      console.log(data);  // undefined
  • Null: Represents an intentional absence of value.

    • Example:

      let result = null;
      console.log(typeof result);  // "object" (JavaScript quirk)
  • Symbol: Unique identifier, used for more advanced operations.

    • Example:

      let sym = Symbol('unique');
      console.log(typeof sym);  // "symbol"
  • BigInt: For very large integers beyond the Number type's limit.

    • Example:

      let bigNumber = 1234567890123456789012345678901234567890n;
      console.log(typeof bigNumber);  // "bigint"

Reference Data Types

  • Object: Collection of key-value pairs.

    let person = {
        name: "Alice",
        age: 30
    };
    console.log(person.name);  // "Alice"
  • Array: List of items, can hold multiple data types.

    let colors = ["red", "green", "blue"];
    console.log(colors[0]);  // "red"
  • Function: Block of code designed to perform a task, treated as a value.

    function greet() {
        console.log("Hello!");
    }
    greet();  // Output: "Hello!"
  • Date: Represents a date and time.

    let currentDate = new Date();
    console.log(currentDate);  // Outputs current date and time

Type Conversion

  • Implicit Conversion (Type Coercion): JavaScript automatically converts types.

    • Example:

      let result = "5" + 2;  // Result: "52" (string)
      console.log(typeof result);  // "string"
  • Explicit Conversion: Manually converting types.

    let num = Number("123");  // Converts string to number
    let str = String(123);     // Converts number to string
    console.log(typeof num);   // "number"
    console.log(typeof str);   // "string"

Basic Operators

Arithmetic Operators

  • Examples:

    let sum = 10 + 5;        // Addition: 15
    let difference = 10 - 5; // Subtraction: 5
    let product = 10 * 5;    // Multiplication: 50
    let quotient = 10 / 5;   // Division: 2
    let remainder = 10 % 3;  // Modulus: 1
    let power = 2 ** 3;      // Exponentiation: 8

Assignment Operators

  • Examples:

    let x = 10;
    x += 5;  // Equivalent to x = x + 5; Result: 15
    x -= 3;  // Equivalent to x = x - 3; Result: 12
    x *= 2;  // Equivalent to x = x * 2; Result: 24
    x /= 4;  // Equivalent to x = x / 4; Result: 6

Comparison Operators

  • Examples:

    console.log(5 == "5");   // true (values are equal)
    console.log(5 === "5");  // false (different types)
    console.log(5 != "6");   // true
    console.log(5 !== "5");  // true (different types)
    console.log(10 > 5);      // true
    console.log(10 <= 5);     // false

Logical Operators

  • Examples:

    let result1 = (5 > 1) && (3 < 6);  // true
    let result2 = (5 > 10) || (3 < 6); // true
    let isFalse = !(5 > 10);           // true

Control Structures

Conditional Statements

  • If-Else Statement: To execute code based on a condition.

    let age = 18;
    if (age >= 18) {
        console.log("You are an adult.");
    } else {
        console.log("You are a minor.");
    }
  • Else If Statement: Handle multiple conditions.

    let score = 85;
    if (score > 90) {
        console.log("Grade: A");
    } else if (score > 75) {
        console.log("Grade: B");
    } else {
        console.log("Grade: C");
    }
  • Switch Statement: Useful for multiple conditions.

    let color = "red";
    switch (color) {
        case "red":
            console.log("You chose red.");
            break;
        case "blue":
            console.log("You chose blue.");
            break;
        default:
            console.log("Unknown color.");
    }

Loops

  • For Loop: Repeats code a certain number of times.

    for (let i = 0; i < 5; i++) {
        console.log("Iteration: " + i);
    }
  • For...of Loop: Iterates over iterable objects (like arrays).

    let fruits = ["apple", "banana", "cherry"];
    for (let fruit of fruits) {
        console.log(fruit);
    }
  • For...in Loop: Iterates over object properties.

    let person = {name: "John", age: 25};
    for (let key in person) {
        console.log(key + ": " + person[key]);
    }
  • While Loop: Repeats code while a condition is true.

    let count = 0;
    while (count < 5) {
        console.log("Count: " + count);
        count++;
    }
  • Do-While Loop: Executes code at least once, then repeats while the condition is true.

    let num = 0;
    do {
        console.log("Number: " + num);
        num++;
    } while (num < 5);

Summary

  • Variables: Use let and const for modern JavaScript, understand scope.

  • Data Types: Understand primitive vs. reference types, type conversion.

  • Operators: Arithmetic, assignment, comparison, and logical operators.

  • Control Structures: Use if-else, switch, and loops (for, while, do-while) for program flow.


Next Chapter: Functions and Scope

Previous1 - Getting startedNext3 - Functions and Scope

Last updated 6 months ago