Hint: Use curly braces and colons for object properties [OK]
Common Mistakes:
Using parentheses instead of braces
Using equal signs instead of colons
Wrong property names like val or pointer
3. What will be the output of the following code?
function Node(value) {
this.value = value;
this.next = null;
}
const first = new Node(1);
const second = new Node(2);
first.next = second;
console.log(first.next.value);
medium
A. undefined
B. 1
C. 2
D. null
Solution
Step 1: Understand node creation and linking
Two nodes are created with values 1 and 2. The next of the first node points to the second node.
Step 2: Access the value of the node pointed by first.next
first.next points to the second node, which has value 2, so first.next.value is 2.
Final Answer:
2 -> Option C
Quick Check:
first.next.value = 2 [OK]
Hint: Follow the next pointer to get the next node's value [OK]
Common Mistakes:
Confusing first.value with first.next.value
Expecting null instead of node value
Not linking nodes before accessing next
4. Identify the error in the following code snippet for creating a linked list node:
function Node(value) {
this.value = value;
this.next = undefined;
}
const node = new Node(10);
console.log(node.next.value);
medium
A. The next pointer should be a number
B. Missing semicolon after new Node(10)
C. Node constructor should not use this
D. Accessing value of undefined causes error
Solution
Step 1: Analyze the next pointer initialization
The next pointer is set to undefined, meaning it does not point to any node.
Step 2: Understand the error when accessing node.next.value
Since node.next is undefined, trying to access value on it causes a runtime error.
Final Answer:
Accessing value of undefined causes error -> Option D
Quick Check:
Accessing property on undefined = error [OK]
Hint: Never access properties on null or undefined pointers [OK]
Common Mistakes:
Assuming next can be undefined safely
Thinking semicolon omission causes runtime error
Believing this is invalid in constructor
5. You want to create a singly linked list with nodes containing values 1, 2, and 3 in order. Which code snippet correctly links the nodes?