Week 5: JavaScript Basics 2

INFO 153A/253A: Front-end Web Architecture

Kay Ashaolu

Text

JavaScript Chapter 4: Functions, Scope, and Execution Context

Why Functions and Scope Matter in Web Architecture

  • Modular Code: Break down complex applications into manageable pieces
  • Maintainability: Reduce bugs and improve code readability
  • Performance: Optimize application execution
  • Scalability: Support large-scale web applications

Functions: Building Blocks of Web Applications

  • Encapsulation: Isolate code functionality
  • Reusability: Use code across different parts of the application
  • Function Types:
    • Function Declarations, Function Expressions, Arrow Functions
// Function Declaration
function fetchData(url) {
  // Fetch data from API
}

// Function Expression
const fetchData = function(url) {
  // Fetch data from API
};

// Arrow Function
const fetchData = (url) => {
  // Fetch data from API
};

Scope in JavaScript

  • Global Scope: Accessible throughout the entire application
  • Function Scope: Accessible within a specific function
  • Block Scope (ES6+): Accessible within blocks (if, for, { })

Importance in Web Architecture:

  • Namespace Management: Prevent variable name conflicts
  • Memory Efficiency: Enable garbage collection of unused variables
  • Security: Protect data by limiting access

Managing Scope in Large Applications

  • Best Practices:
    • Minimize global variables
    • Use module patterns (IIFE, ES6 Modules)
    • Understand variable lifetimes and closures
// Module Pattern using IIFE
const App = (function() {
  let privateData = 'secret';

  return {
    getData: function() {
      return privateData;
    },
  };
})();

console.log(App.getData()); // Output: 'secret'

Execution Context and Call Stack

  • Execution Context: Environment where code is executed
    • Global Execution Context
    • Function Execution Context
  • Call Stack:
    • Manages function execution order
    • Last-In, First-Out (LIFO) principle

Implications:

  • Debugging stack overflow errors
  • Optimizing performance by understanding execution flow

Asynchronous JavaScript and the Event Loop

  • Single-threaded Nature: JavaScript executes one task at a time
  • Concurrency Model Components:
    • Call Stack
    • Web APIs
    • Task Queue
    • Event Loop

Relevance to Web Architecture:

  • Handle asynchronous operations (e.g., API calls)
  • Maintain a responsive user interface

Closures in Web Development

  • Definition: Functions that retain access to their lexical scope
  • Uses:
    • Data privacy and encapsulation
    • Implementing module patterns
    • Maintaining state between function calls
function createCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}

const counter = createCounter();
counter(); // Returns: 1
counter(); // Returns: 2

Modern JavaScript Practices

  • Arrow Functions:

    • Concise syntax
    • Lexical this binding
    • Widely used in modern frameworks
  • Let and Const:

    • Block scope reduces variable conflicts
    • Encourage immutability with const
  • Modules:

    • Use import and export for code organization
    • Avoid global namespace pollution

Integrating Concepts in Front-End Architecture

  • Design Patterns:

    • Module Pattern
    • Revealing Module Pattern
  • Frameworks and Libraries:

    • Utilize functions and scope for component-based architecture
    • Manage state and data flow efficiently
  • Best Practices:

    • Write pure functions when possible
    • Use closures wisely
    • Understand execution context to prevent performance issues

Summary and Next Steps

  • Key Takeaways:

    • Functions and scope are foundational in web architecture
    • Execution context affects how code runs and performs
    • Modern practices enhance code quality and maintainability
  • Further Exploration:

    • Dive deeper into asynchronous programming
    • Learn about ES6 modules and import/export
    • Study common design patterns in JavaScript

JavaScript Chapter 5: Logic and Control Flow

Introduction to Logic and Control Flow

  • Fundamental concepts in programming
  • Control the execution flow based on conditions
  • Essential for building interactive web applications
  • Allows making decisions within code

If Statements

Syntax:

if (condition) {
  // code to execute if condition is true
}

Example:

if (userIsLoggedIn) {
  displayDashboard();
}
  • Evaluates a condition and executes code if true

Else-If and Nesting

Else-If Syntax:

if (condition1) {
  // code for condition1
} else if (condition2) {
  // code for condition2
} else {
  // code if none of the above conditions are true
}

Nested If Statements:

if (outerCondition) {
  if (innerCondition) {
    // code for inner condition
  }
}
  • Allows checking multiple conditions sequentially

Switch Statements

Simplifies complex conditional logic Syntax:

switch (expression) {
  case value1:
    // code for case value1
    break;
  case value2:
    // code for case value2
    break;
  default:
    // code if no cases match
}

