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.

What can we use JavaScript for?

JavaScript Where To?

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:
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: The prompt() method displays a dialog box that prompts the user for input.

JavaScript Syntax

JavaScript Variables

JavaScript Identifiers

The general rules for constructing names for variables (unique identifiers)

Declaring(Creating) JavaScript Variables

JavaScript Arithmetic Operators

JavaScript Arithmetic Operators are used to perform arithmetic on numbers:

Operator Description
+ addition
- subtraction
* multiplication
/ division
** Exponentiation
% module
++ increment
-- decrement


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

			// 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");
		
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

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

HTML <button> </button> tags and onclick Event Attribute

JavaScript Events

The Document Object

How the DOM Works

Select and Modify DOM Elements

Select DOM Elements

getElementById() method (Selects One Element by ID)
			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)
	// 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)
		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