当前位置:网站首页>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.
边栏推荐
猜你喜欢
1.13 学习JS
The Error in the render: "TypeError: always read the properties of null '0' (reading)" Error solution
【 application 】 life many years of operations, what turned scored 12 k + annual bonus salary?
Phospholipid-polyethylene glycol-azide, DSPE-PEG-Azide, DSPE-PEG-N3, MW: 5000
解决5+APP真机测试无法访问后台(同局域网)
5.20今日学习
js __proto__、prototype、constructor的关系
STM32 CAN过滤器
js 原型和原型链
你的本地创建的项目库还在手动创建远端代码仓库再推送吗,该用它了
随机推荐
Circular linked list---------Joseph problem
uniapp | 使用npm update更新后编译报错问题
display,visibility,opacity
5.20今日学习
querystring模块
DOM操作---放大镜案例
微信小程序自定义swiper轮播图面板指示点|小圆点|进度条
如何计算地球上两点的距离(附公式推导)
微信小程序云开发之券码领取,怎么防止用户领取到相同的数据?
正则笔记(2)- 正则表达式位置匹配攻略
轮播图详解(完整代码在最后)
ES6数组的扩展方法map、filter、reduce、fill和数组遍历for…in for…of arr.forEach
多线程(实现多线程、线程同步、生产者消费者)
微信小程序云开发之模糊搜索
一分种一起来了解Vite的基础
如何查看一个现有的keil工程之前由什么版本的keil IDE编译
require modular syntax
--fs module--
clock tick marks
猴子选大王