Back to the 2024 paper

Module III — Basics of Web Programming

20249m

Discuss the following with respect to JavaScript: Data types, function expression, and this keyword.

Worked SolutionAI Assisted

1. Data types in JavaScript

JavaScript is dynamically typed: a variable's type is decided at runtime and can change.

Primitive types (immutable, stored by value)

Type Example
number 42, 3.14, NaN, Infinity
string "hello", 'hi', `template ${x}`
boolean true, false
undefined a declared variable with no value
null intentional "no value"
symbol Symbol('id'), a unique identifier
bigint 123n, for very large integers

Non-primitive (reference) type: object, which includes plain objects {}, arrays [], functions, Date, Map, Set (stored by reference).

let a = 10;            typeof a;   // "number"
let b = "text";        typeof b;   // "string"
let c = null;          typeof c;   // "object" (historic quirk)
let d;                 typeof d;   // "undefined"
let e = [1, 2];        typeof e;   // "object" (use Array.isArray)

2. Function expression

A function expression creates a function inside an expression and assigns it to a variable; the function may be anonymous.

const square = function (n) {      // function expression
  return n * n;
};
console.log(square(5));              // 25

const add = (a, b) => a + b;         // arrow function expression

Differences from a function declaration (function square(n) {...}):

Declaration Expression
Fully hoisted; can be called before it is defined Not usable before the assignment line runs (variable hoisted, value is not)
Always has a name Can be anonymous or named

Uses: callbacks (arr.map(function (x) {...})), IIFEs (function(){ ... })();, closures, and passing functions as values.

3. The this keyword

this refers to the object that is executing the current code; its value depends on how the function is called.

Context Value of this
Global scope / plain function (non-strict) window (browser) or globalThis; undefined in strict mode
Method call obj.method() obj
Constructor new Person() the newly created object
Event handler the element that received the event
call, apply, bind the object explicitly supplied
Arrow function inherits this from the enclosing scope (no own this)
const user = {
  name: "Raiyan",
  greet() { console.log("Hi, " + this.name); }   // this = user
};
user.greet();                 // Hi, Raiyan

const fn = user.greet;
fn();                          // this lost: undefined / window.name

fn.call({ name: "Ali" });      // Hi, Ali (explicit binding)

const timer = {
  n: 0,
  start() { setInterval(() => this.n++, 1000); }   // arrow keeps this = timer
};

Similar questions

AI LearningWeb Platform

Coursify — Personal AI Course Generator

Struggling with a difficult subject or concept? Turn any engineering topic into a structured course with interactive lessons, quizzes, and research-backed explanations.