当前位置:网站首页>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.
边栏推荐
- 阿里云设置域名解析重定向后,无法使用Chrome访问
- 由中序遍历和后序遍历得到前序遍历(树的遍历)
- IP门禁:手把手教你用PHP实现一个IP防火墙
- 微信小程序云开发之模糊搜索
- [phpunit/php-timer]一个用于代码执行时间的计时器
- clock tick marks
- The Error in the render: "TypeError: always read the properties of null '0' (reading)" Error solution
- 骨架效果 之高级渐变,适用图片等待时
- 每日五道面试题总结 22/7/21
- v-bind用法:类动态绑定对象 数组 style样式 及函数方法
猜你喜欢
随机推荐
Phospholipid-polyethylene glycol-targeted neovascularization targeting peptide APRPG, DSPE-PEG-APRPG
每日五道面试题总结 22/7/19
STM32 CAN过滤器
这些JS题面试时一定要答对!
FreeRTOS内核详解(1) —— 临界段保护原理
每日五道面试题总结 22/7/20
针对简历上的问题
每日五道面试题总结 22/7/21
URL module
面试总结 22/7/22 面试中的重点
[phpunit/php-timer]一个用于代码执行时间的计时器
阿里云服务器如何使用admin账户登录
解决5+APP真机测试无法访问后台(同局域网)
如何根据地图上的两个坐标点来确定方向
数组的高级操作
uniapp | 开发中遇到的兼容性问题(待续)
微信小程序云开发如何将页面生成为pdf?
js 之 Object.defineProperty()
---静态页面---
使用PHPMailer发送邮件









