Câu hỏi phỏng vấn Javascript
Câu hỏi

Explain the differences on the usage of foo between function foo() {} and var
foo = function() {}

Câu trả lời

In JavaScript, the way you define a function can affect how and when you can use it due to differences in hoisting and scope. The two primary ways to define a function are through a function declaration and a function expression.

Function Declaration

A function declaration is the traditional way of defining a function. It is written with the function keyword followed by the name of the function:

javascript Copy
function foo() {
    // Function body
}

The key characteristics of function declarations include:

  • Hoisting: Function declarations are hoisted, which means they are raised to the top of their containing scope during the compilation phase. This allows you to call the function before it is defined in the code[2][3].
  • Scope: The scope of a function declaration is either global or local to the function it is defined within[3].
  • Named Function: Function declarations must have a name, which is foo in this case[2].

Function Expression

A function expression, on the other hand, involves creating a function and assigning it to a variable:

javascript Copy
var foo = function() {
    // Function body
};

The characteristics of function expressions include:

  • No Hoisting: Function expressions are not hoisted. You must define them before you can call them. If you try to call a function expression before its definition, you will get a TypeError because the variable foo will be undefined at that point in the code[2].
  • Anonymous Functions: The function in a function expression can be anonymous, which means it does not have a name. However, it can also be named, which can be useful for recursion or debugging[2].
  • Variable Scope: The variable foo has the scope rules of any other variable. If it's declared with var, it's scoped to the function or global scope. If declared with let or const, it's block-scoped[2].

Arrow Functions

With the introduction of...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

When should you NOT use arrow functions in ES6? Name three or more cases

expert

In JavaScript, why is the this operator inconsistent?

junior

What is a Polyfill?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào