1.

When an onfocus event is triggered in JavaScript?

Answer»

Function declaration is like most other traditional languages, but in JavaScript we use the keyword “function”.
In function expression we assign an anonymous function to an variable. They are very useful when we PASS function as arguments to other function or return an function.

function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); }   console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //Function expression 

One of the key difference is that, we can call a function declaration even before defining it but same is not true for function expression and it will give reference error. Let’s move both the function call to the top. 

console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //ReferenceError   function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); }

/*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization

@Scratchpad/7:2:1

*/

But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we UNDERSTOOD in Question 1. 
The compiler RUNS first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration. 
So, the function declaration call doesn’t give as any error.
But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t KNOW what is functionExpression.



Discussion

No Comment Found