What is the correct way to write a JavaScript array

  1. 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”]

  1. 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);
  1. 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 obj variable will contain:
    javascript { name: "John", age: 30, school: "Wake Tech" }
  1. Accessing Object Properties:
  • obj.name retrieves the value "John" from the name property.
  • obj.school retrieves the value "Wake Tech" from the school property.
  1. String Concatenation:
  • The + operator combines strings.
  • "John" and " attends Wake Tech" are concatenated to form the final message: "John attends Wake Tech".
  1. 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.
Scroll to Top