Introduction to JavaScript
Understand JavaScript fundamentals, DOM interaction, and asynchronous programming with Node.js.
Summary
Read Summary
Flashcards
Save Flashcards
Quiz
Take Quiz
Quick Practice
What is the primary JavaScript runtime used for back-end services?
1 of 19
Summary
Introduction to JavaScript
What is JavaScript and Why Does It Exist?
JavaScript is a programming language created to add interactivity to static HTML pages. Before JavaScript, web pages were static documents that couldn't respond to user actions. Today, JavaScript has become the de facto language that powers interactive features across the web.
JavaScript is unique because it runs in multiple environments:
In web browsers — where it makes web pages interactive
On servers and devices — via the Node JavaScript runtime, enabling full-stack development
In various other applications — wherever a JavaScript runtime is available
This versatility means JavaScript can power everything from simple click handlers to complex single-page applications and back-end web services.
Basic Syntax and Variables
JavaScript uses C-style syntax conventions. Statements end with semicolons, and code blocks are wrapped in curly braces {}.
Variables are declared using three keywords:
let — the preferred modern way to declare variables with block scope
const — declares variables that cannot be reassigned (use this by default)
var — the older way to declare variables (avoid in modern JavaScript)
Here's a simple example:
javascript
const name = "Alice";
let count = 0;
var oldStyle = "avoid this"; // old style
Important: Dynamic Typing and Type Coercion
JavaScript is dynamically typed, meaning you don't specify data types when creating variables—the language figures them out automatically. A variable can hold different types at different times:
javascript
let value = 42; // number
value = "hello"; // now it's a string
value = true; // now it's a boolean
JavaScript also performs type coercion, automatically converting between types when necessary. This can be convenient but also tricky:
javascript
console.log("5" + 3); // "53" (concatenation, not addition)
console.log("5" - 3); // 2 (coerced to numbers)
console.log("5" == 5); // true (loose equality with coercion)
console.log("5" === 5); // false (strict equality, no coercion)
Important tip: Use === and !== for comparisons instead of == and != to avoid unexpected type coercion bugs.
Data Types and Structures
JavaScript provides several ways to organize data:
Primitive Types
The basic primitive types are:
Numbers — 42, 3.14, and Infinity
Strings — "hello", 'world', template
Booleans — true and false
Objects as Key-Value Maps
Objects store collections of related data as key-value pairs. Think of them as labeled containers:
javascript
const person = {
name: "Alice",
age: 30,
city: "Portland"
};
console.log(person.name); // "Alice"
console.log(person["age"]); // 30
Objects are versatile and used throughout JavaScript for organizing related data.
Arrays as Ordered Collections
Arrays hold ordered lists of values with numeric indexing (starting at 0):
javascript
const fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits.length); // 3
Functions as First-Class Values
In JavaScript, functions are first-class values—they can be assigned to variables, passed as arguments, and returned from other functions. This is a powerful feature:
javascript
const greet = function(name) {
return "Hello, " + name;
};
console.log(greet("Bob")); // "Hello, Bob"
Interacting with Web Pages: The Document Object Model
The Document Object Model (DOM) is a tree-like representation of an HTML page. JavaScript uses the DOM to read and modify page content.
Selecting Elements
JavaScript provides methods to select HTML elements:
document.querySelector(selector) — selects the first element matching a CSS selector:
javascript
const header = document.querySelector("h1");
const button = document.querySelector("#submit-btn");
const items = document.querySelector(".list-item");
getElementById(id) — selects a single element by its unique id attribute (a slightly older but still useful method):
javascript
const input = document.getElementById("username");
Responding to User Interactions
The addEventListener() method attaches a listener to an element so JavaScript can respond to user events like clicks, typing, or mouse movement:
javascript
const button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("Button was clicked!");
});
This code pattern is fundamental to interactive web development. The code shows real examples of selecting elements and manipulating the DOM.
Event-Driven Programming
Modern web interfaces are built on an event-driven model: the page responds to user actions by triggering event listeners that run JavaScript code.
When you attach an event listener, your code can:
Change page content — update text, add/remove elements
Change styling — apply CSS classes or modify styles
Change behavior — enable/disable features, navigate to new pages
The key advantage is non-reloading interactivity. Without event-driven updates, every user action would require the entire page to reload. With events, you can update just what changed:
javascript
const submitButton = document.querySelector("button");
submitButton.addEventListener("click", function() {
const input = document.querySelector("input");
const message = input.value;
// Update the page without reloading
const display = document.querySelector(".result");
display.textContent = "You said: " + message;
display.style.color = "blue";
});
This is the foundation of responsive, fast-feeling web applications.
Control Flow: Making Decisions and Repeating Code
JavaScript provides standard ways to control program flow:
If Statements for Conditional Execution
The if statement runs a block of code only when a condition is true:
javascript
if (age >= 18) {
console.log("You can vote");
} else {
console.log("You're too young to vote");
}
For Loops for Known Repetition
The for loop repeats code a specific number of times:
javascript
for (let i = 0; i < 5; i++) {
console.log("Count: " + i);
}
While Loops for Conditional Repetition
The while loop repeats code while a condition is true:
javascript
let x = 0;
while (x < 5) {
console.log("x is " + x);
x = x + 1;
}
Functions for Reusable Code
Functions encapsulate reusable pieces of code. They take arguments (inputs) and can return a value (output):
javascript
function multiply(a, b) {
return a b;
}
console.log(multiply(3, 4)); // 12
Functions let you write code once and use it many times, making your code cleaner and easier to maintain.
Object Literals for Creating Simple Objects
Object literals use curly braces to define objects with key-value pairs:
javascript
const book = {
title: "Learning JavaScript",
author: "Jane Smith",
pages: 450
};
This is a convenient shorthand for creating objects with initial data.
Asynchronous Programming: Doing Work Without Freezing the Page
Some operations take time—loading data from the internet, reading files, or querying databases. If you run these operations normally, the entire page would freeze until they finish. JavaScript solves this with asynchronous programming.
Callbacks: Functions That Run Later
A callback is a function passed as an argument to be executed later when an asynchronous operation completes:
javascript
function loadUserData(userId, callback) {
// Simulate loading from server
setTimeout(function() {
callback({ id: userId, name: "Alice" });
}, 1000);
}
loadUserData(1, function(user) {
console.log("User loaded: " + user.name);
});
Promises: A Cleaner Approach
Promises provide a cleaner way to handle asynchronous operations. A promise represents a value that will be available in the future. You use .then() to specify what happens when the promise resolves:
javascript
loadUserDataPromise(1)
.then(function(user) {
console.log("User loaded: " + user.name);
});
The Fetch Function
The fetch function is a promise-based API that loads data from a server without blocking the user interface:
javascript
fetch("https://api.example.com/users/1")
.then(response => response.json())
.then(user => {
console.log("User: " + user.name);
});
The key benefit is asynchronous operations prevent UI freezing. While waiting for the server to respond, the user can still click buttons, scroll, and interact with the page normally.
Server-Side JavaScript with Node
The Node JavaScript runtime extends JavaScript beyond the browser, enabling server-side development. Node gives JavaScript access to:
The file system — read and write files on the server
Databases — connect to and query databases
Networking — make HTTP requests and build servers
Because the same language works on both client and server, developers can share code and libraries between client and server. For example, validation logic written in JavaScript can run in the browser and on the server, reducing duplication and keeping both sides in sync.
This makes JavaScript a full-stack language suitable for building complete web applications from front-end to back-end.
Flashcards
What is the primary JavaScript runtime used for back-end services?
Node
What two C-style syntax conventions does JavaScript use for statements and code blocks?
Semicolons to end statements and curly braces for code blocks.
Which three keywords are used to declare variables in JavaScript?
let
const
var
What does it mean for JavaScript to be "dynamically typed"?
Data types do not need to be specified when a variable is created.
What is the term for JavaScript automatically converting data types when necessary?
Type coercion
How are JavaScript Objects structured to store data?
As collections of key-value pairs.
What does it mean for functions to be "first-class values" in JavaScript?
They can be passed around like any other data.
What is the structural representation of the Document Object Model?
A tree-like representation of an HTML page.
Which method is used to select a single element by its unique identifier?
getElementById
Which method is used to attach a listener to an element for responding to user events?
addEventListener
What is a major advantage for developers using JavaScript for both client-side and server-side development?
They can share code and libraries across environments.
Under what condition does an "if statement" run its block of code?
Only when a specified condition is true.
When is a "for loop" typically used instead of other loops?
When repeating a block of code a known number of times.
How long does a "while loop" continue to repeat its code block?
While a specified condition remains true.
What is the syntax for defining an object literal?
A comma-separated list of key-value pairs inside curly braces.
What are "callbacks" in the context of asynchronous operations?
Functions passed as arguments to be executed later when an operation completes.
What does a promise-based API, such as the fetch function, return?
A promise that resolves when the operation finishes.
How does the fetch function handle data retrieval from a server?
It retrieves data without blocking the user interface.
What is the primary benefit of asynchronous programming for web interfaces?
It prevents time-consuming operations from freezing the user interface.
Quiz
Introduction to JavaScript Quiz Question 1: What programming model underlies modern web interfaces in JavaScript?
- Event‑driven model (correct)
- Procedural model
- Functional reactive model
- Object‑oriented model
Introduction to JavaScript Quiz Question 2: Which characters are used to delimit code blocks in JavaScript?
- Curly braces { } (correct)
- Parentheses ( )
- Square brackets [ ]
- Angle brackets < >
Introduction to JavaScript Quiz Question 3: Which loop structure repeats a block of code a known number of times in JavaScript?
- for loop (correct)
- while loop
- do…while loop
- if statement
Introduction to JavaScript Quiz Question 4: Which built‑in function fetches data from a server without blocking the user interface?
- fetch (correct)
- XMLHttpRequest
- setTimeout
- Promise.all
Introduction to JavaScript Quiz Question 5: Which keywords are used to declare variables in modern JavaScript?
- let, const, and var (correct)
- function, class, and import
- static, private, and protected
- enum, type, and interface
Introduction to JavaScript Quiz Question 6: What JavaScript data structure stores ordered collections of values with numeric indexing?
- Arrays (correct)
- Objects
- Functions
- Strings
Introduction to JavaScript Quiz Question 7: Which DOM method selects elements using CSS selectors?
- document.querySelector (correct)
- document.getElementById
- document.getElementsByClassName
- document.createElement
Introduction to JavaScript Quiz Question 8: Which capability does the Node runtime give JavaScript programs?
- Perform networking operations (correct)
- Access the Document Object Model
- Automatically render graphics
- Compile code to native binaries
Introduction to JavaScript Quiz Question 9: Which of the following is NOT a typical use of JavaScript?
- Developing low‑level operating system kernels (correct)
- Implementing simple click handlers in web pages
- Creating complex single‑page applications
- Writing back‑end services using Node.js
Introduction to JavaScript Quiz Question 10: In JavaScript, which data structure is primarily used to store collections of key‑value pairs?
- Objects (correct)
- Arrays
- Functions
- Numbers
Introduction to JavaScript Quiz Question 11: Which DOM method is used to attach an event listener to an element?
- addEventListener (correct)
- getElementById
- querySelector
- removeEventListener
Introduction to JavaScript Quiz Question 12: What does it mean that JavaScript is dynamically typed?
- Variable types are determined at runtime and need not be declared (correct)
- All variables must be declared with a type keyword
- Type checking occurs only during compilation
- Variables can hold only one fixed type for their lifetime
Introduction to JavaScript Quiz Question 13: What capability does the Node JavaScript runtime give programs?
- Access to the file system (correct)
- Direct manipulation of the browser DOM
- Automatic rendering of HTML pages
- Compilation to native machine code
Introduction to JavaScript Quiz Question 14: The Document Object Model (DOM) represents an HTML page as what kind of structure?
- A tree‑like hierarchy (correct)
- A flat list of elements
- A relational database schema
- A binary search tree
Introduction to JavaScript Quiz Question 15: Which JavaScript construct runs a block of code only when a specified condition is true?
- If statement (correct)
- While loop
- For loop
- Function declaration
Introduction to JavaScript Quiz Question 16: Calling the fetch function in modern JavaScript returns which type of object immediately?
- A Promise (correct)
- The raw response data
- An Event object
- A callback function
Introduction to JavaScript Quiz Question 17: How are functions treated in JavaScript regarding their use as values?
- They are first‑class values that can be passed as arguments (correct)
- They can only be declared at the top level of a script
- They cannot be assigned to variables
- They must be invoked immediately upon definition
Introduction to JavaScript Quiz Question 18: The DOM method <code>getElementById</code> selects an element based on which attribute?
- The element's <code>id</code> attribute (correct)
- The element's <code>class</code> attribute
- The element's <code>name</code> attribute
- The element's tag name
Introduction to JavaScript Quiz Question 19: Which of the following is NOT a primitive data type in JavaScript?
- Object (correct)
- Number
- String
- Boolean
Introduction to JavaScript Quiz Question 20: Which programming model allows JavaScript to respond to user actions such as clicks or key presses?
- Event‑driven programming (correct)
- Procedural programming
- Object‑oriented programming
- Functional programming
Introduction to JavaScript Quiz Question 21: How are objects defined using object literal notation in JavaScript?
- Curly braces containing comma‑separated key‑value pairs (correct)
- Using the <code>new</code> keyword with a constructor function
- Assigning a function to a variable
- Calling a class constructor with <code>class</code>
Introduction to JavaScript Quiz Question 22: Event‑driven programming enables a web page to update without doing what?
- Reloading the entire document (correct)
- Opening a new browser window
- Changing the URL
- Downloading additional resources
What programming model underlies modern web interfaces in JavaScript?
1 of 22
Key Concepts
JavaScript Fundamentals
JavaScript
Dynamic typing
First‑class functions
Web Development Concepts
Node.js
Document Object Model
CSS selectors
fetch API
Programming Paradigms
Event‑driven programming
Asynchronous programming
Promise (JavaScript)
Definitions
JavaScript
A high‑level, interpreted programming language that adds interactivity to web pages and powers modern web applications.
Node.js
A server‑side JavaScript runtime built on Chrome’s V8 engine that enables JavaScript to run outside browsers.
Document Object Model
A tree‑like programming interface that represents HTML and XML documents as objects for scriptable access.
Event‑driven programming
A paradigm where program flow is determined by events such as user actions, timers, or messages.
Asynchronous programming
An execution model that allows time‑consuming operations to run without blocking the main thread.
Promise (JavaScript)
An object representing the eventual result or failure of an asynchronous operation, enabling chained handling.
Dynamic typing
A language feature where variable types are resolved at runtime rather than being declared explicitly.
First‑class functions
Functions that can be treated like any other value: passed as arguments, returned from other functions, and assigned to variables.
fetch API
A web API that performs network requests and returns a Promise resolving to the response data.
CSS selectors
Pattern syntax used to select and manipulate elements within the Document Object Model.