- What is the correct way to write a JavaScript array?
A.
var colors = (1:”red”, 2:”green”, 3:”blue”)
B.
var colors = “red”, “green”, “blue”
C.
var colors = 1 = (“red”), 2 = (“green”), 3 = (“blue”)
D.
var colors = [“red”, “green”, “blue”]
- What will be printed in the browser alert window based on the code below?
var obj = JSON.parse(‘{“name” : “John”, “age” : 30, “school” : “Wake Tech”}’);
window.alert(obj.name + ” attends ” + obj.school);
The Correct Answer and Explanation is :
1. Correct Answer:
D. var colors = ["red", "green", "blue"]
Explanation:
- Arrays in JavaScript are collections of items stored in square brackets
[], separated by commas. - Option D correctly represents an array:
["red", "green", "blue"]. - Option A uses a syntax that resembles an object or map, not an array.
- Option B lacks array brackets and is not valid syntax.
- Option C uses an invalid assignment syntax for JavaScript arrays.
2. Correct Answer:
John attends Wake Tech
Explanation:
The code:
var obj = JSON.parse('{"name" : "John", "age" : 30, "school" : "Wake Tech"}');
window.alert(obj.name + " attends " + obj.school);
- JSON.parse():
- This method is used to parse a JSON string and convert it into a JavaScript object.
- The string
'{"name" : "John", "age" : 30, "school" : "Wake Tech"}'is a valid JSON format. - After parsing, the
objvariable will contain:javascript { name: "John", age: 30, school: "Wake Tech" }
- Accessing Object Properties:
obj.nameretrieves the value"John"from thenameproperty.obj.schoolretrieves the value"Wake Tech"from theschoolproperty.
- String Concatenation:
- The
+operator combines strings. "John"and" attends Wake Tech"are concatenated to form the final message:"John attends Wake Tech".
- window.alert():
- Displays the message
"John attends Wake Tech"in a browser’s alert window.
Why is This Important?
- Understanding
JSON.parse()and object property access is essential in JavaScript for handling APIs, databases, or JSON-formatted files. - Concatenation ensures proper formatting of output strings, often necessary for user-friendly communication in web applications.