πŸ“Š JavaScript
Q. What will be the output of the following Javascript code?
Code:
var str1 = ”4321”;
var intval = 4321;
alert( str1 + intval );
  • (A) 4321
  • (B) 43214321
  • (C) 8642
  • (D) 12341234
πŸ’¬ Discuss
βœ… Correct Answer: (B) 43214321

Explanation:

In the given code:

var str1 = "4321";    // string
var intval = 4321; // number
alert( str1 + intval ); // concatenates str1 and intval

The key point here is that JavaScript uses type coercion when you perform the + operation between a string and a number. Since one of the operands (str1) is a string, JavaScript converts the other operand (intval) to a string as well. Then, the two strings are concatenated.

  • str1 is the string "4321".
  • intval is the number 4321, which is coerced into the string "4321".

When these two strings are concatenated:

"4321" + "4321" => "43214321"

Thus, the output of alert(str1 + intval) will be the string "43214321".

Why the other options are incorrect:

  • (A) 4321: This is incorrect because it would require a mathematical operation, not string concatenation.
  • (C) 8642: This would happen if we were performing arithmetic addition, but the + operator here is used for string concatenation.
  • (D) 12341234: This is incorrect because it's not related to the given values or any possible operation with those values.

So, the correct output is (B) 43214321.

Explanation by: Praveen Singh

In the given code:

var str1 = "4321";    // string
var intval = 4321; // number
alert( str1 + intval ); // concatenates str1 and intval

The key point here is that JavaScript uses type coercion when you perform the + operation between a string and a number. Since one of the operands (str1) is a string, JavaScript converts the other operand (intval) to a string as well. Then, the two strings are concatenated.

  • str1 is the string "4321".
  • intval is the number 4321, which is coerced into the string "4321".

When these two strings are concatenated:

"4321" + "4321" => "43214321"

Thus, the output of alert(str1 + intval) will be the string "43214321".

Why the other options are incorrect:

  • (A) 4321: This is incorrect because it would require a mathematical operation, not string concatenation.
  • (C) 8642: This would happen if we were performing arithmetic addition, but the + operator here is used for string concatenation.
  • (D) 12341234: This is incorrect because it's not related to the given values or any possible operation with those values.

So, the correct output is (B) 43214321.

πŸ’¬ Discussion


πŸ“Š Question Analytics

πŸ‘οΈ
282
Total Visits
πŸ“½οΈ
4 y ago
Published
πŸŽ–οΈ
Kirti
Publisher
πŸ“ˆ
83%
Success Rate