Core Syntax Fundamentals of JavaScript Programming
Overview of JavaScript
JavaScript is a client-side language executed in browsers, enabling interactive experiences. It supports web effects, form validation, front-end rendering of back-end data, and server-side development via Node.js.
The language consists of:
- ECMAScript: Core syntax and features.
- Web APIs:
- DOM: Menipulate page elements (move, resize, add, remove).
- BOM: Control browser actions (dialogs, viewport size, storage).
Placement of JavaScript Code
Scripts can be embedded in HTML within <script> tags placed in the <head> or before </body>. External files may also be linked via src attribute.
Input and Output Mechanisms
- Input:
prompt()displays a dialog for user entry. - Output:
alert(): Shows a modal message; HTML tags are rendered as text.document.write(): Writes directly into the document stream.console.log(): Outputs to browser developer tools for debugging.
Literals
Literals represent fixed values in code:
- Numeric:
1000 - String:
'engineer' - Array:
[] - Object:
{}
Variables: var vs let
Variables act as containers for data.
Declaration
let workerName;
let enforces block scope and disallows redeclaration.
Initialization and Assignment
let workerName = 'engineer';
workerName = 'coder'; // reassignment
let role = 'tester', level = 2; // multiple declarations
Naming Rules
- No reserved keywords.
- Allowed characters: letters, digits,
_,$; digit cannot lead. - Case-sensitive (
Age≠age).
Conventions
- Use meaningful identifiers.
- Apply camelCase: first word lowercase, subsequent words capitalized (
employeeId).
Arrays
Declaration
const items = [];
Access
Retrieve by index: items[0].
Data Types
JavaScript types fall into two categories: primitive and reference.
Number
Represents integers and floats. Arithmetic follows IEEE 754 standard.
String
Delimited by matching single or double quotes; nesting requires opposite styles. Escape sequences (\) handle special characters.
Concatenation:
const part1 = 'Hello';
const part2 = 'World';
console.log(part1 + ' ' + part2);
Template literals:
const userName = 'Alex';
console.log(`User: ${userName}`);
Type Detection
Use typeof:
console.log(typeof someVar);
Type Conversion
Implicit Conversion
Occurs automatically during operations:
+with a string converts the other operand to string.-,*,/coerce operands to numbers.- Unary
+casts to number.
console.log(12 + '12'); // "1212"
console.log('12' - 12); // 0
console.log(+'99' + 1); // 100
Explicit Conversion
Ensures predictable results.
console.log(Number('45.67')); // 45.67
console.log(Number('45.67abc')); // NaN
console.log(parseInt('45.99px')); // 45
console.log(parseFloat('45.99')); // 45.99
let strNum = String(321);
console.log(typeof strNum); // "string"
Operators
Include arithmetic (+, -), assignment (=, +=), unary (++, --), comparison (===, !==), logical (&&, ||), with defined precedence.
Control Flow
Three structures: sequential, conditional, iterative.
Conditionals
if,if-else,if-else-ifchains.- Ternary:
condition ? expr1 : expr2. switch: compares using strict equality.
Loops
while: condition-controlled iteration.for: initailization, condition, increment.- Nested loops for multi-dimensional traversal.
Loop Controls
continue: skip current iteration.break: exit loop entirely.return: exit function with value.
Array Operations
Iteration
const data = [3, 1, 4];
for (let i = 0; i < data.length; i++) {
console.log(data[i]);
}
Modification
- Add:
push(item): append to end, returns new length.unshift(item): prepend, returns new length.
- Remove:
pop(): remove last element.shift(): remove first element.splice(start, count): remove from index.
Bubble Sort Example
Repeatedly swap adjacent misordered items:
function bubble(arr) {
const len = arr.length;
for (let i = 0; i < len - 1; i++) {
for (let j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
console.log(bubble([2, 3, 1, 4, 5])); // [1,2,3,4,5]
Functions
Functions execute only when invoked. Variable hoisting applies to declarations.
Scope
Local variables shadow outer ones; undeclared assignments inside functions become global (not recommended). Function parameters are local.
Anonymous Functions
Assigned to identifiers:
const greet = function() { console.log('hello'); };
greet();
Constructors
Define object blueprints:
function Person(id, years) {
this.id = id;
this.years = years;
this.describe = () => console.log(`${this.id}, age ${this.years}`);
}
const p1 = new Person('P01', 30);
p1.describe();
Objects
Creation
- Literal:
const person = {
name: 'Lee',
age: 28,
hi: function() { console.log('hey'); }
};
new Object():
const personA = new Object();
personA.name = 'Lee';
personA.hi = () => console.log('hey');
- Constructor: see previous section.
Access
Dot notation (person.name) or bracket notation (person['name']).
Mutation
Add or override properties/methods direct:
person.role = 'dev';
person.hi = () => console.log('hello');
Iteration
for (let key in person) {
console.log(key, person[key]);
}
Built-in Objects
Examples: Math for mathematical constants and methods (Math.random(), Math.floor()).