当前位置:网站首页>Function hoisting and variable hoisting
Function hoisting and variable hoisting
2022-08-02 03:52:00 【Xiaoru wants to sleep】
Let's look at two similar codes first
a = 2;var a ;console.log(a);console.log(a);var a = 2;The first output is 2
The second output value is undefined
You may be wondering why?
Let's look into it
This is because all declarations including variables and functions are processed first before any code is executed
So the first code actually handles this
var a;a = 2;console.log(a);The second code is handled like this
var a ;console.log(a);a = 2;This process is as if variable and function declarations are "moved" to the top from where they appear in the code.This process is called ascension
Note: Only the declaration itself will be hoisted, and assignments or other run logic will be left in place.If hoisting changes the order in which code is executed, it can cause very serious damage.Function declarations can be hoisted, but function expressions cannot be hoisted.
Function first
Both function declarations and variable declarations are hoisted, but in duplicated code, functions are hoisted first, then variables
foo();//1var foo;function foo() {console.log(1);}foo = function() {console.log(2);}This will output 1 instead of 2, this code will be understood by the engine as the following format
function foo(){console.log(1);}foo(); // 1foo = function(){console.log(2);}Here var foo although appears before the declaration of function foo()......, but because it is a duplicate declaration (and thus ignored) because when there is a duplicate declaration, the function declarationwill be hoisted before variable declarations.
边栏推荐
猜你喜欢
随机推荐
npm and package.json
正则笔记(1)- 正则表达式字符匹配攻略
ES6迭代器解释举例
查询数据库中所有表的索引,并且解析成sql
多线程(实现多线程、线程同步、生产者消费者)
ES6数组的扩展方法map、filter、reduce、fill和数组遍历for…in for…of arr.forEach
js 取字符串中某位置某特征的值,如华为(Huawei)=>华为
数组的高级操作
如何计算地球上两点的距离(附公式推导)
L1-043 阅览室 (20分)
display,visibility,opacity
js scope and closure
1.10今日学习
PHP8.2的版本发布管理员和发布计划
1.11今日学习
PHP图片压缩到指定的大小
我的小笔记 =》其他东东
解决MySQL创建子视图并查看的时候,字符集报错问题
页面加载流程
uniapp | 开发中遇到的兼容性问题(待续)









