Introduction to JavaScript
JavaScript is a high-level, dynamically typed scripting language primarily used for client-side web development. It enables interactive behavior on websites and integrates seamlessly with HTML and CSS. Despite its name, JavaScript has no direct relation to the Java programming language—its naming was largely a marketing decision during its early development.
Modern browsers support JavaScript natively, allowing scripts embedded in web pages to execute without additional plugins. JavaScript code can either be written inline within <script> tags or loaded externally via the src attribute:
<!-- Inline script -->
<script>
alert('Hello from JavaScript');
</script>
<!-- External file reference -->
<script src="app.js"></script>
Comments and Code Organization
JavaScript supports two types of comments:
- Single-line comments using
// - Multi-line commments enclosed in
/* ... */
Code execution typically follows a structured learning path: variables → data types → operators → control structures → functions → object-oriented patterns.
Variable Declaration and Scope
In JavaScript, variables are declared using three keywords:
- var: Function-scoped; declarations are hoisted and accessible throughout their enclosing function.
- let: Block-scoped (introduced in ES6); limited to the current block (e.g., loops, conditionals).
- const: Also block-scoped but immutable once assigned; ideal for constants like
PI.
Example demonstrating scope differences:
let globalCounter = 5;
for (let globalCounter = 0; globalCounter < 3; globalCounter++) {
console.log(globalCounter); // Outputs: 0, 1, 2
}
console.log(globalCounter); // Still outputs: 5
const PI_VALUE = 3.14159;
// PI_VALUE = 3; // This would throw an error
Data Types in JavaScript
Numeric Values
All numbers in JavaScript are floating-point values, represented by the number type. Special numeric values include:
NaN("Not-a-Number"), which results from invalid operations like parsing non-numeric strings.
Conversion functions:
parseInt("42"); // Returns 42
parseInt("42px"); // Returns 42
parseInt("abc"); // Returns NaN
parseFloat("3.14"); // Returns 3.14
String Handling
Strings are sequences of characters defined with single, double, or backtick quotes. Template literals (using backticks) allow embedding expressions:
const userName = "Alice";
const greeting = `Hello, ${userName}!`; // Interpolation
console.log(greeting); // Output: Hello, Alice!
const multiLineText = `
Line one
Line two
`;
Common string methods:
.length: Get character count..trim(): Remove whitespace from both ends..charAt(index): Retrieve character at position..indexOf(substring): Find first occurence index..substring(start, end): Extract substring (end not included)..slice(): Similar tosubstring, supports negative indices..split(delimiter): Convert string into array.
Boolean Logic
Booleans represent truth values: true and false (always lowercase). The following values evaluate to false in conditional contexts:
false0- Empty string
"" nullundefinedNaN
Null vs Undefined
- null: Intentional absence of any object value. Type is
object, often used to reset variable values. - undefined: Default value for uninitialized variables or missing function returns. Type is
undefined.
Arrays
Arrays are ordered collections created with square brackets. Though technically objects, they provide list-like functionality:
const items = [10, 20, 30];
items.push(40); // Adds to end, returns new length
items.pop(); // Removes last element, returns it
items.unshift(5); // Adds to beginning
items.shift(); // Removes first element
items.join("-"); // Joins elements into a string
Iterating over arrays:
items.forEach((element, index, array) => {
console.log(`Index ${index}: ${element}`);
});
The splice() method modifies arrays by removing, replacing, or inserting elements:
items.splice(1, 1, 99); // At index 1, remove 1 item, insert 99
Operators
Increment Operators
i++: Post-increment — use current value, then increment.++i: Pre-increment — increment first, then use new value.
Equality Comparisons
==: Loose equality — performs type coercion before comparison.===: Strict equality — checks both value and type.!=and!==: Their respective inequality counterparts.
Logical Operators
&&: Logical AND||: Logical OR!: Logical NOT
Control Flow Structures
If-Else Statements
const temperature = 25;
if (temperature > 30) {
console.log("It's hot outside.");
} else if (temperature > 20) {
console.log("Nice weather today.");
} else {
console.log("It's getting cold.");
}
Switch Statement
const dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Another day");
}
For Loops
const numbers = [1, 2, 3];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Ternary Operator
A concise way to write simple conditionals:
const score = 85;
const result = score >= 60 ? "Pass" : "Fail";
console.log(result); // Outputs: Pass
Functions in JavaScript
Functions can be defined using function declarations or arrow syntax:
function validateArgs(a, b) {
if (arguments.length === 2) {
console.log("Correct number of arguments:", a, b);
} else if (arguments.length > 2) {
console.log("Too many arguments provided");
} else {
console.log("Too few arguments provided");
}
}
validateArgs(1, 2); // Correct number of arguments: 1 2
validateArgs(1); // Too few arguments provided
validateArgs(1, 2, 3); // Too many arguments provided
Immediately Invoked Function Expressions (IIFE)
Functions that run as soon as they're defined:
(function(x, y) {
console.log(x + y);
})(10, 20); // Immediately logs: 30
Arrow Functions
Concise syntax for writing functions, especially useful in callbacks:
const multiply = (x, y) => x * y;
console.log(multiply(6, 7)); // 42
// Equivalent traditional function
const multiplyLegacy = function(x, y) {
return x * y;
};
Built-in Objects
Custom Objects
Objects group related data and behaviors using key-value pairs:
const user = { name: "Bob", age: 30 };
// Access properties
console.log(user.name); // Bob
// Iterate through keys
for (const key in user) {
console.log(key, user[key]);
}
Alternatively, create objects using constructor syntax:
const person = new Object();
person.firstName = "Carol";
person.lastName = "Smith";
Date Object
Handle dates and times:
const now = new Date();
console.log(now.toLocaleString()); // e.g., 11/17/2019, 1:35:02 PM
console.log(now.getMonth()); // 0–11 (0 = January)
console.log(now.getDay()); // 0–6 (0 = Sunday)
JSON Utilities
Convert between JavaScript objects and JSON strings:
const obj = { username: "Dave", active: true };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"username":"Dave","active":true}
const parsedObj = JSON.parse(jsonString);
console.log(parsedObj.username); // Dave
Regular Expression Support
Create regex patterns using literal or constructor syntax:
const pattern1 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/;
const pattern2 = new RegExp("^[a-zA-Z][a-zA-Z0-9]{5,9}$");
// Test matching
console.log(pattern1.test("user123")); // true
// Global flag example
const globalPattern = /test/g;
globalPattern.test("test string"); // true
console.log(globalPattern.lastIndex); // 4
globalPattern.test("test string"); // false (resumes from lastIndex)