Week 8: JavaScript Basics
JS | Variables, Conditions, Loops, Functions, Arrays, Objects
Week 08 - JavaScript Basics
Web Development 1 — Al-Aqsa University
What is JavaScript?
JavaScript is a high-level, dynamic, interpreted programming language that is one of the core technologies of the World Wide Web. Along with HTML and CSS, JavaScript makes web pages interactive and dynamic.
- HTML provides the structure (skeleton)
- CSS provides the presentation (skin and clothes)
- JavaScript provides the behavior (muscles and brain)
Where Does JavaScript Run?
JavaScript was originally designed to run only in web browsers, but now it runs everywhere:
- Browser - Chrome (V8 engine), Firefox (SpiderMonkey), Safari (JavaScriptCore)
- Server - Node.js (built on V8 engine)
- Mobile - React Native, Ionic
- Desktop - Electron (VS Code, Discord, Slack are built with it)
Fun Fact
JavaScript was created by Brendan Eich in just 10 days in 1995. Despite its name, JavaScript has no relation to Java — the name was a marketing decision.
Adding JavaScript to HTML
1. Inline Script Tag
Write JavaScript directly inside <script> tags in the HTML file:
<!-- At the bottom of the body -->
<script>
console.log("Hello from inline script!");
</script>
2. External JavaScript File
Link a separate .js file — the recommended approach for larger projects:
<!-- Link to external file -->
<script src="script.js"></script>
<!-- Or with full path -->
<script src="./js/main.js"></script>
3. Script Loading: defer vs async
When the browser encounters a <script> tag, it stops parsing HTML to download and execute the script. defer and async change this behavior:
<!-- Normal: blocks HTML parsing -->
<script src="app.js"></script>
<!-- defer: downloads in parallel, executes after HTML is parsed -->
<script src="app.js" defer></script>
<!-- async: downloads in parallel, executes as soon as downloaded -->
<script src="app.js" async></script>
| Attribute |
Download |
Execution |
Order Preserved |
Best For |
| (none) |
Blocks parsing |
Immediately |
Yes |
Critical inline scripts |
defer |
In parallel |
After HTML parsed |
Yes |
Most scripts (recommended) |
async |
In parallel |
As soon as ready |
No |
Independent scripts (analytics) |
Best Practice
Use defer for most scripts placed in the <head>. If you place scripts at the bottom of <body>, defer is not needed since HTML is already parsed.
Console Methods
The console is your best friend for debugging. Open it with F12 or Ctrl+Shift+J in Chrome.
// Basic logging
console.log("Hello, World!"); // General output
console.log("Name:", "Ahmad", "Age:", 25); // Multiple values
// Warning (yellow)
console.warn("This is a warning!");
// Error (red)
console.error("Something went wrong!");
// Table - great for arrays and objects
const students = [
{ name: "Ahmad", grade: 90 },
{ name: "Sara", grade: 95 },
{ name: "Omar", grade: 88 }
];
console.table(students);
// Timing
console.time("loop");
for (let i = 0; i < 1000000; i++) {}
console.timeEnd("loop"); // loop: 3.45ms
// Grouping
console.group("User Info");
console.log("Name: Ahmad");
console.log("Age: 25");
console.groupEnd();
// Clear console
console.clear();
Variables: var vs let vs const
Variables are containers for storing data. JavaScript has three ways to declare variables:
var (old way - avoid in modern JS)
var name = "Ahmad";
var name = "Sara"; // No error! Can re-declare
name = "Omar"; // Can reassign
// var is function-scoped, NOT block-scoped
if (true) {
var x = 10;
}
console.log(x); // 10 - accessible outside the block!
let (modern - for values that change)
let age = 25;
age = 26; // Can reassign
// let age = 30; // Error! Cannot re-declare in same scope
// let is block-scoped
if (true) {
let y = 20;
}
// console.log(y); // Error! y is not defined outside the block
const (modern - for values that don't change)
const PI = 3.14159;
// PI = 3.14; // Error! Cannot reassign
// const PI = 3; // Error! Cannot re-declare
// const MUST be initialized when declared
// const x; // Error! Missing initializer
// BUT: const objects and arrays CAN be modified
const person = { name: "Ahmad" };
person.name = "Sara"; // OK! Modifying property
person.age = 25; // OK! Adding property
// person = {}; // Error! Cannot reassign the variable itself
const colors = ["red"];
colors.push("blue"); // OK! Modifying the array
// colors = []; // Error! Cannot reassign
Hoisting
// var is hoisted (moved to top) with value undefined
console.log(a); // undefined (not an error!)
var a = 5;
// let and const are hoisted but NOT initialized
// console.log(b); // Error! Cannot access 'b' before initialization
let b = 10;
// This is called the "Temporal Dead Zone" (TDZ)
| Feature |
var |
let |
const |
| Scope | Function | Block | Block |
| Re-declare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisting | Yes (undefined) | Yes (TDZ) | Yes (TDZ) |
| Must initialize | No | No | Yes |
Best Practice
Use const by default. Use let only when you need to reassign. Never use var.
Data Types
JavaScript has 8 data types. Seven are "primitive" (immutable) and one is "complex" (mutable):
Primitive Types
// 1. String - text enclosed in quotes
let firstName = "Ahmad"; // double quotes
let lastName = 'Hassan'; // single quotes
let greeting = `Hello!`; // backticks (template literal)
// 2. Number - integers and decimals
let age = 25;
let price = 19.99;
let negative = -5;
let infinity = Infinity;
let notANum = NaN; // Not a Number
// 3. Boolean - true or false
let isLoggedIn = true;
let isAdmin = false;
// 4. null - intentional empty value
let selectedUser = null;
// 5. undefined - variable declared but not assigned
let score;
console.log(score); // undefined
// 6. BigInt - for very large integers
let big = 9007199254740991n;
// 7. Symbol - unique identifier
let id = Symbol("id");
typeof Operator
console.log(typeof "Hello"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a famous JS bug!)
console.log(typeof {}); // "object"
console.log(typeof []); // "object" (arrays are objects)
console.log(typeof function(){}); // "function"
Type Conversion
// String to Number
let str = "42";
console.log(Number(str)); // 42
console.log(parseInt("42px")); // 42 (stops at non-numeric char)
console.log(+str); // 42 (unary plus shortcut)
console.log(Number("abc")); // NaN
// Number to String
let num = 42;
console.log(String(num)); // "42"
console.log(num.toString()); // "42"
console.log(num + ""); // "42" (concatenation trick)
// To Boolean
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false
console.log(Boolean(1)); // true
console.log(Boolean("hi")); // true
console.log(Boolean([])); // true (empty array is truthy!)
Falsy Values
There are exactly 6 falsy values in JavaScript: false, 0, "" (empty string), null, undefined, and NaN. Everything else is truthy.
Operators
Arithmetic Operators
let a = 10, b = 3;
console.log(a + b); // 13 Addition
console.log(a - b); // 7 Subtraction
console.log(a * b); // 30 Multiplication
console.log(a / b); // 3.33 Division
console.log(a % b); // 1 Modulus (remainder)
console.log(a ** b); // 1000 Exponentiation (10^3)
// Increment & Decrement
let x = 5;
x++; // x is now 6 (post-increment)
x--; // x is now 5 (post-decrement)
++x; // x is now 6 (pre-increment)
// String concatenation with +
console.log("Hello" + " " + "World"); // "Hello World"
console.log("5" + 3); // "53" (string wins!)
console.log("5" - 3); // 2 (only + does concatenation)
Comparison Operators
// Loose equality (==) - compares VALUE only, converts types
console.log(5 == "5"); // true (string "5" converted to number)
console.log(0 == false); // true
console.log(null == undefined); // true
// Strict equality (===) - compares VALUE and TYPE
console.log(5 === "5"); // false (different types)
console.log(5 === 5); // true
console.log(0 === false); // false
// Not equal
console.log(5 != "5"); // false (loose)
console.log(5 !== "5"); // true (strict)
// Greater / Less than
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10