JS in the Real World

JavaScript

In the Real World & Catch-up Lab

CSCI 4513

Week 5, Lecture 9

Today's Learning Objectives

Code Style Matters

Having consistent style rules makes your code more maintainable and easier to read.

Popular JavaScript Style Guides:

πŸ’‘ Key Point: None are "right" or "wrong"β€”they just promote consistency across a codebase.

What is Linting?

Linters scan your code with a set of style rules and report errors they find.

# Install as dev dependency
npm install --save-dev eslint

# Initialize configuration
npx eslint --init

eslint - The most popular JavaScript linter. Catches style errors and inconsistencies.

--init - Interactive wizard that creates a config file with your preferred rules

What it does: catches style errors, reports inconsistencies, auto-fixes some issues, enforces team standards.

Formatting with Prettier

Formatters automatically format your code according to a set of rules.

# Install Prettier
npm install --save-dev prettier

# Format a file
npx prettier --write myfile.js
  • Handles spaces, indentation, line-breaks
  • Few options (by design!)
  • Works alongside ESLint

prettier - Opinionated formatter: rewrites your code to follow consistent style

--write - Edits the file in place (without it, Prettier just prints the formatted output)

ESLint vs Prettier: ESLint finds problems in your code. Prettier fixes how it looks. Use both together!

IDE Extensions

ESLint Extension

  • Shows errors as squiggly lines
  • Displays rule violations inline
  • No command line needed!

Prettier Extension

  • Format with keyboard shortcut
  • Format on save (optional)
  • Instant code cleanup
⚠️ Important: Extensions are for convenience, but your project should still have the packages installed and configured. The project is the source of truth!

Form Validation

Forms are crucial for most websites: sign-ups, contact forms, search, and more!

Why Validate?

πŸ’‘ Best Practice: Always validate on both client and server!

Constraint Validation API

JavaScript provides built-in methods for form validation:

// Check if a field is valid
const emailInput = document.querySelector('#email');
if (!emailInput.validity.valid) {
  console.log(emailInput.validationMessage);
}

// Common validity properties:
emailInput.validity.valueMissing;   // Required field empty
emailInput.validity.typeMismatch;   // Wrong type (bad email)
emailInput.validity.tooShort;       // Below minlength
emailInput.validity.tooLong;        // Above maxlength

// Set custom validation message
emailInput.setCustomValidity(
  'Please use a company email');

validity - Object on every input element with boolean flags for each validation rule

validationMessage - Browser-generated error text (e.g., "Please include an '@' in the email")

setCustomValidity() - Override the default message with your own. Pass '' to clear it.

These properties map to HTML attributes: required, type, minlength, maxlength.

Live Inline Validation

Validate as the user types, not just on submit!

const form = document.querySelector('form');
const email = document.querySelector('#email');

// Validate when user leaves field
email.addEventListener('blur', () => {
  if (!email.validity.valid) {
    showError(email, 'Please enter a valid email');
  } else {
    clearError(email);
  }
});

// Prevent form submission if invalid
form.addEventListener('submit', (e) => {
  if (!form.checkValidity()) {
    e.preventDefault();
    showErrors();
  }
});

'blur' - Fires when user clicks/tabs away from a field. Better UX than validating on every keystroke.

showError / clearError - Your own helper functions to display/remove error messages in the DOM

checkValidity() - Returns true if the entire form passes all constraints

e.preventDefault() - Stops the form from submitting so you can show errors instead

What is ECMAScript?

JavaScript is a programming language that conforms to the ECMAScript standard.

Version Names:

ES6 (ES2015) Major Features

Already Covered:

  • let and const
  • Arrow functions
  • Template literals
  • Destructuring
  • Default parameters
  • Classes
  • Modules (import/export)

Coming Soon:

  • Promises
  • async/await
  • Spread operator
  • Rest parameters
  • Map and Set

Browser Support Challenge

Problem: New JavaScript features take time to be supported across all browsers.

The Reality:

Solution: We can transpile modern JavaScript to older versions!

Babel: The JavaScript Compiler

Babel transpiles modern JavaScript to code that older browsers can understand.

// Modern ES6 code you write:
const greet = (name = 'World') => `Hello, ${name}!`;

// Transpiled to ES5 by Babel:
var greet = function greet(name) {
  if (name === undefined) name = 'World';
  return 'Hello, ' + name + '!';
};

What Babel converts:

  • => arrow β†’ function keyword
  • const β†’ var
  • Default params β†’ if check
  • Template literal β†’ string concatenation

For our curriculum, modern browsers support everything we use β€” no Babel needed yet!

πŸ“š Homework Check-In

By this point, you should have completed:

  1. Sign-up Form - HTML forms and validation
  2. Admin Dashboard - CSS Grid layout
  3. Library - JavaScript object constructors
  4. Tic Tac Toe - Factory functions and module pattern
  5. Restaurant Page - ES6 modules and Webpack

Use remaining class time to:

  • Catch up on incomplete projects
  • Get help with current assignments
  • Ask questions about concepts
  • Add validation to your Library project

Today's Takeaways

You Can Now:

πŸ“… Next Class: Async and APIs

πŸ“ Homework: Catch up on previous projects!