Table of Contents
Function scope
grammar
Example 2
Different types of functions in JavaScript
Normal function
Function expression
Arrow function
Close function
Constructor
Home Web Front-end JS Tutorial Explore the concept of JavaScript function scope and the different types of JavaScript functions

Explore the concept of JavaScript function scope and the different types of JavaScript functions

Sep 07, 2023 pm 02:41 PM

探索 JavaScript 函数作用域的概念和不同类型的 JavaScript 函数

In JavaScript, different scopes allow us to access functions and variables from different locations in the code. We will learn about function scope in this tutorial. Additionally, we will explore the different types of function expressions in JavaScript.

Function scope

When we create a new function in JavaScript, it also creates the scope of that specific function. This means that whatever variable we declare inside a function or define a nested function within it, we can access it only within the function block.

If we try to access a variable defined inside a function block from outside the function, a reference error will occur.

grammar

You can follow the following syntax to define functions and understand function scope.

function  function_name(){
   var variable = 10; // variable has a function scope.
}
let variable1 = variable; 
// we can't access the variable here as it has a function scope.
Copy after login

In the above syntax, you can see that we cannot access the variables outside the function because the function block restricts it.

Example 1

In this example, we created the sample function and defined the variables inside the function with block scope. If we try to access a variable defined inside the Sample() function from outside the function, JavaScript will throw a reference error.

<html>
<body>
   <h2>Function Scope in JavaScript</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      // defining the function
      function sample() {
         //  variables with function scope.
         var website = "TutorialsPoint!";
         var language = "JavaScript";
         output.innerHTML +=
            "You are learning the " +
            language +
            " programming language on " +
            website +
            " </br>";
      }
      sample();
      // we can't access language and website variables here.
   </script>
</body>
</html>
Copy after login

Example 2

We define nested_function() in the example function in this example. We cannot call nested_funciton() outside the sample() function because nested_function is within the scope of the sample function.

<html>
<body>
   <h2>Function sSope in JavaScript</h2>
   <div id="output"></div>
   <script>
      let output = document.getElementById("output");
      function sample() {
         //  variables with function scope.
         var num = 10;
         function nested_function() {
            // num variables also can be accessed here as nested_function() is
            //inside the scope of sample function
            var string = "JavaScript";
            output.innerHTML +=
               "The value of the num variable is " + num + "<br/>";
            output.innerHTML +=
               "The value of the string variable is " + string + "</br>";
         }
         //  we can call the nested_function() inside the sample() function only
         nested_function();
         // we can't access the string variable here as the scope of 
         //nested_function bounds it
      }
      sample();
   </script>
</body>
</html>
Copy after login

Different types of functions in JavaScript

According to the definition and declaration of the function, there are many types of functions. We will study them one by one here.

Normal function

Normal functions are functions commonly used by all JavaScript developers. We can define regular functions using the function name followed by the function keyword.

Regular functions remain at the top of the function's current scope. This means we can call the function before defining it, but it should be defined after execution.

grammar

Define regular functions according to this syntax.

function function_name(){
   // function body
}
Copy after login

In the above syntax, we use the function keyword to define the function. ‘function_name’ is the name of the function, and we can write the code for the function body within curly brackets.

Function expression

Function expressions also work similarly to ordinary functions. However, the difference is that it doesn't have any name and we need to store the function expression in a variable. We can use the identifier to call the function that stores it.

JavaScript evaluates function expressions step by step. Therefore, it is not hoisted to the top of the scope, so we cannot call it before declaring it.

grammar

Define function expressions according to this syntax.

var function_identifier = function () {
   // function body
}
function_identifier();
Copy after login

In the above syntax, we have defined a function without a name using only the function keyword and stored it in the function_identifier variable. Additionally, users can see how we use function_identifier to call function expressions.

Arrow function

Arrow functions were introduced in ES6, the last major revision of JavaScript in 2015. It is a shorter syntax for defining functions without a function name. Also, it is called expressions and anonymous functions because it does not contain their identities.

grammar

Define arrow functions according to this syntax.

var function_identifier =  (params) => {
   // function body
}
function_identifier(arguments);
Copy after login

In the above syntax, we store the arrow function expression in function_identifier. Furthermore, we passed the arguments and arguments inside the arrow function while calling the function using the function_identifier variable.

Close function

We can create nested functions in JavaScript and use child functions to access parent function variables. Since the child function contains access to all variables defined in the scope of the parent function, we can call the child function a closure function.

grammar

function parent() {
   // variables of the parent
   var child = () => {
      // variables of child
      // access variables of the parent
   };
   return child;
}
var child = parent();
child();
Copy after login

In the above syntax, we can access all variables of the parent function inside the child function, and the parent function returns the child function. Therefore, we can call a child function indirectly from outside the parent function, even if it is defined within the scope of the parent function.

Constructor

grammar

We can use constructors to create objects.

function constructor(property){
   this.property = property
}
var string = new constructor("value");
Copy after login

In the above syntax, we create the object of the constructor.

We learned how function scope for nested functions works through two examples in this tutorial. Additionally, we learned about the different types of functions. Additionally, there are some other types of functions such as recursive or callback functions that users can explore on the internet.

The above is the detailed content of Explore the concept of JavaScript function scope and the different types of JavaScript functions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles