JavaScript Client-Side Theory - Exam Preparation
1. Introduction to JavaScript
What is JavaScript?
JavaScript is a high-level, interpreted, client-side scripting language primarily used for web
development. It was created by Brendan Eich in 1995 while working at Netscape Communications.
Key Characteristics:
Dynamic Language: Variables don't need explicit type declaration
Interpreted Language: No compilation required, executed by browser's JavaScript engine
Object-Oriented: Supports object-oriented programming paradigms
Event-Driven: Responds to user interactions and browser events
Case-Sensitive: Distinguishes between uppercase and lowercase letters
Platform Independent: Runs on any platform with JavaScript engine
Features of JavaScript:
1. Client-Side Validation: Validates user input before sending to server
2. Dynamic Content: Modifies HTML content without page reload
3. Event Handling: Responds to user actions like clicks, mouse movements
4. DOM Manipulation: Changes HTML elements and their properties
5. Asynchronous Programming: Handles multiple operations simultaneously
How JavaScript Works:
JavaScript code is embedded in HTML documents and executed by the browser's JavaScript engine
when the page loads. It can be included in three ways:
Inline: Directly in HTML elements using event attributes
Internal: Within <script> tags in HTML document
External: In separate .js files linked to HTML
Advantages:
Reduces server load by performing client-side operations
Provides immediate feedback to users
Creates interactive and dynamic web pages
No compilation required
Supports multiple programming paradigms
Disadvantages:
Code is visible to users (security concern)
Browser compatibility issues
Can be disabled by users
Limited file system access for security reasons
2. Objects in JavaScript
Definition:
Objects in JavaScript are collections of key-value pairs where keys are strings (properties) and values
can be any data type including functions (methods).
Object Creation Methods:
1. Object Literal Syntax:
javascript
let person = {
name: "John",
age: 25,
city: "New York",
greet: function() {
return "Hello";
}
};
2. Object Constructor:
javascript
let person = new Object();
person.name = "John";
person.age = 25;
3. Constructor Function:
javascript
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person("John", 25);
Object Properties:
Property Access:
Dot notation: object.property
Bracket notation: object["property"]
Property Addition: object.newProperty = value
Property Deletion: delete object.property
Property Enumeration: for...in loop
Object Methods:
Methods are functions stored as object properties. They can access object properties using the this
keyword.
Built-in Objects:
1. Array: For storing ordered collections
2. Date: For date and time operations
3. Math: For mathematical operations
4. String: For string manipulation
5. Number: For number operations
6. Boolean: For boolean operations
Object Characteristics:
Objects are reference types
Objects are mutable
Objects can contain other objects (nested objects)
Objects can have methods that operate on their data
3. Primitives, Operations and Expressions
Primitive Data Types:
1. Number:
Represents both integers and floating-point numbers
Special values: Infinity , -Infinity , NaN
Example: let num = 42; let pi = 3.14;
2. String:
Sequence of characters enclosed in quotes
Can use single quotes, double quotes, or backticks
Example: let name = "JavaScript"; let message = 'Hello';
3. Boolean:
Represents logical values: true or false
Used in conditional statements
Example: let isActive = true;
4. Undefined:
Variable declared but not assigned a value
Default value for uninitialized variables
Example: let x; // x is undefined
5. Null:
Represents intentional absence of value
Must be explicitly assigned
Example: let data = null;
6. Symbol (ES6):
Unique identifier
Used as object property keys
Example: let sym = Symbol('id');
Operations:
Arithmetic Operations:
Addition: + (also string concatenation)
Subtraction: -
Multiplication: *
Division: /
Modulus: %
Exponentiation: **
Increment: ++
Decrement: --
Comparison Operations:
Equal: == (type coercion)
Strict Equal: === (no type coercion)
Not Equal: !=
Strict Not Equal: !==
Greater than: >
Less than: <
Greater than or equal: >=
Less than or equal: <=
Logical Operations:
AND: &&
OR: ||
NOT: !
Assignment Operations:
Basic Assignment: =
Addition Assignment: +=
Subtraction Assignment: -=
Multiplication Assignment: *=
Division Assignment: /=
Expressions:
An expression is any valid unit of code that resolves to a value.
Types of Expressions:
1. Arithmetic Expressions: 5 + 3 * 2
2. String Expressions: "Hello" + " World"
3. Logical Expressions: true && false
4. Assignment Expressions: x = 10
5. Function Call Expressions: Math.max(1, 2, 3)
Type Conversion:
Implicit Conversion: Automatic type conversion by JavaScript
Explicit Conversion: Manual type conversion using functions
Number() : Convert to number
String() : Convert to string
Boolean() : Convert to boolean
4. Control Statements
Definition:
Control statements determine the flow of program execution based on certain conditions or criteria.
Types of Control Statements:
1. Conditional Statements:
if Statement:
javascript
if (condition) {
// code to execute if condition is true
}
if...else Statement:
javascript
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
if...else if...else Statement:
javascript
if (condition1) {
// code for condition1
} else if (condition2) {
// code for condition2
} else {
// code if no condition is true
}
switch Statement:
javascript
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// default code
}
2. Looping Statements:
for Loop:
javascript
for (initialization; condition; increment) {
// code to repeat
}
while Loop:
javascript
while (condition) {
// code to repeat
}
do...while Loop:
javascript
do {
// code to repeat
} while (condition);
for...in Loop:
javascript
for (variable in object) {
// code to execute for each property
}
for...of Loop:
javascript
for (variable of iterable) {
// code to execute for each element
}
3. Jump Statements:
break Statement:
Terminates the current loop or switch statement
Control transfers to the statement after the terminated statement
continue Statement:
Skips the current iteration of a loop
Control transfers to the next iteration
return Statement:
Exits from a function
Optionally returns a value
Control Statement Characteristics:
Control statements alter the sequential execution of statements
They use conditions to determine which code blocks to execute
Proper use of control statements creates efficient and logical programs
Nested control statements allow complex decision-making logic
5. Arrays
Definition:
Arrays are ordered collections of elements that can store multiple values in a single variable. Each
element has an index starting from 0.
Array Creation:
1. Array Literal:
javascript
let fruits = ["apple", "banana", "orange"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [1, "hello", true, null];
2. Array Constructor:
javascript
let arr = new Array();
let arr2 = new Array(5); // Creates array with 5 empty slots
let arr3 = new Array(1, 2, 3); // Creates [1, 2, 3]
Array Properties:
Length Property:
array.length : Returns the number of elements
Can be modified to change array size
Example: fruits.length returns 3
Array Methods:
Adding Elements:
push(): Adds elements to the end
unshift(): Adds elements to the beginning
splice(): Adds elements at specific position
Removing Elements:
pop(): Removes last element
shift(): Removes first element
splice(): Removes elements from specific position
Searching Elements:
indexOf(): Returns index of first occurrence
lastIndexOf(): Returns index of last occurrence
includes(): Checks if element exists
find(): Returns first element matching condition
Iterating Arrays:
for loop: Traditional iteration
forEach(): Executes function for each element
map(): Creates new array with transformed elements
filter(): Creates new array with elements matching condition
Other Useful Methods:
join(): Converts array to string
slice(): Returns portion of array
concat(): Combines arrays
reverse(): Reverses array order
sort(): Sorts array elements
Multi-dimensional Arrays:
Arrays can contain other arrays, creating multi-dimensional structures:
javascript
let matrix = [[1, 2], [3, 4], [5, 6]];
Array Characteristics:
Arrays are dynamic (size can change)
Elements can be of different data types
Arrays are objects in JavaScript
Array indices start from 0
Arrays have a length property
6. Functions
Definition:
Functions are reusable blocks of code designed to perform specific tasks. They are executed when
called (invoked).
Function Declaration:
javascript
function functionName(parameters) {
// function body
return value; // optional
}
Function Expression:
javascript
let functionName = function(parameters) {
// function body
return value;
};
Arrow Functions (ES6):
javascript
let functionName = (parameters) => {
// function body
return value;
};
// Short form for single expression
let add = (a, b) => a + b;
Function Components:
1. Function Name:
Identifies the function
Used to call the function
Should be descriptive of function's purpose
2. Parameters:
Variables that receive values when function is called
Listed in parentheses after function name
Can have default values: function greet(name = "Guest")
3. Function Body:
Contains the code to be executed
Enclosed in curly braces
Can contain any valid JavaScript statements
4. Return Statement:
Returns a value to the function caller
Optional - functions return undefined if no return statement
Terminates function execution
Function Invocation:
javascript
functionName(arguments);
Types of Functions:
1. Named Functions:
Functions with a specific name that can be called multiple times.
2. Anonymous Functions:
Functions without a name, often used as callbacks or event handlers.
3. Self-Invoking Functions (IIFE):
javascript
(function() {
// code executed immediately
})();
4. Callback Functions:
Functions passed as arguments to other functions.
Function Scope:
Local Scope: Variables declared inside function
Global Scope: Variables declared outside all functions
Function Hoisting: Function declarations are moved to top of scope
Function Characteristics:
Functions are first-class objects in JavaScript
Functions can be assigned to variables
Functions can be passed as arguments
Functions can return other functions
Functions create their own scope
7. Constructors
Definition:
Constructor functions are special functions used to create and initialize objects. They serve as
blueprints for creating multiple objects with similar properties and methods.
Constructor Function Syntax:
javascript
function ConstructorName(parameters) {
this.property1 = value1;
this.property2 = value2;
this.method = function() {
// method body
};
}
Creating Objects with Constructors:
javascript
let objectName = new ConstructorName(arguments);
The 'new' Keyword:
When using the new keyword:
1. Creates a new empty object
2. Sets the constructor's this to the new object
3. Executes the constructor function
4. Returns the new object (unless constructor explicitly returns something else)
The 'this' Keyword:
Refers to the object being created
Used to assign properties and methods to the new object
Context depends on how function is called
Constructor Example:
javascript
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
this.greet = function() {
return "Hello, I'm " + this.name;
};
}
let person1 = new Person("John", 25, "New York");
let person2 = new Person("Jane", 30, "London");
Built-in Constructors:
1. Object Constructor:
javascript
let obj = new Object();
2. Array Constructor:
javascript
let arr = new Array();
3. Function Constructor:
javascript
let func = new Function('a', 'b', 'return a + b');
4. Date Constructor:
javascript
let date = new Date();
Prototype Property:
Every constructor function has a prototype property that allows adding properties and methods to all
instances:
javascript
Person.prototype.nationality = "Unknown";
Person.prototype.getAge = function() {
return this.age;
};
Constructor vs Regular Function:
Constructor: Called with new keyword, creates objects
Regular Function: Called directly, performs operations
Constructor Best Practices:
1. Constructor names should start with capital letter
2. Always use new keyword when calling constructors
3. Use prototype for methods to save memory
4. Validate parameters in constructor
5. Return nothing explicitly (let new handle return)
Advantages of Constructors:
Code reusability
Consistent object structure
Encapsulation of related properties and methods
Easy to create multiple similar objects
Supports inheritance through prototypes
Constructor Characteristics:
Constructors are regular functions called with new
They initialize object properties
They can have parameters for customization
They automatically return the created object
They can be used to implement object-oriented programming concepts