Functions: Declarations, Expressions, and Scoping

In JavaScript, functions are reusable blocks of code that can be called and executed multiple times with different inputs. There are different ways to declare functions and define their scope.

Function Declarations:

Function declarations are a way to define a named function with a set of parameters and a body of code that will be executed when the function is called. They are defined using the function keyword followed by the name of the function, the parameter list in parentheses, and the function body in curly braces. Example:

function add(a, b) {
return a + b;
}

Function Expressions:

Function expressions are another way to create a function in JavaScript. They are defined using the const, let, or var keyword, followed by an assignment operator, and a function definition. Function expressions can be anonymous or named.

const add = function(a, b) {
return a + b;
}

Arrow Functions:

Arrow functions are a newer way to create a function in JavaScript. They provide a shorter syntax for writing functions and are commonly used for callbacks and event handlers. They are defined using the arrow (=>) symbol, which replaces the function keyword.

const add = (a, b) => {
return a + b;
}

Scoping:

In JavaScript, there are two types of scope: global scope and local scope. Global scope refers to variables or functions that are accessible throughout the entire program, while local scope refers to variables or functions that are only accessible within a specific block of code.

The var keyword is used to declare variables with function scope, while const and let are used to declare variables with block scope.

function myFunction() {
var x = 1; // function scope
const y = 2; // block scope
let z = 3; // block scope
}

It’s important to note that variables declared with the var keyword have function scope, meaning they can be accessed anywhere within the function, even before they are declared. Variables declared with const and let, on the other hand, have block scope, meaning they can only be accessed within the block where they are declared.

--

--

Arun Kumar
Mastering JavaScript: Essential Concepts and Techniques for Web Development

Experienced web developer with 10+ years expertise in JavaScript, Angular, React and Vue. Collaborative team player with focus on results.