Skip to content

JavaScript: Answer To Tricky Interview Questions

23 June 2014

This question is listed on June 22, 2014 @ JS: Tricky Interview Questions under part -2: intermediate

Q: If i have a var str = ‘hello world’, how could i get str.reverse() return ‘dlrow olleh’?

Introduced in ECMAScript 5, string could be treated as an array-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"

JavaScript automatically converts primitives (string literals, i.e. quoted, and strings in a non-constructor context i.e., without using the new keyword) to String objects, so we can always apply String object methods.

Analyzing the task probably the first think we’ll notice (at least I did) is the word “reverse” which is an Array method. Starting from here we’ll need one String object method to convert string to an array, the reverse itself, and another Array object method to convert array back to string.

If we had to split string into words I hope that every javascript developer is aware of the existence of String.prototype.split() method.

Definition reads: Splits a String object into an array of strings by separating the string into substrings.
The split method returns a new array. It accept two parameters: split([separator][, limit]). What we are looking for is: “If separator is an empty string, string is converted to an array of characters“.

So let’s apply it:

'hello world'.split('');
> ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

So far, so good. Next we apply array.reverse() method which “… reverses an array in place. The first array element becomes the last and the last becomes the first.

'hello world'.split('').reverse();
> ["d", "l", "r", "o", "w", " ", "o", "l", "l", "e", "h"]

Last one is again well known – how to combine char array into string. Do you know it?

Good for you!
Yes, it is “The join() method joins all elements of an array into a string.” But be aware that “If [separator is] omitted, the array elements are separated with a comma.” So as a separator we’ll use empty string:

'hello world'.split('').reverse().join('');
 > "dlrow olleh"

Done! Inline.

I hope now you’re ready to answer that question 😉

Advertisements

From → JavaScript, Tips

2 Comments
  1. Liar permalink

    WRONG. TRIED IT AND IT CAME OUT AS “WORLD! HELLO” I HATE LIARS.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: