Fundamentals of JavaScript: Syntax, Objects, and DOM Interaction

Historical Background

  • In 1992, Nombas developed an embedded scripting language called C-minus-minus (C--), later renamed ScriptEase, designed to run within the CEnvi environment.
  • Netscape adopted this concept and tasked Brendan Eich with creating a scripting language called LiveScript for Netscape Navigator 2.0. It was later renamed JavaScript through a collaboration with Sun Microsystems.
  • Microsoft introduced JScript, a JavaScript clone, in Internet Explorer 3.0.
  • To standardize the language, ECMA (European Computer Manufacturers Association) defined the ECMA-262 specification. ISO/IEC also adopted it as ISO/IEC-16262. EcmaScript is the standardized specification, while JavaScript is the most common implementation.

Core Components

A complete JavaScript implementation consists of three parts:

  • ECMAScript: The core language specification (syntax, types, statements).
  • DOM (Document Object Model): The interface for interacting with HTML and CSS.
  • BOM (Browser Object Model): The interface for interacting with the browser window.

JavaScript is predominantly object-based and supports object-oriented programming paradigms like encapsulation, inheritance, and polymorphism.

Getting Started

Embedding Scripts

You can include JavaScript directly in HTML or link to an external file.

<!-- Inline script -->
<script>
    console.log('Welcome to JS');
</script>

<!-- External file -->
<script src="main.js"></script>

Variables and Identifiers

Variables in JavaScript do not require explicit type declarations. Use the var, let, or const keywords.

// Basic assignment
var score = 95;
var total = score + 5;

// Multiple declarations
var userName = "Alice", level = 10, role = "Admin";

If you omit the keyword (e.g., x = 10), the variable becomes global implicitly. Identifiers must start with a letter, _, or $, followed by alphanumeric characters.

Naming Conventions:

  • camelCase: myVariableName
  • PascalCase: MyVariableName
  • Hungarian Notation: sName (string), iCount (integer)

Constants

Values that appear directly in the code, such as 100, "hello", or true.

Data Types

Type Description
number Numeric values (e.g., 10, 3.14)
string Textual data (e.g., 'abc', "def")
boolean Logical values: true or false
undefined Variable declared but not initialized
null Intentional absence of any object value

Number

All numbers are stored as 64-bit floating-point values. This includes integers and decimals. Special values include Infinity, -Infinity, and NaN (Not-a-Number).

var intVal = 100;
var floatVal = 20.5;
var hex = 0xFF; // 255
var oct = 0o77; // 63

String

Strings are sequences of Unicode characters. They can be defined using single or double quotes.

var greeting = "Hello World";
var quote = 'He said, "Hi!"';

Escape sequences: \n (newline), \' (single quote), \" (double quote), \\ (backslash).

Boolean

Used heavily in control flow.

if (isActive) {
    performAction();
}

Undefined vs Null

  • undefined means a variable has been declared but hasn't been assigned a value.
  • null is an assignment value representing no value.
var a;
console.log(a); // undefined

var b = null;
console.log(b); // null

Operators

Arithmetic

+, -, *, /, %, ++, --

var counter = 10;
console.log(counter++); // 10 (returns old value)
console.log(++counter); // 12 (returns new value)

Type Coercion: JavaScript is weakly typed.

var result = "5" + 2; // "52" (string concatenation)
var diff = "5" - 2;   // 3 (numeric conversion)

NaN: Results from invalid numeric operations.

var x = +"abc";
console.log(x); // NaN
console.log(typeof x); // "number"

Comparison

>, >=, <, <=, ==, !=, ===, !==

  • == (Loose equality): Performs type conversion.
  • === (Strict equality): No type conversion.
console.log(5 == "5");  // true
console.log(5 === "5"); // false

When comparing strings, comparison is based on lexicographical order (char codes). When comparing a string and a number, the string is converted to a number.

Logical

&& (AND), || (OR), ! (NOT)

// Short-circuit evaluation
var val = 0 || "default"; // "default"
var num = 10 && 20;       // 20

Assignment

=, +=, -=, *=, /=

Control Flow

Conditionals

If/Else:

var temp = 30;
if (temp > 35) {
    console.log("Hot");
} else if (temp > 20) {
    console.log("Moderate");
} else {
    console.log("Cold");
}

Switch:

var day = 3;
switch (day) {
    case 1: console.log("Mon"); break;
    case 2: console.log("Tue"); break;
    case 3: console.log("Wed"); break;
    default: console.log("Unknown");
}

Loops

For Loop:

for (var i = 0; i < 5; i++) {
    console.log(i);
}

For...in (Iterating properties):

var user = { name: "Bob", age: 25 };
for (var key in user) {
    console.log(key + ": " + user[key]);
}

While Loop:

var count = 0;
while (count < 3) {
    console.log(count);
    count++;
}

