Interview Questions on Javascript

Quick Questions to check basic conceptual knowledge.

Question 5

How would you reverse a string in JavaScript?
Input : reverse
Output : reverse

This is one of the most simple and trick questions in interview. It can be achieved in many ways and all of them would be simple concepts.

Javascript:


	let input = 'reverse';
	let output = '';

	console.log('How would you reverse a string in JavaScript');
	console.log('Input : ' + input);

	//One way to do this is using a simple decremented for loop. Just concatenate the string in reverse order into a new string.
	for (i = input.length - 1; i >= 0; i--) {
		output += input.charAt(i);
	}

	console.log('Output: ' + output);
	//There are few in-build javascript methods which can be used to do the same task in one line. Here I have used split(), reverse() and join() methods.

	let simpleOutput = input.split('').reverse().join('');

	console.log('Output From Split Reverse Join: ' + simpleOutput);								
									
Explanation:

		split(): It breaks the string into an array based on the delimiter. In this case, delimiter is empty string, that means, each character of the string will be treated as separate value.

		So, console.log(input.split('')) will give an output of [ 'r', 'e', 'v', 'e', 'r', 's', 'e' ].

		reverse(): The task of reverse is to put an array in reverse order. In this case, console.log(input.split('').reverse()) will give output as [ 'e', 's', 'r', 'e', 'v', 'e', 'r' ].

		join(): Join concatenates each value inside an array along with the value passed to the function.
		For example,
		console.log(['abc', 'def', 'ghi'].join(',')) will give an output as abc,def,ghi.
		While console.log(input.split('').reverse().join('')) will output as esrever because, as per the value passed to the join function, it should have a ‘’ between each value of the array.