Crazy interview Questions on Javascript functions (Part 1).

·

2 min read

Dear Fellow Readers, In this blog I am going to talk about functions in javascript. what it is and what is the craziest interview question you might get asked in your next round.

well, functions are the heart of javascript.

since the definition is common in all languages functions are blocks of code you might want to repeat in your codebase. so, you can wrap it inside the function and call it wherever you want.

but the way you can use functions in javascript is so different from how you use it in another language not just in terms of syntax but in a lot of different ways.

well, a normal function looks like this in javascript.

function myfunction() {
   console.log("my funciton is called");
}

this is what the function looks like.

now, let's talk about interview questions in javascript functions.

  1. Difference between function declarations/function expressions/function statements?

well, function declaration and function statements both are the same in logic but different in English juggles and it means basically, declaring functions, creating a function, or initializing a function.

for eg.

function myfunction() {
   console.log("my funciton is called");
}

here, again myfunction is declared which is a statement and declaration as well.

now, let's talk about function expressions. well as I told you functions are amazing in javascript and one of its great features is, you can use functions as values and assign them to any variable like this.

var b = function () {
   console.log("my funciton is called");
}

here, a function is used as a value and is assigned to b and now you can call b and it will execute the logic of the function like this.

b();

but, what's the difference well the difference is hoisting. the difference comes when we try to access the function before a declaration. you can do this easily with function statements but with function expressions, you will get an error.

myfunction(); // will execute perfectly
b(); // will throw error

function myfunction() {
   console.log("my funciton is called");
}

var b = function () {
   console.log("my funciton is called");
}

well, if you what is hoisting in javascript you understood the reason here that function can be called before declaration as it gets stored in memory. while the variable is also stored in memory but with the initial value as "undefined". and you can't call something a function that is undefined.

hope, you understand this.

now, I don't want to make this blog lengthier so, the next question will be on the next blog.

just keep following.