Introduction to JavaScript
Why Study JavaScript?
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is one of the 3 languages all web developers must learn.
- ★ HTML
to define the content of web pages.
- ★ CSS
to specify the layout of web pages.
.
- ★ JavaScript
to program the behavior of web pages.
.
What can we use JavaScript for?
- ★ Make websites respond to user interaction.
- ★ Build apps and games.
- ★ Organize and present data.
JavaScript Where To?
- ★ In HTML, JavaScript code must be inserted between
<script> and </script> tags.
<script type="text/javascript" src="demo.js"></script>
- ★ Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
- ★ External scripts are practical when the same code is used in many different web pages.
- ♣ JavaScript files have the file extension .js
- ♣ To use an external script, put the name of the script file in the src (source) attribute of a
<script> </script>tag.
- ♣ Placing scripts in external files has some advantages:
- ☆ It separates HTML and code.
- ☆ It makes HTML and JavaScript easier to read and maintain.
- ☆ Cached JavaScript files can speed up page loads.
Example
In HTML file:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Demo</title>
<script type="text/javascript" src="demo.js"></script>
</head>
<body>
<button onclick="my_function()">Try it</button>
</body>
</html>
In JavaScript file:
function my_function() {
let firstName = prompt("What is your first name?");
let lastName = prompt("What is your last name?");
let fullName = firstName + ' ' + lastName;
let userConfirmed = confirm("Hello!" + fullName + " Welcome to CSCI4410/5410! Click OK to continue.");
if (userConfirmed) {
alert("You clicked OK! Enjoy the course.");
console.log(fullName + " has joined the course.");
} else {
alert("You clicked Cancel. Let us know if you need help.");
console.log(fullName + " declined to continue.");
}
}
The
confirm() function in JavaScript displays a popup dialog with "OK" and "Cancel" buttons.
It returns a Boolean value:
- ★ true if the user clicks "OK"
- ★ false if the user clicks "Cancel"
- ★ A confirm box is often used if you want the user to verify or accept something.
The
alert() function in JavaScript is used to display a simple popup message to the user.
It does not return any value and only has an "OK" button to close the dialog.
The
console.log() function is used to print messages or data to the browser console.
It's mainly used for debugging and testing in JavaScript.
Steps to Open Console Using Right Click:
- ★ 1. Right-click anywhere on a webpage.
- ★ 2. Click "Inspect" (or "Inspect Element" in some browsers).
- ★ 3. In the Developer Tools panel, click the "Console" tab.
- ★ 4. Now you can see JavaScript logs from console.log().
The
prompt() method displays a dialog box that prompts the user for input.
- ★ A prompt box is often used if you want the user to input a value before entering a page.
- ★ When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after
entering an input value.
- ★ The prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel",
the method returns null.
JavaScript Syntax
- ★ JavaScript is a programming language.
- ★ JavaScript syntax is the set of rules, how JavaScript programs are constructed.
- ★ In a programming language, these program instructions are called statements.
- ★ JavaScript statements are composed of: Variables, Operators, Expressions, Keywords, and Comments.
JavaScript Variables
- ★ JavaScript variables are containers for storing data values.
- ★ We do this by defining a variable with a specific, case-sensitive name.
- ★ Once you create (or declare) a variable as having a particular name, you can then call up that value
by typing the variable name.
JavaScript Identifiers
- ★ All JavaScript variables must be identified with unique names.
- ★ These unique names are called identifiers.
- ★ Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers)
- ★ Names can contain letters, digits, underscores, and dollar signs.
- ★ Names must begin with a letter.
- ★ Names are case sensitive (eg: y and Y are different variables).
- ★ Reserved words (like JavaScript keywords) cannot be used as names.
Declaring(Creating) JavaScript Variables
- ★ Creating a variable in JavaScript is called "declaring" a variable.
- ★ JavaScript Variables can be declared in the following ways:
- var: The var keyword was used in all JavaScript code from 1995 to 2015.
- let: The let keyword was added to JavaScript in 2015.
- const: The const keyword was added to JavaScript in 2015.
Keyword |
Introduced |
Can Be Reassigned? |
Can Be Redeclared? |
Scope |
var |
Since 1995 |
✅ Yes |
✅ Yes (Function Scope) |
Function Scope |
let |
ES6 (2015) |
✅ Yes |
❌ No (Block Scope) |
Block Scope |
const |
ES6 (2015) |
❌ No |
❌ No (Block Scope) |
Block Scope |
- ★ After the declaration, the variable has no value. (Technically it has the value of undefined). To
assign a value to the variable, and use the equal sign.
- ★ Example:
// syntax
var var_name = data;
// Example using var
var my_name = "Ada";
var my_age = 33;
var is_male = true;
// Example using let
let x = 5;
let y = 6;
let z = x + y;
// Example using const
const x = 5;
const y = 6;
const z = x + y;
// Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
★ The var keyword should only be used in code written for older browsers.
★ Variables declared with let cannot be Redeclared in the same scope
★ Variables defined with const cannot be Redeclared
★ Variables defined with const cannot be Reassigned
JavaScript Arithmetic Operators
JavaScript Arithmetic Operators are used to perform arithmetic on numbers:
Operator |
Description |
+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
** |
Exponentiation |
% |
module |
++ |
increment |
-- |
decrement |
- ★ The + operator can also be used to add (concatenate) strings.
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The result of text3 will be: John Doe
★ JavaScript Arithmetic Operators Examples.
let a = 10;
let b = 5;
console.log(a + b); // ✅ Addition → Output: 15
console.log(a - b); // ✅ Subtraction → Output: 5
console.log(a * b); // ✅ Multiplication → Output: 50
console.log(a / b); // ✅ Division → Output: 2
console.log(a ** 2); // ✅ Exponentiation → Output: 100
console.log(a % 3); // ✅ Modulus (Remainder) → Output: 1
// Increment and Decrement
let x = 5;
console.log(++x); // ✅ Pre-increment → Output: 6
console.log(x++); // ✅ Post-increment → Output: 6 (then x becomes 7)
console.log(--x); // ✅ Pre-decrement → Output: 6
console.log(x--); // ✅ Post-decrement → Output: 6 (then x becomes 5)
JavaScript Assignment Operators
Operator |
Example |
Same as |
= |
x = y |
x=y |
+= |
x += y |
x = x + y |
-= |
x -= y |
x = x - y |
*= |
x *= y |
x = x * y |
/= |
x /= y |
x = x / y |
%= |
x %= y |
x = x % y |
JavaScript Comparison Operators
Operator |
Description |
Example |
Result |
== |
Equal to (checks value only) |
5 == "5" |
true |
=== |
Strict equal (checks value and type) |
5 === "5" |
false |
!= |
Not equal (checks value only) |
10 != "10" |
false |
!== |
Strict not equal (checks value and type) |
10 !== "10" |
true |
> |
Greater than |
8 > 5 |
true |
< |
Less than |
3 < 7 |
true |
>= |
Greater than or equal to |
6 >= 6 |
true |
<= |
Less than or equal to |
4 <= 9 |
true |
? : |
Ternary operator (shorthand for if-else) |
let result = (age >= 18) ? "Adult" : "Minor"; |
"Adult" if age >= 18, otherwise "Minor" |
Examples in JavaScript:
1. Loose Equality (==) vs. Strict Equality (===)
console.log(5 == "5"); // true (loose equality, only checks value)
console.log(5 === "5"); // false (strict equality, checks value and type)
2. Ternary Operator (? :)
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // Output: "Adult"
Logical Operators
Logical operator |
Description |
&& |
logic and |
|| |
logic or |
! |
logic not |
JavaScript has 8 Datatypes
- ★ 1. String: Strings are written with quotes. You can use single or
double quotes:
- ★ 2. Number
- ★ 3. Bigint: used to store integer values that are too big to be represented by a normal JavaScript
Number.
- ★ 4. Boolean: can only have two values: true or false.
- ★ 5. Undefined: a variable without a value, has the value undefined
- ♣ An empty value has nothing to do with undefined.
let car; // Value is undefined, type is undefined
let car = ""; // The value is "", the typeof is "string"
★ 6. Null
★ 7. Symbol
★ 8. Object:
The object data type can contain:
- An object
- An array
- A date
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
- You can use the JavaScript
typeof
operator to find the type of a JavaScript variable.
- The typeof operator returns the type of a variable or an expression:
typeof "John Doe"; // Returns "string"
var x = 5;
typeof x; // Returns "Number"
Type |
Description |
Example |
String |
Represents text data |
"Hello, World!" |
Number |
Represents numeric values (integers & floating-point) |
42, 3.14, -10 |
BigInt |
For very large integers beyond Number limits |
BigInt(9007199254740991) , 123456789012345678901234567890n |
Boolean |
Represents true or false |
true, false |
Undefined |
A variable declared but not assigned a value |
let x; console.log(x); // undefined |
Null |
Represents an empty or unknown value |
let y = null; |
Symbol |
Unique and immutable values (introduced in ES6) |
let sym = Symbol('id'); |
Object |
Complex data structure (objects, arrays, functions) |
{ name: "Alice", age: 25 } , [1, 2, 3] , function() {} |
JavaScript Data Type Examples
// String
let name = "Alice";
console.log(typeof name); // Output: "string"
// Number
let age = 30;
console.log(typeof age); // Output: "number"
// BigInt
let bigNumber = 123456789012345678901234567890n;
console.log(typeof bigNumber); // Output: "bigint"
// Boolean
let isStudent = true;
console.log(typeof isStudent); // Output: "boolean"
// Undefined
let x;
console.log(typeof x); // Output: "undefined"
// Null (special case, returns "object" due to a JS bug)
let y = null;
console.log(typeof y); // Output: "object"
// Symbol
let sym = Symbol('id');
console.log(typeof sym); // Output: "symbol"
// Object
let person = { firstName: "John", lastName: "Doe" };
console.log(typeof person); // Output: "object"
// Array (special type of object)
let numbers = [1, 2, 3];
console.log(typeof numbers); // Output: "object"
// Function (also a type of object)
function greet() {
return "Hello!";
}
console.log(typeof greet); // Output: "function"
JavaScript Functions
- ★ A JavaScript function is a block of code designed to perform a particular task.
- ★You can reuse code: Define the code once, and use it many times.
- ★ A JavaScript function is defined with the function keyword, followed
by a name, followed by
parentheses ().
- ★ The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...).
- ★ The code to be executed, by the function, is placed inside curly brackets:
function func_name(parameter1, parameter2,...){
//code to be executed
}
★ Function Invocation.The code inside the function will execute when "something" invokes (calls) the function:
- a. When it is invoked (called) from JavaScript code
//Example: Direct Function Call
function greet() {
console.log("Hello, welcome to JavaScript!");
}
// Function is invoked
greet();
b. When an event occurs (when a user clicks a button)
//Function Invocation by an Event (e.g., Button Click)
JavaScript:
function showMessage() {
alert("Button Clicked! Function Invoked.");
}
HTML:
<button onclick="showMessage()">Click Me</button>
c. Function Invocation with an Event Listener
JavaScript:
//Using addEventListener()
function showAlert() {
alert("Function invoked using an event listener!");
}
// Add event listener to the button
document.getElementById("myButton").addEventListener("click", showAlert);
HTML:
<button id="myButton">Click Me</button>
Correct Syntax for addEventListener():
document.getElementById("myId").addEventListener("eventType",function);
- ★ "eventType": The type of event (e.g., "click", "mouseover", "keydown").
- ★ function: The function that executes when the event happens.
Inline onclick vs addEventListener() in JavaScript
Both addEventListener() and using onclick in HTML can trigger a function when a button is clicked,
but they have key differences in terms of flexibility, maintainability, and best practices.
✅Pros of Inline onclick: |
✅Pros of addEventListener(): |
- ✅ Simple and easy for small script
- ✅ Quick to implement
|
- ✅ Separates JavaScript from HTML (better code structure)
- ✅ Can add multiple event listeners to the same element
- ✅ Can be dynamically removed using removeEventListener()
|
❌Cons of Inline onclick: |
❌Cons of addEventListener(): |
- ❌ Harder to maintain (mixes HTML with JavaScript)
- ❌ Cannot attach multiple event listeners (only one onclick per element)
- ❌ Less flexible for dynamic event handling
|
- ❌ Slightly more code compared to onclick
- ❌ Requires selecting the element first (document.getElementById())
|
Global and Local variables
- ★ Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.
- ★ Variables defined inside a function are local variables. They cannot be accessed outside of that
function.
HTML <button> </button> tags and onclick Event Attribute
- ★ The <button> </button> tag defines a clickable button.
- ★ The onclick attribute fires on a mouse click on the element.
- ★ <button onclick = "my_function()">Click me</button>
- ★ Common HTML events:
Event Attribute |
Description |
Example |
onclick |
Fires when an element is clicked |
<button class="example-btn" onclick="alert('Clicked!')">Click Me</button> |
ondblclick |
Fires when an element is double-clicked |
<button class="example-btn" ondblclick="alert('Double Clicked!')">Double Click Me</button> |
onmouseover |
Fires when the mouse hovers over an element |
<button class="example-btn" onmouseover="this.style.backgroundColor='yellow'" onmouseout="this.style.backgroundColor='lightgray'">Hover Over Me</button> |
onkeydown |
Fires when a key is pressed on the keyboard |
<input type="text" placeholder="Type something..." onkeydown="alert('Key Pressed!')"> |
- ★ Other HTML events: Event Attributes
JavaScript Events
- ★ HTML events are "things" that happen to HTML elements.
- ★ When JavaScript is used in HTML pages, JavaScript can "react" on these events.
The Document Object
- ★ When a webpage loads, the browser creates a Document Object Model (DOM).
- ★ When an HTML document is loaded into a web browser, it becomes a document
object.
- ★ The document object is the root node of the HTML document.
- ★ The document object allows JavaScript to access and modify the HTML and CSS of a webpage.
How the DOM Works
- ★ When a webpage loads, the browser converts the HTML document into a DOM tree.
Each HTML element becomes a node in this tree.
- ★ Example: HTML Structure
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="heading">Hello, DOM!</h1>
<p class="text">This is a paragraph.</p>
<button onclick="changeText()">Click Me</button>
</body>
</html>
★ How the Browser Translates it into a DOM Tree
Document
├── <html>
│ ├── <head>
│ │ └── <title>My Page</title>
│ ├── <body>
│ ├── <h1 id="heading">Hello, DOM!</h1>
│ ├── <p class="text">This is a paragraph.</p>
│ └── <button onclick="changeText()">Click Me</button>
✅ JavaScript can access, modify, and manipulate any of these elements using the DOM!
Select and Modify DOM Elements
Select DOM Elements
getElementById() method (Selects One Element by ID)
- ♣ The document.getElementById() method selects one HTML element by its unique ID and
allows JavaScript to manipulate it.
- ♣ The getElementById() method returns an element object if the specified id exists in the HTML document.
It returns null if the element does not exist.
- ♣ The getElementById() method is one of the most common methods in the
HTML DOM. It is used almost every time you want to read or edit an HTML element.
- ♣ The innerHTML property sets or returns the HTML content (inner HTML)
of an element.
JavaScript:
let title = document.getElementById("heading");
console.log(title.innerHTML); // Output: Hello, DOM!
HTML:
<h1 id="heading">Hello, DOM!</h1>
querySelector() method (Selects the first matching HTML element)
- ♣ The querySelector() method is used to select the first matching HTML element based on a CSS selector.
- ♣ It returns the first matching element in the document. If no element matches, it returns null.
// Selecting an Element by ID
let title = document.querySelector("#myTitle"); // Selects the first element with ID "myTitle"
// Selecting an Element by Class
let box = document.querySelector(".box"); // Selects the first element with class "box"
//Selecting an Element by Tag Name
let firstParagraph = document.querySelector("p"); // Selects the first <p> tag
// Selecting an Element by a Nested Selector
let firstItem = document.querySelector("ul li"); // Selects the first <li> inside <ul>
querySelectorAll() method (Selecting Multiple Elements by IDs)
- ♣ The document.querySelectorAll() method can be used to select multiple elements by multiple IDs using CSS ID selectors.
- ♣ The comma (,) allows you to select multiple elements by their IDs.
- ♣ Returns a NodeList, which behaves like an array and allows iteration.
- ♣ Works with tags, classes, IDs,
and other CSS selectors.
JavaScript:
function changeText() {
// Select multiple IDs
let elements = document.querySelectorAll("#title1, #title2, #title3");
elements.forEach(element => {
element.innerHTML = "Updated Heading"; // Change text
element.style.color = "blue"; // Change color
});
}
HTML:
<h1 id="title1">Heading 1</h1>
<h1 id="title2">Heading 2</h1>
<h1 id="title3">Heading 3</h1>
<button onclick="changeText()">Change Headings</button>
Modify DOM Elements
Change Content (innerHTML)
document.getElementById("heading").innerHTML = "Hello, JavaScript!";
Change Styles (style)
document.getElementById("heading").style.color = "blue";
Combined Examples:
JavaScript:
document.getElementById("heading").addEventListener("click", function() {
// Change Content
document.getElementById("heading").innerHTML = "Hello, JavaScript!";
// Apply Multiple Style Changes
document.getElementById("heading").style.color = "blue";
});
HTML:
<h1 id="heading">Hello, DOM!</h1>
Reference