John Smith John Smith - 1 month ago 8
Javascript Question

Javascript ING BANK 3 questions test interview

I had a test interview and for 3 questions I didn't know the answer:


  1. Write a function that will insert underscore between characters: this will become t_h_i_s.

  2. Write a function that will output this:





l('t') === 'lt'
l()('t') === 'l3t'
l()()('t') === 'l33t'
l()()('g') === 'l33g'
l()()()()()()()()()()()('t') === 'l33333333333t'






  1. Why the output is true?





var bar = true;
function foo() {
bar = false;
return 5;
function bar() {}
}
foo();
console.log(bar);





Can someone help please with the answers?

Answer
  1. Write a function that will insert underscore between characters: this will become t_h_i_s.

You want to write a function that iterates over all characters in a string, and appends an underscore between all characters.

For example:

function underscoreString(str) {
    var result = str.charAt(0);

    for (var i=1; i<str.length; i++) {
        result += '_' + str.charAt(i);
    }

    return result;
}

console.log( underscoreString('this') );
  1. Write a function that will output this:

You will need to write a function that returns another function, so you can chain the functions. Since Javascript allows you to store functions as variables, you can make use of this by re-calling the same function continuously until a proper argument is returned.

The following function is an example. It works as intended but is not the most beautiful.

function l(ch) {
    var str = 'l';
    if (ch) return str + ch;
    else str += '3';

    var newFunc = function (ch) {
        if (ch) return str + ch; 
        str += '3';
        return newFunc;
    }
    return newFunc
}

console.log( l('t') === 'lt' );
console.log( l()('t') === 'l3t' );
console.log( l()()('t') === 'l33t' );
console.log( l()()('g') === 'l33g' );
console.log( l()()()()()()()()()()()('t') === 'l33333333333t' );
  1. Why the output is true?
var bar = true;
function foo() {
  bar = false;
  return 5;
  function bar() {}
}
foo();
console.log(bar);

The bar that is within the function foo() is not referencing the global variable bar. Instead, it is referencing the function function bar() {}. This is because of hoisting, as mentioned in the comments.

Thus, the global bar variable is not touched at all by the function, and stays true at all times.