search
HomeWeb Front-endJS TutorialExplanation of common JS function issues

Explanation of common JS function issues

May 21, 2018 am 10:54 AM
javascriptjsfunction

We often encounter Javascript function problems while studying, and this article will explain them.

What is the difference between function declaration and function expression

Function expression and function declaration statement contain the same function name, and both create new function objects. Their difference mainly lies in variable promotion The objects are different

The function name declared by the function is a variable, and the variable points to the function object. Variable promotion is the variable and function body of the function.

The function expression is assigned through var, and the entire function is assigned to a new variable. The variable is promoted to a new variable name, and the function initialization code will remain in its original position.

What is variable declaration prefix? What is the declaration prefix of a function

The declaration prefix of a variable

console.log(a);var a = 1;
结果为underfined

The declaration prefix of a variable will default to this code:

var a; //Before the variable declaration Set console.log(a);
a = 1;

The declaration of the function is preceded

a()function a(){console.log ("hello") }

The declaration of the function is preceded. The default code is:

function a(){                   //将函数声明提升console.log ("hello") }a()
arguments 是什么

arguments is an array-like object, which stores the parameters passed in when the function is executed. In the function, arguments can be used to obtain the parameters of all functions.
The following code:

function say(name,sex,age){  console.log(arguments);
}console.log('name:jiuyi',"sex:男",'age:54')
结果为:"name:jiuyi""sex:男""age:54"

How to implement function overloading

There is no concept of function overloading in JS. The subsequent new function will overwrite the previous function with the same name, even if the parameters are different .

      function p(a,b,c) {  
           console.log(a+b+c);  
       }  
 
       function p(a,b) {  
           console.log(a+b);  
       }       console.log(p('hello','jiuyi','yes'));       console.log(p('hello'))
结果为:  "hellojiuyi"
 "helloundefined"

As can be seen from the above figure, the latter P function overwrites the upper P function.

What is the immediate execution function expression? What is the function

Immediately executing a function expression means enclosing the entire function declaration with () to become a function expression, and then following the parameters, the function will be executed immediately.
function ( ){ }The function declaration is converted to ( function (){ }) ( )
Function:

Generates its own scope and independent local variables, without being disturbed by variable promotion. Reduce the possibility of conflicts between internal variables and external variables. The variables will be destroyed once executed.

What is the scope chain of a function

In JS, it is divided into global variables and local variables. Global variables can be accessed inside the function, but local variables inside the function cannot be accessed outside the function. In variables When inside a function, it will first search whether the variable is defined in this scope. If not, it will search to the next level until it finds the required variable. If it is not found in the global variable, an error will be reported. Try to use local variables to avoid interference with external variables.

1. Code output

  function getInfo(name, age, sex){        console.log('name:',name);        console.log('age:', age);        console.log('sex:', sex);        console.log(arguments); //代表实际参数,所以输出实际参数内容
        arguments[0] = 'valley';//name赋值为valley
        console.log('name', name);//所以这里参数输出为valley
    }
    getInfo('hunger', 28, '男');
    getInfo('hunger', 28);
    getInfo('男');
结果为:
name: hunger
 age: 28
 sex: 男
["hunger", 28, "男"]
name valley
 name: hunger
 age: 28sex: undefined
 ["hunger", 28]
 name valley
name: 男
age: undefined
 sex: undefined["男"]
name valley

2. Write a function that returns the sum of the squares of the parameters

  function sumOfSquares(){   var x = 0;   for(var i = 0;i<arguments.length;i++){
   x = x + arguments[i]*arguments[i]
   }   console.log(x)
   }
   sumOfSquares(2,3,4);   
   sumOfSquares(1,3);
结果为:2910

3. What is the output of the following code? Why

console.log(a); //The output is underfined, because JS will promote global variables, a only declares but does not assign a value var a = 1;console.log(b);//An error is reported because b Undeclared Unassigned

4. What is the output of the following code? Why

sayName(&#39;world&#39;); 
sayAge(10); function sayName(name){ console.log(&#39;hello &#39;, name);
 } var sayAge = function(age){ 
console.log(age); 
};

The result is:
hello world //Because the function declaration prefix function sayName(name) is promoted to the top, sayName has a declaration and content. Error report //Because the variable declaration preceded var sayAge is raised to the top, and the sayAge function is not declared, an error is reported.

5. What is the output of the following code? Why

function fn(){} 
 var fn = 3; console.log(fn);
相当于:  var fn;  function fn(){} ;
  fn = 3;  console.log(fn);    //所以输出为3

6.The output of the following code? Why

function fn(fn2){   console.log(fn2);   //输出 function fn2(){ console.log(&#39;fnnn2&#39;);}
   var fn2 = 3;   console.log(fn2);   //输出3
   console.log(fn);    //输出 function fn(fn2){ console.log(fn2); var fn2 = 3; console.log(fn2); console.log(fn); function fn2(){ console.log(&#39;fnnn2&#39;); } } fn(10);
   function fn2(){ 
     console.log(&#39;fnnn2&#39;);  //不输出,函数未调用
   } 
} 
fn(10);
相当于:var fn2;                            //声明前置function fn(fn2){  
   function fn2(){                   //函数声明前置
     console.log(&#39;fnnn2&#39;);          //此函数不输出,未调用
   } 
   console.log(fn2);               // 调用的其实是函数fn2
   fn2 = 3;             
   console.log(fn2);            // 此时fn2已被赋值为3
   console.log(fn);              //调用的其实是fn整个函数}
fn(10);

7.The output of the following code? Why

  var fn = 1;    function fn(fn){         console.log(fn);
    }    console.log(fn(fn));       //结果报错,变量提升,fn为1,直接调用1出错结果相当于:    var fn;    function fn(fn){         console.log(fn);
    }
    fn = 1;    console.log(fn(fn));

8.The output of the following code? Why

console.log(j);   //变量提升输出undefined
 console.log(i);    //变量提升输出undefinedfor(var i=0; i<10; i++){   //i循环后结果为10var j = 100; 
} console.log(i);    //输出10
 console.log(j);    //输出100

9.The output of the following code? Why

 fn();   var i = 10;   var fn = 20;   console.log(i);   function fn(){       console.log(i);       var i = 99;
       fn2();       console.log(i);       function fn2(){
           i = 100;
        }
    }
代码相当于:var i; 
var fn;function fn(){  
  var i ;  function fn2(){
  i = 100;
  } console.log(i);    //只有声明未赋值输出underfined
  i = 99;
  fn2();                  //经过运行I=100
  console.log(i);      //输出100}
fn();
i = 10;
fn = 20;console.log(i);             //输出10

10.The output of the following code? Why is the

 var say = 0;
    (function say(n){        console.log(n);        if(n<3) return;
        say(n-1);
    }( 10 ));    console.log(say);

code equivalent to: var say;

   (function say(n){        console.log(n);        if(n<3) return;    
        say(n-1);
    }( 10 ));
      say = 0;    console.log(say);           //输出为0结果为:10987654320

The function say is an immediate execution function, and the execution results are 10, 9, 8, 7, 6, 5, 4, 3 , 2. Finally, say is assigned a value of 0, so the output is 0

This article explains common js function problems. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Explanation of JavaScript related functions

Explanation of jquery DOM& events

Some related modular basics

The above is the detailed content of Explanation of common JS function issues. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles

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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software