Example:

switch (userRole) {
  case 'admin':
    accessLevel = 'full';
    break;
  case 'editor':
    accessLevel = 'partial';
    break;
  default:
    accessLevel = 'read-only';
}

Truthy and Falsy Values

  • Falsy Values:
    • false
    • 0
    • '' (empty string)
    • null
    • undefined
    • NaN

Truthy Values

All values that are not falsy Example:

if ('') {
  // This block will not execute
}

if ('hello') {
  // This block will execute
}
  • Important for evaluating conditions that aren't strictly true or false

Logical Operators

AND (&&):

if (condition1 && condition2) {
  // code executes if both conditions are true
}

OR (||):

if (condition1 || condition2) {
  // code executes if at least one condition is true
}

NOT (!):

if (!condition) {
  // code executes if condition is false
}
  • Used to build complex logical expressions

Logical Assignment Operators

OR Assignment (||=):

x ||= y; // Equivalent to: x = x || y;

AND Assignment (&&=):

x &&= y; // Equivalent to: x = x && y;

Nullish Coalescing Assignment (??=):

x ??= y; // Equivalent to: x = x ?? y;

Useful for setting default values or conditions

Ternary Operator

Shorthand for simple if-else statements Syntax:

condition ? expressionIfTrue : expressionIfFalse;

Example:

const access = age >= 18 ? 'Granted' : 'Denied';

Nested Ternary (use with caution):

const status = score > 90 ? 'A' : score > 80 ? 'B' : 'C';

Makes code more concise but can reduce readability

Calculator Challenge Example

Function to perform basic arithmetic operations:

function calculator(num1, num2, operator) {
  switch (operator) {
    case '+':
      return num1 + num2;
    case '-':
      return num1 - num2;
    case '*':
      return num1 * num2;
    case '/':
      return num1 / num2;
    default:
      return 'Invalid operator';
  }
}

Calculator Challenge Example

Usage Examples:

calculator(5, 2, '+'); // Returns 7
calculator(5, 2, '-'); // Returns 3
calculator(5, 2, '*'); // Returns 10
calculator(5, 2, '/'); // Returns 2.5

Demonstrates practical use of switch statements and control flow

Conclusion

  • Logic and control flow are foundational in programming
  • Essential for creating dynamic and interactive web applications
  • Understanding these concepts is crucial for front-end web development
  • Forms the basis for more advanced topics in web architecture

Chapter 6: JavaScript Loops, Iteration, and High-Order Array Methods

Loops

  • Automate repetitive tasks
  • Manipulate data structures
  • Control flow in applications
  • Essential for dynamic front-end interactions

The for Loop

Standard looping structure in JavaScript Syntax:

for (initialization; condition; increment) {
  // code block to execute
}

Example:

for (let i = 0; i < 5; i++) {
  console.log(`Iteration ${i}`);
}

Loop Control Statements

break: Exit the loop immediately

for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);
}

continue: Skip the current iteration

for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue;
  console.log(i); // Logs odd numbers
}

while and do...while Loops

while loop: Executes as long as the condition is true

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

do...while loop: Executes code block at least once

let count = 0;
do {
  console.log(count);
  count++;
} while (count < 5);

High-Order Functions in JavaScript

  • Functions that take other functions as arguments or return them
  • High-order array methods simplify array manipulation
  • Improve code readability and maintainability

The forEach Method

Executes a provided function once for each array element Syntax:

array.forEach((element, index, array) => {
  // code to execute
});

Example:

const colors = ['red', 'green', 'blue'];
colors.forEach(color => {
  console.log(color);
});

The map Method

Creates a new array by applying a function to each element Syntax:

const newArray = array.map(element => {
  // return new value
});

Example:

const numbers = [1, 2, 3];
const squares = numbers.map(number => number * number);

The filter Method

Creates a new array with elements that pass a test Syntax:

const filteredArray = array.filter(element => {
  // return condition
});

Example:

const ages = [18, 21, 16, 25];
const adults = ages.filter(age => age >= 18);

The reduce Method

Reduces an array to a single value Syntax:

const result = array.reduce((accumulator, currentValue) => {
  // return updated accumulator
}, initialValue);

Example:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, number) => total + number, 0);

Applying These Concepts in Web Development

  • Manipulate DOM elements using loops and array methods
  • Handle user interactions efficiently
  • Process and display data from APIs
  • Example: Displaying a list of products fetched from a server

Questions?

Week 5 - JavaScript Basics 2

By kayashaolu

Week 5 - JavaScript Basics 2

Course Website: https://www.ischool.berkeley.edu/courses/info/253a

  • 84