JavaScript String Concatenation with Unary Plus Operator

💡JavaScript Interview Question💡 Predict the output of the below code and explain in detail. const result = ("b" + "a" + +"cteri" + "a").toLowerCase(); console.log(result); 𝗔𝗻𝘀𝘄𝗲𝗿: The above code prints "banana" as the output. This is because in JavaScript unary + operator converts a string into a number for example, +"5" will return 5 but If the string to be converted is not a number then NaN is returned so in the above code +"cteria" will result in NaN So, "b" + "a" => "ba" "ba" + +"cteria" => "baNaN" "baNaN" + "a" => "baNaNa" ("baNaNa").toLowerCase() => "banana" So, even If you write ("b" + "a" + + "a" + "a").toLowerCase(), it will still result into "banana". 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment

  • No alternative text description for this image

baNaNa - Due to unary operator + (number conversion)

Nice i don't understand why it's banana then I past the code in chatgpt and its explain me

Like
Reply

Why do you need such questions at an interview?

See more comments

To view or add a comment, sign in

Explore content categories