Exception Handling

try {
    throw new Error("Something went wrong");
} catch (err) {
    console.log(err.message);
} finally {
    console.log("Cleanup done");
}

Built-in Objects

String Object

var msg = "  Hello World  ";
console.log(msg.length);          // 16
console.log(msg.trim());          // "Hello World"
console.log(msg.toUpperCase());   // "  HELLO WORLD  "
console.log(msg.indexOf("World")); // 7
console.log(msg.slice(2, 7));     // "Hello"
console.log(msg.replace("World", "JS")); // "  Hello JS  "

Array Object

Arrays can hold mixed types and resize dynamically.

var colors = ["Red", "Green", "Blue"];
colors.push("Yellow");
console.log(colors.length); // 4

// Sorting
var nums = [10, 1, 5];
nums.sort(function(a, b) { return a - b; }); // [1, 5, 10]

// Slicing
var sub = nums.slice(0, 2); // [1, 5]

// Joining
var text = colors.join(" - "); // "Red - Green - Blue - Yellow"

Date Object

var now = new Date();
console.log(now.getFullYear());
console.log(now.getMonth() + 1); // Months are 0-indexed
console.log(now.getDate());

// Formatting
function formatDate(d) {
    var y = d.getFullYear();
    var m = String(d.getMonth() + 1).padStart(2, '0');
    var day = String(d.getDate()).padStart(2, '0');
    return y + "-" + m + "-" + day;
}

Math Object

console.log(Math.round(4.7));      // 5
console.log(Math.floor(4.7));      // 4
console.log(Math.random());        // 0.0 to 1.0
console.log(Math.max(10, 20, 5));   // 20
console.log(Math.pow(2, 3));       // 8

Function Object

Functions are first-class objects.

// Declaration
function sum(a, b) {
    return a + b;
}

// Expression
var multiply = function(a, b) {
    return a * b;
};

// Invocation
console.log(sum(5, 3));

Arguments Object:

function addAll() {
    var total = 0;
    for (var i = 0; i < arguments.length; i++) {
        total += arguments[i];
    }
    return total;
}
console.log(addAll(1, 2, 3, 4)); // 10

Anonymous Functions:

(function(msg) {
    console.log(msg);
})("Immediate execution");

Browser Interaction (BOM)

The window object represents the browser window.

// Alerts and Confirmations
alert("This is a message");
var confirmed = confirm("Are you sure?");
var input = prompt("Enter your name:", "Guest");

// Timers
setInterval(function() {
    console.log("Tick");
}, 1000);

var timer = setTimeout(function() {
    console.log("Delay finished");
}, 2000);
clearTimeout(timer);

Document Object Model (DOM)

Selecting Elements

var mainDiv = document.getElementById("main");
var paragraphs = document.getElementsByTagName("p");
var items = document.getElementsByClassName("list-item");

Traversing Nodes

var parent = mainDiv.parentElement;
var kids = mainDiv.children;
var first = mainDiv.firstElementChild;
var next = first.nextElementSibling;

Manipulating Nodes

// Create
var newPara = document.createElement("p");
newPara.innerText = "New Paragraph";

// Append
mainDiv.appendChild(newPara);

// Attributes
newPara.setAttribute("class", "highlight");
console.log(newPara.getAttribute("class"));

// Style
newPara.style.color = "blue";
newPara.classList.add("active");

// Remove
mainDiv.removeChild(newPara);

Event Handling

var btn = document.getElementById("submitBtn");

// Method 1: Attribute
// <button onclick="handleClick()">Click</button>

// Method 2: Property
btn.onclick = function() {
    console.log("Button clicked");
};

// Preventing default behavior (e.g., form submission)
var form = document.getElementById("myForm");
form.onsubmit = function(event) {
    event.preventDefault();
    console.log("Form submission blocked");
};

Scope and Hoisting

Global Scope

Variables defined outside any function or without var/let/const.

var globalVar = "I am everywhere";
function test() {
    console.log(globalVar);
}

Local Scope

Variables defined inside a function.

function localTest() {
    var localVar = "I am hidden";
    console.log(localVar);
}
// console.log(localVar); // Error

Hoisting

Variable and function declarations are moved to the top of their scope during the compilation phase.

console.log(myFunc); // ƒ myFunc() { ... }
function myFunc() {
    return "Hello";
}

console.log(myVar); // undefined
var myVar = 10;

Scope Chain Example

var outer = "Outer";
function wrapper() {
    var inner = "Inner";
    console.log(outer); // Accesses parent scope
    function nested() {
        console.log(inner); // Accesses grandparent scope
    }
    nested();
}
wrapper();

Tags: javascript Frontend Development DOM Web Programming ecmascript

Posted on Tue, 22 Sep 2026 16:30:02 +0000 by shmeeg