JavaScript Explained
1. Introduction
1.1 What is JavaScript?
JavaScript is a high-level, interpreted programming language that conforms to the ECMAScript specification. JavaScript has curly-bracket syntax, dynamic typing, prototype-based object-orientation, and first-class functions.
Alongside HTML and CSS, JavaScript is one of the core technologies of the World Wide Web. JavaScript enables interactive web pages and is an essential part of web applications. The vast majority of websites use it for client-side page behavior, and all major web browsers have a dedicated JavaScript engine to execute it.
As a multi-paradigm language, JavaScript supports event-driven, functional, and imperative programming styles. It has application programming interfaces (APIs) for working with text, dates, regular expressions, standard data structures, and the Document Object Model (DOM).
1.2 Data Types
JavaScript has several built-in data types that are used to define the operations possible on them and the storage method for each of them. The most fundamental data types in JavaScript include:
The basic data types in JavaScript are:
- Number: Integers and floating-point numbers (e.g., 3, 3.14)
- String: Text enclosed in quotes (e.g., "Hello", 'JavaScript')
- Boolean: true or false values
- Undefined: A variable that has been declared but not assigned a value
- Null: Represents the intentional absence of any object value
- Symbol: A unique and immutable primitive value (ES6)
- BigInt: For integers of arbitrary length (ES2020)
- Object: Collections of related data
JavaScript is dynamically typed, which means you don't need to declare the type of a variable when you create it. The interpreter automatically determines the type based on the assigned value.
Examples of basic data types in JavaScript:
// JavaScript Data Types
let age = 25; // Number
let name = "Alice"; // String
let isStudent = true; // Boolean
let job = undefined; // Undefined
let salary = null; // Null
let id = Symbol("id"); // Symbol
let bigNumber = 1234567890123456789012345n; // BigInt
let person = { // Object
firstName: "John",
lastName: "Doe"
};
// Checking types
console.log(typeof age); // "number"
console.log(typeof name); // "string"
console.log(typeof isStudent); // "boolean"
console.log(typeof job); // "undefined"
console.log(typeof salary); // "object" (this is a known quirk in JavaScript)
console.log(typeof id); // "symbol"
console.log(typeof bigNumber); // "bigint"
console.log(typeof person); // "object"
1.3 Variables
In JavaScript, variables are containers for storing data values. There are three ways to declare variables in JavaScript:
// Using var (function-scoped, older way)
var x = 10;
// Using let (block-scoped, introduced in ES6)
let y = 20;
// Using const (block-scoped, constant value, introduced in ES6)
const z = 30;
// Variable naming rules
let camelCase = "This is the standard naming convention";
let _privateVariable = "Starting with underscore is common for private variables";
let $specialVariable = "Dollar sign is allowed";
// Variables can change type in JavaScript
let variable = 10; // Number
variable = "ten"; // Now it's a String
variable = true; // Now it's a Boolean
// Multiple declarations
let a = 1, b = 2, c = 3;
Key differences between var, let, and const:
- var: Function-scoped, can be redeclared, hoisted
- let: Block-scoped, cannot be redeclared in the same scope, not hoisted
- const: Block-scoped, cannot be reassigned after declaration, not hoisted
1.4 Constants
Constants in JavaScript are declared using the const keyword. Once a constant is assigned a value, it cannot be reassigned. However, if the constant is an object or array, its properties or elements can still be modified.
// Declaring constants
const PI = 3.14159;
const MAX_USERS = 100;
// This will cause an error
// PI = 3.14; // TypeError: Assignment to constant variable
// However, for objects and arrays, the content can be modified
const person = {
name: "John",
age: 30
};
// This is allowed
person.age = 31;
console.log(person); // { name: "John", age: 31 }
// But this is not allowed
// person = { name: "Jane", age: 25 }; // TypeError: Assignment to constant variable
// Same for arrays
const numbers = [1, 2, 3];
numbers.push(4); // This is allowed
console.log(numbers); // [1, 2, 3, 4]
// But this is not allowed
// numbers = [5, 6, 7]; // TypeError: Assignment to constant variable
1.5 Key Takeaways
JavaScript is a versatile language with dynamic typing and multiple ways to declare variables. The following table summarizes the key concepts covered in this introduction:
| Concept | Description | Example |
|---|---|---|
| Data Types | JavaScript has 8 basic data types | number, string, boolean, null, undefined, symbol, bigint, object |
| Variable Declaration | Three ways to declare variables | var x = 10; let y = 20; const z = 30; |
| Dynamic Typing | Variables can change types | let x = 10; x = "hello"; |
| Constants | Values that cannot be reassigned | const PI = 3.14159; |
| Object Mutability | Object properties can be changed even when declared with const | const obj = {}; obj.prop = "value"; |
| Type Checking | Use typeof operator to check types | typeof "hello" // "string" |
Understanding these fundamental concepts is crucial for mastering JavaScript. As you progress through this guide, you'll build on these basics to create more complex and powerful applications.
2. Basic Concepts
2.1 Basic Structure of JavaScript
JavaScript can be included in HTML documents in several ways:
- Inline JavaScript - Directly in HTML elements using event attributes
- Internal JavaScript - Using the <script> tag in the HTML document
- External JavaScript - Linking to external .js files
- Modern JavaScript - Using modules with import/export statements
Example: Writing Basic JavaScript
// External JavaScript file (script.js)
// 1. Variables and values
let greeting = "Hello, World!";
// 2. Functions
function displayGreeting() {
console.log(greeting);
}
// 3. Event handling (when included in HTML)
document.addEventListener("DOMContentLoaded", function() {
displayGreeting();
document.getElementById("demo").innerHTML = greeting;
});
How to include JavaScript in HTML:
<!-- Inline JavaScript -->
<button onclick="alert('Hello!')">Click Me</button>
<!-- Internal JavaScript -->
<script>
console.log("This is internal JavaScript");
</script>
<!-- External JavaScript -->
<script src="script.js"></script>
<!-- Modern JavaScript with type="module" -->
<script type="module" src="app.js"></script>
2.2 Variables and Data Types in JavaScript
JavaScript has several data types that can be stored in variables. Understanding these types is essential for effective programming.
Common Data Types in JavaScript:
| Data Type | Example | Description |
|---|---|---|
Number |
let age = 25; |
Integers and floating-point numbers |
String |
let name = "John"; |
Text enclosed in quotes |
Boolean |
let isActive = true; |
true or false values |
Object |
let person = {name: "John", age: 30}; |
Collection of key-value pairs |
Array |
let colors = ["red", "green", "blue"]; |
Ordered collection of values |
Null |
let empty = null; |
Intentional absence of any value |
Undefined |
let notDefined; |
Variable declared but not assigned a value |
Working with variables and data types:
// Variable declarations
let name = "John";
let age = 30;
let isEmployed = true;
let hobbies = ["reading", "gaming", "coding"];
let person = {
firstName: "John",
lastName: "Doe",
email: "john@example.com"
};
// Accessing and manipulating variables
console.log(name); // "John"
console.log(age + 5); // 35
console.log(hobbies[1]); // "gaming"
console.log(person.firstName); // "John"
// Type conversion
let numStr = "42";
let num = Number(numStr); // Convert string to number
let str = String(num); // Convert number to string
let bool = Boolean(num); // Convert to boolean (0 is false, other numbers are true)
// Checking types
console.log(typeof name); // "string"
console.log(typeof age); // "number"
console.log(typeof isEmployed); // "boolean"
console.log(typeof hobbies); // "object" (arrays are objects in JavaScript)
console.log(Array.isArray(hobbies)); // true (specific check for arrays)
2.3 Operators in JavaScript
JavaScript includes arithmetic, comparison, logical, and assignment operators for performing operations on variables.
| Operator | Example | Description |
|---|---|---|
+ |
x + y |
Addition (also used for string concatenation) |
- |
x - y |
Subtraction |
* |
x * y |
Multiplication |
/ |
x / y |
Division |
% |
x % y |
Modulus (Remainder) |
** |
x ** y |
Exponentiation (ES2016) |
== |
x == y |
Equal to (value) |
=== |
x === y |
Equal to (value and type) |
!= |
x != y |
Not equal to (value) |
!== |
x !== y |
Not equal to (value and type) |
&& |
x && y |
Logical AND |
|| |
x || y |
Logical OR |
! |
!x |
Logical NOT |
Example: Using Operators in JavaScript
// Arithmetic operators
let a = 10, b = 5;
console.log("Sum: " + (a + b)); // 15
console.log("Difference: " + (a - b)); // 5
console.log("Product: " + (a * b)); // 50
console.log("Quotient: " + (a / b)); // 2
console.log("Remainder: " + (a % b)); // 0
console.log("Power: " + (a ** b)); // 100000 (10^5)
// Comparison operators
console.log(a == "10"); // true (equal value)
console.log(a === "10"); // false (not equal type)
console.log(a != b); // true
console.log(a > b); // true
console.log(a <= b); // false
// Logical operators
let isAdult = true;
let hasLicense = false;
console.log(isAdult && hasLicense); // false (both must be true)
console.log(isAdult || hasLicense); // true (at least one is true)
console.log(!isAdult); // false (negation)
// Assignment operators
let x = 10;
x += 5; // x = x + 5
console.log(x); // 15
x *= 2; // x = x * 2
console.log(x); // 30
2.4 Conditional Statements in JavaScript
JavaScript provides if, else, and switch statements to control the flow of execution.
1. if Statement
Executes a block of code if the condition is true.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
2. if-else Statement
Executes one block if true, another if false.
let num = 10;
if (num % 2 === 0) {
console.log("Even number");
} else {
console.log("Odd number");
}
3. if-else if-else Statement
Checks multiple conditions in sequence.
let score = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
4. switch Statement
Used when you have multiple conditions for a single variable.
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log("Today is " + dayName);
5. Ternary Operator
A shorthand for simple if-else statements.
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // "Adult"
6. Loops in JavaScript
Loops are used to execute a block of code multiple times.
6.1 for Loop
Executes code a fixed number of times.
for (let i = 1; i <= 5; i++) {
console.log("Iteration: " + i);
}
6.2 while Loop
Executes code while a condition is true.
let i = 1;
while (i <= 5) {
console.log("Iteration: " + i);
i++;
}
6.3 do-while Loop
Executes code at least once, then repeats while the condition is true.
let i = 1;
do {
console.log("Iteration: " + i);
i++;
} while (i <= 5);
6.4 for...of Loop
Iterates over iterable objects like arrays.
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log(color);
}
6.5 for...in Loop
Iterates over the properties of an object.
let person = {name: "John", age: 30, job: "Developer"};
for (let key in person) {
console.log(key + ": " + person[key]);
}
3. Functions
3.1 Functions
Functions in JavaScript are blocks of code designed to perform a particular task. They are executed when they are called (invoked).
// Function declaration
function greet(name) {
console.log("Hello, " + name + "!");
}
// Function call
greet("Alice"); // Output: Hello, Alice!
3.2 Function Parameters
Functions can take parameters, which are values passed to the function when it is called.
// Function with multiple parameters
function addNumbers(a, b) {
return a + b;
}
// Function call with arguments
let sum = addNumbers(5, 3); // sum = 8
console.log(sum);
// Parameters vs. Arguments
// - Parameters: Variables listed in function definition (a, b)
// - Arguments: Actual values passed to the function (5, 3)
3.3 Function Calls
Functions are called (invoked) using the function name followed by parentheses containing any arguments.
// Defining a function to calculate area
function calculateArea(width, height) {
return width * height;
}
// Different ways to call functions
let area1 = calculateArea(5, 10); // Direct values
console.log(area1); // 50
let width = 6, height = 8;
let area2 = calculateArea(width, height); // Variables as arguments
console.log(area2); // 48
// Using function results in expressions
let totalArea = calculateArea(5, 10) + calculateArea(6, 8);
console.log(totalArea); // 98
// Nested function calls
let radius = 5;
let circleArea = calculateArea(radius, radius) * Math.PI;
console.log(circleArea.toFixed(2)); // 78.54
Function calls can be used in expressions, assigned to variables, passed as arguments to other functions, and more. This flexibility is a powerful feature of JavaScript.
3.4 Types of Functions
JavaScript supports several ways to define and use functions.
// 1. Function Declaration
function sayHello() {
console.log("Hello!");
}
// 2. Function Expression
const greet = function() {
console.log("Greetings!");
};
// 3. Arrow Function (ES6)
const welcome = () => {
console.log("Welcome!");
};
// 4. Immediately Invoked Function Expression (IIFE)
(function() {
console.log("This runs immediately!");
})();
// 5. Method (Function as object property)
const person = {
name: "John",
sayName: function() {
console.log(this.name);
}
};
// Calling different types of functions
sayHello(); // Function declaration
greet(); // Function expression
welcome(); // Arrow function
person.sayName(); // Method
3.5 Functions Without Parameters & Return
A function that doesn't take input or return anything.
// Function without parameters or return value
function showMessage() {
console.log("This is a simple message");
}
// Function call
showMessage();
- The function doesn't accept any parameters
- It performs an action (logging to console) but doesn't return a value
- Such functions are useful for tasks that don't need inputs or outputs
3.6 Functions With Return Values
Functions can return values using the return statement.
// Function that returns a value
function calculateArea(width, height) {
return width * height;
}
// Using the returned value
let area = calculateArea(5, 3);
console.log("Area: " + area); // Output: Area: 15
// Early return
function getGreeting(hour) {
if (hour < 12) {
return "Good morning";
} else if (hour < 18) {
return "Good afternoon";
} else {
return "Good evening";
}
}
console.log(getGreeting(9)); // "Good morning"
console.log(getGreeting(14)); // "Good afternoon"
console.log(getGreeting(20)); // "Good evening"
- The return statement ends function execution and specifies a value to be returned
- Functions can have multiple return statements (but only one will execute)
- If no return statement is specified, the function returns undefined
3.7 Default Parameters
ES6 introduced default parameters, allowing parameters to have default values if no argument is provided.
// Function with default parameters
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
// Different ways to call
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
greet("Bob", "Welcome"); // Output: Welcome, Bob!
// Skipping parameters
function createUser(name, role = "User", active = true) {
return {
name: name,
role: role,
isActive: active
};
}
// To skip the middle parameter but provide the third
let user = createUser("Alice", undefined, false);
console.log(user); // {name: "Alice", role: "User", isActive: false}
- Default parameters are used when arguments are undefined or omitted
- They make functions more flexible and reduce the need for conditional logic
- You can use expressions as default values, including function calls
3.8 Arrow Functions
Arrow functions provide a concise syntax for writing functions in JavaScript (introduced in ES6).
// Traditional function expression
const add = function(a, b) {
return a + b;
};
// Arrow function equivalent
const addArrow = (a, b) => {
return a + b;
};
// Even shorter for single expressions (implicit return)
const addShort = (a, b) => a + b;
// Arrow function with single parameter (parentheses optional)
const square = x => x * x;
// Arrow function with no parameters
const sayHello = () => "Hello!";
// Using arrow functions
console.log(addArrow(5, 3)); // 8
console.log(addShort(5, 3)); // 8
console.log(square(4)); // 16
console.log(sayHello()); // "Hello!"
Key differences between arrow functions and regular functions:
- Arrow functions don't have their own this binding
- They cannot be used as constructors (no new keyword)
- They don't have arguments object
- They have implicit return when the body is a single expression
3.9 Function Scope
Variables defined inside a function are not accessible from outside the function. This is known as function scope.
// Global scope
let globalVar = "I'm global";
function exampleFunction() {
// Function scope
let localVar = "I'm local";
console.log(globalVar); // Can access global variables
console.log(localVar); // Can access local variables
// Nested function
function nestedFunction() {
let nestedVar = "I'm nested";
console.log(globalVar); // Can access global variables
console.log(localVar); // Can access parent function variables
console.log(nestedVar); // Can access its own variables
}
nestedFunction();
// console.log(nestedVar); // Error: nestedVar is not defined
}
exampleFunction();
console.log(globalVar); // Works: globalVar is global
// console.log(localVar); // Error: localVar is not defined
// Block scope (let and const)
if (true) {
let blockVar = "I'm in a block";
const FIXED_VALUE = 100;
var oldVar = "I use var";
}
// console.log(blockVar); // Error: blockVar is not defined
// console.log(FIXED_VALUE); // Error: FIXED_VALUE is not defined
console.log(oldVar); // Works: var is function-scoped, not block-scoped
Understanding scope is crucial for writing maintainable JavaScript code and avoiding unexpected behavior.