Technical Question

Q1

What is output and why?

(function(){
  var a = 3;
  b = 3;
})();

console.log("a defined? " + (typeof a !== 'undefined'));
console.log("b defined? " + (typeof b !== 'undefined'));

A1

false

True

Q2

Is this same result? if not, what is best practice?

function foo1()
{
  return {
      bar: "hello"
  };
}

function foo2()
{
  return
  {
      bar: "hello"
  };
}

A2

It is not.

This is why in Javascript,

curly bracket shouldnt be in new line.

Q3

(function() {
    console.log(1); 
    setTimeout(function(){console.log(2)}, 1000); 
    setTimeout(function(){console.log(3)}, 0); 
    console.log(4);
})();

What is the order?

A3

1,4,3,2

Q4

var test = "3";

(function outerFunc(test) {
  var test = '4';
  
  (function innerFunc(test) {
    console.log(test);
    
  })(2);
})(1);

What is output?

A4

2

Q5

console.log(false == '0')
console.log(false === '0')

What is the output? explain.

A5

true
false

Q6

var text = 'outside';
function logIt(){
    console.log(text);
    var text = 'inside';
};
logIt();

What is the output?

A6

Undefined

Q7

if (true) {
    var value = 'test';
}
console.log(value); 

What is output?

A7

test

Q8

var value = 1;

function Foo(value){
    value += 100;
}

Foo(value);
console.log(value); 

What is output?

A8

1

Q9

<button id="btn0">Button 1!</button>
<button id="btn1">Button 2!</button>

<script type="text/javascript">
    var values = ['test1', 'test2'];
    for (var btnNum = 0; btnNum < values.length; btnNum++) {

        document.getElementById('btn' + btnNum).onclick = function() {

            alert(values[btnNum]);
        };
    }
</script>

This will give us all undefined value when pressing button. What is wrong with this?

A9

Scope issue!

Use wrapper function.

 

<button id="btn0">Button 1!</button>
<button id="btn1">Button 2!</button>

<script type="text/javascript">
    var values = ['test1', 'test2'];
    for (var btnNum = 0; btnNum < values.length; btnNum++) {

        document.getElementById('btn' + btnNum).onclick = function(frozenBtnNum){
            return function() {

                alert(values[frozenBtnNum]);
            };
        }(btnNum);
    }
</script>
Made with Slides.com