Home > Web Front-end > JS Tutorial > Analysis of the difference between JavaScript function declaration and variable declaration

Analysis of the difference between JavaScript function declaration and variable declaration

不言
Release: 2018-09-11 15:14:34
Original
1495 people have browsed it

The content of this article is about the analysis of the difference between JavaScript function declaration and variable declaration. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Today, another question triggered a battle between me and the basics of JS: First of all,

var getName = function(){alert(1)};
function getName(){alert(2)};

getName();// 1
Copy after login

or

function getName(){alert(2)};
var getName = function(){alert(1)};

getName();// 1
Copy after login

Why did I change the order of declarations, but the result was still output? The value of a function declared in the form var?
Someone answered me and said, "Ah, the variables are improved...", My initial understanding is that even if the variables are improved, after the first situation is improved, it should be like this:

var getName;
getName = function(){alert(1)};
function getName(){alert(2)};
Copy after login

The final output should be 2 (very reasonable).
As everyone knows, not only var declarations will be advanced, functions declared in the form of function fn(){} will be promoted to the scope. The most is at the top, and then the variable is raised.
Please see the following example for details:

fn();//Uncaught TypeError: fn is not a function
var fn = function(){console.log(1)};
Copy after login

but

fn();//2
var fn = function(){console.log(1)};
function fn(){console.log(2)}
Copy after login

It is enough to show that the function is improved more fiercely.

Related recommendations:

javascript variable declaration example analysis_javascript skills

##JavaScript global variable declaration and introduction to advantages and disadvantages

The above is the detailed content of Analysis of the difference between JavaScript function declaration and variable declaration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template