JavaScript Fundamentals
Understanding JavaScript Execution in Browsers
Modern web browsers consist of two primary components:
- Rendering Engine: Responsible for parsing HTML and CSS, commonly known as the browser kernel. For example, Chrome uses Blink.
- JavaScript Engine: Also known as a JS interpreter, it reads JavaScript code and processes it in the background. Chrome uses V8.
JavaScript Components
- ECMAScript: Defines JavaScript syntax, core programming concepts, and standards followed by all browser vendors.
- DOM (Document Object Model): Provides interfaces to manipulate page elements (size, position, color, etc.).
- BOM (Browser Object Model): Enables interaction with browser windows.
JavaScript Implementation Methods
- Inline JavaScript: Used in specific scenarios. Single quotes are recommended.
- Embedded JavaScript: Commonly used during learning and development.
- External JavaScript: Suitable for larger codebases.
External JavaScript Example
<script src="./scripts/main.js"></script>
<!-- No code allowed between script tags -->
Input and Output Methods
prompt(): Displays a dialog with an optional message prompting the user for input.alert(): Shows an alert dialog with a specified message.console.log(): Outputs messages to the browser's console.
Variables in JavaScript
// Variable declaration
var identifier;
// Assignment
identifier = value;
// Declaration and initialization
var identifier = value;
Variable Declaration Best Practices
- Declared but uninitialized variables return
undefined. - Using variables without declaration works but is discouraged.
- Assignment without declaration works but is not recommended.
Variable Naming Conventions
- Can contain letters, numbers, underscores, and dollar signs.
- Case-sensitive.
- Cannot start with a number.
- Cannot be keywords.
- Must be meaningful.
- Follow camelCase naming (first letter lowercase, subsequent words capitalized).
- Avoid using
nameas a variable name.
Data Types
JavaScript is dynamically typed - a variable's type is determined by the value assigned to it at runtime.
Simple Data Types
- Number: Includes integers and floats (default: 0).
- String: Text data (default:
""). - Boolean: Logical values (default:
false). - Undefined: Variable declared without a value.
- Null: Represents no value.
Number Type
- Octal: Prefix with 0 (e.g.,
var octal = 077;). - Hexadecimal: Prefix with 0x (e.g.,
var hex = 0xFF;). - Special values:
Infinity,-Infinity,NaN. isNaN(): Checks if a value is NaN (returnstruefor non-numbers).
String Type
- Escape sequences:
\n(newline),\\(backslash),\'(single quote),\"(double quote),\t(tab),\b(backspace). - String concatenation using
+operator. - String length:
string.length.
Boolean Type
When used in arithmetic operations, true is treated as 1 and false as 0.
Type Checking
var value = 42;
console.log(typeof value); // "number"
var empty = null;
console.log(typeof empty); // "object" (historical JavaScript quirk)
Type Conversion
Converting to String
toString()method.String()function.- String concatenation (implicit conversion).
Converting to Number
parseInt(): Converts to integer.parseFloat(): Converts to float.Number(): Strict conversion.- Arithmetic operations (implicit conversion).
Converting to Boolean
Boolean()function.- Falsy values:
"",0,NaN,null,undefined. - All other values are truthy.
Operators
Arithmetic Operators
- Basic operations:
+,-,*,/,%(modulo). - Floating-point precision issues: Avoid direct comparison of floats.
Increment and Decrement Operators
- Prefix:
++variable(increments before use). - Postfix:
variable++(uses then increments).
Comparison Operators
==: Loose equality (type conversion).===: Strict equality (no type conversion).- Other:
!=,!==,>,>=,<,<=.
Logical Operators
&&(AND): Both expressions must be true.||(OR): At least one expression must be true.!(NOT): Inverts the boolean value.
Short-circuit Evaluation
&&: If first expression is false, returns it without evaluating the second.||: If first expression is true, returns it without evaluating the second.
Assignment Operators
- Basic:
= - Compound:
+=,-=,*=,/=,%=
Flow Control
If-Else Statements
if (condition) {
// Code to execute if condition is true
} else if (anotherCondition) {
// Code to execute if anotherCondition is true
} else {
// Code to execute if all conditions are false
}
Switch Statements
switch (expression) {
case value1:
// Code to execute if expression === value1
break;
case value2:
// Code to execute if expression === value2
break;
default:
// Code to execute if no cases match
}
Ternary Operator
condition ? valueIfTrue : valueIfFalse;
Loops
For Loop
for (initialization; condition; increment) {
// Code to execute repeatedly
}
While Loop
while (condition) {
// Code to execute while condition is true
}
Do-While Loop
<ndo>do {
// Code to execute at least once
} while (condition);
Loop Control
break: Exits the current loop.continue: Skips to the next iteration of the loop.
Arrays
Creating Arrays
// Using constructor
var array1 = new Array();
// Using literal notation
var array2 = [];
// With initial values
var array3 = [1, 2, 3, 4];
Accessing Array Elements
var firstElement = array3[0]; // Array indices start at 0
Modifying Arrays
// Change length
array3.length = 7;
// Modify elements by index
array3[4] = "new value";
// Add elements at specific positions
array3[6] = "another value";
Array Methods
array.push(): Adds elements to the end.array.pop(): Removes the last element.array.shift(): Removes the first element.array.unshift(): Adds elements to the beginning.array.slice(): Extracts a section of an array.array.splice(): Adds/removes elements at any position.
Array Sorting
var numbers = [3, 1, 4, 1, 5, 9, 2, 6];
numbers.sort(function(a, b) {
return a - b; // Ascending order
});
console.log(numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
Functions
Function Declaration
function functionName(parameter1, parameter2) {
// Function body
return result;
}
Function Expression
var functionName = function(parameter1, parameter2) {
// Function body
return result;
};
Arrow Functions (ES6)
var functionName = (parameter1, parameter2) => {
// Function body
return result;
};
// Concise syntax for single-expression functions
var multiply = (a, b) => a * b;
Function Parameters and Return Values
- Functions can have multiple parameters.
- Functions can return a single value using
return. - If no
returnstatement, the function returnsundefined. - Arguments can be passed as objects or arrays for multiple values.
Function Scope
- Variables declared inside functions are local to those functions.
- Functions can access variables in their outer scope (closures).
thisrefers to the object the function is a method of, or the global object in strict mode.