JavaScript

JavaScript is a dynamic, high-level programming language used to make web pages interactive. It runs in the browser and on servers (Node.js). This chapter covers basics: printing, variables, types, conditions, loops, functions, arrays, objects, events, DOM basics, and a final Collatz example. Save JavaScript code in .js files. Examples are shown in code blocks.

Getting started

JavaScript can be added to HTML inline, in a <script> tag, or as an external file. Use the console or alerts for quick output during learning.

Inline script

<script>
  alert("Hello, world!");
</script>

External script

<!-- index.html -->
<script src="script.js"></script>

Output

Common ways to show output: alert(), console.log(), or updating the DOM.

Console

console.log("Hello from the console");

Variables and types

Use let for block-scoped mutable variables, const for constants, and var is the old function-scoped keyword.

Examples

let name = "Alice";
const PI = 3.14159;
var oldStyle = true;

Operators

Arithmetic, assignment, comparison, logical, and more. Note strict equals (===).

Comparison

if (a === b) {
  // strict equality
}
if (a == b) {
  // loose equality (not recommended)
}

Conditions

Use if, else if, else, and the ternary operator.

Example

let score = 75;
let grade = (score >= 90) ? "A" : (score >= 75) ? "B" : "C";

Loops

Use for, while, and for...of for arrays.

Examples

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

let arr = [10, 20, 30];
for (const v of arr) {
  console.log(v);
}

Functions

Functions can be declared, expressed, or arrow functions.

Examples

function add(a, b) {
  return a + b;
}

const mul = function(a, b) {
  return a * b;
};

const sub = (a, b) => a - b;

Arrays

Arrays hold lists. Use methods like push, pop, map, and filter.

Examples

let nums = [1, 2, 3];
nums.push(4);
let doubled = nums.map(x => x * 2);

Objects

Objects store key-value pairs and are JavaScript's core data structure for structured data.

Example

let person = {
  name: "Sam",
  age: 14,
  greet: function() {
    console.log("Hi " + this.name);
  }
};

DOM Basics

DOM stands for Document Object Model. Use selectors to find and change elements.

Selecting elements

let el = document.getElementById("title");
let items = document.querySelectorAll(".item");

Modifying DOM

Change text, HTML, attributes, and styles via DOM properties.

Examples

el.textContent = "New title";
el.style.color = "blue";
el.setAttribute("data-id", "123");

Events

Events let your code respond to user actions like clicks and keypresses.

Adding event listeners

let btn = document.querySelector(".btn");
btn.addEventListener("click", function(e) {
  console.log("Button clicked");
});

Error handling

Use try/catch to handle runtime errors safely.

Example

try {
  let data = JSON.parse(badJson);
} catch (err) {
  console.error("Parsing failed", err);
}

Timers

setTimeout and setInterval let you schedule actions.

Example

setTimeout(() => {
  console.log("Waited 1 second");
}, 1000);

let id = setInterval(() => {
  console.log("Tick");
}, 1000);

Modules (brief)

Modern JavaScript supports modules via import and export.

Example

/* utils.js */
export function sum(a, b) { return a + b; }

/* main.js */
import { sum } from './utils.js';

JSON

JSON is a text format for data. Use JSON.parse() and JSON.stringify().

Example

let obj = { name: "A", age: 12 };
let s = JSON.stringify(obj);
let back = JSON.parse(s);

Final example — Collatz sequence (simple)

The Collatz example below reads a number and prints the sequence from 1 up to the input number using console output. Save as collatz.js and run with Node.js or include in an HTML file.

/* collatz.js */
function collatz(n) {
  let arr = [];
  for (let i = 1; i <= n; i++) {
    let x = i;
    let seq = [x];
    while (x !== 1) {
      if (x % 2 === 0) {
        x = x / 2;
      } else {
        x = 3 * x + 1;
      }
      seq.push(x);
    }
    arr.push(seq);
  }
  return arr;
}

// Example: print sequences up to 5
let sequences = collatz(5);
sequences.forEach((s, idx) => {
  console.log("Start = " + (idx + 1) + " : " + s.join(" - "));
});

MCQs

1. Which keyword declares a variable in JavaScript?

(a) let

(b) var

(c) const

(d) All of the above

► (d) All of the above

2. Which method prints output to the browser console?

(a) print()

(b) console.write()

(c) console.log()

(d) log.print()

► (c) console.log()

3. What is the correct way to write a single-line comment?

(a) # comment

(b) // comment

(c)

(d) /* comment */

► (b) // comment

4. Which operator is used to compare both value and type?

(a) ==

(b) =

(c) ===

(d) !==

► (c) ===

5. Which function displays an alert box?

(a) popup()

(b) message()

(c) alert()

(d) show()

► (c) alert()

6. Which data type represents true/false values?

(a) String

(b) Number

(c) Boolean

(d) Object

► (c) Boolean

7. Which built-in method converts a string to an integer?

(a) parseInt()

(b) int()

(c) number()

(d) convertInt()

► (a) parseInt()

8. What is the output of: console.log(typeof 42)?

(a) integer

(b) number

(c) numeric

(d) int

► (b) number

9. Which symbol starts a template literal?

(a) "

(b) '

(c) `

(d) ~

► (c) `

10. Which object is the root of the browser window?

(a) screen

(b) tab

(c) window

(d) document

► (c) window

11. Which loop runs at least once regardless of condition?

(a) for

(b) while

(c) do...while

(d) foreach

► (c) do...while

12. What does JSON stand for?

(a) Java Syntax Object Notation

(b) JavaScript Object Notation

(c) Java Source Output Network

(d) Java System Object Naming

► (b) JavaScript Object Notation

13. Which method adds an element to the end of an array?

(a) push()

(b) add()

(c) append()

(d) insert()

► (a) push()

14. What is the output of: "5" + 2?

(a) 7

(b) 52

(c) Error

(d) undefined

► (b) 52

15. What will console.log(2 == "2") output?

(a) false

(b) true

(c) undefined

(d) error

► (b) true

16. What keyword stops a loop immediately?

(a) stop

(b) exit

(c) break

(d) quit

► (c) break

17. Which operator is used for logical AND?

(a) &

(b) &&

(c) and

(d) ++

► (b) &&

18. Which DOM method selects an element by ID?

(a) querySelector()

(b) get()

(c) getElementById()

(d) pickId()

► (c) getElementById()