当前位置:网站首页>What is the difference between statements and expressions
What is the difference between statements and expressions
2022-07-18 04:18:00 【www_ xuhss_ com】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
Preface
JavaScript What are the differences between statements and expressions in ?
For this question , I seem to know the answer , But when I try to explain to others , But I was speechless . I have a feeling about this problem , But it can't be expressed clearly .
I realized later , This question is extremely important . It can be said to be the bearing wall of the house , Will help support a large number of JavaScript knowledge .
Yes React For developers , More so . Those you have to remember JSX The rules , And those rules that you always forget to follow , Most of them are sentence / expression The result of duality .
In this article , I will share some of my insights on the difference between the two , And how we use this information in our daily work .
expression
essentially , An expression is a segment that produces a value JavaScript Code .
All the following examples are expressions :
1→ The generated value is1"hello"→ The generated value is"hello"5 * 10→ The generated value is50num > 100→ The generated value istrueperhapsfalseisHappy ? "" : ""→ The resulting value is a emoji[1, 2, 3].pop()→ The generated value is3
Expressions can contain other expressions . for instance , You think the following JS How many expressions are there in the code ?
(5 + 1) * 2
The answer is 5 Expression .
say concretely , They are 5 individual :
(5 + 1) * 2, This code itself is an expression , The resulting value is12(5 + 1), Because there are brackets , This subexpression is evaluated first , And resolved to6.5, A single number is itself an expression , Because they produce a value . This expression resolves to5.1, Same thing , This expression resolves to1.2, This number forms the final expression , It translates into2.
sentence
One JavaScript A program is a series of statements . Every statement is an instruction for the computer to do something .
This is about JavaScript Examples of statements in :
let hi = 5;
if (hi > 10) {
// More statements
}
throw new Error(' Wrong report ');
About statements and expressions , I think so : Statement is the rigid structure supporting our program , The expression is filled with details .
Statements usually have expressions “ slot ”. We can put any expression we like into these slots .
for instance , Declaring a variable with an expression slot can do this :
let hi = /* expression */;
In this slot , We can use any expression we have seen before :
let hi = 1;
let hi = "hello";
let hi = 5 * 10;
let hi = num > 100;
let hi = isHappy ? "" : "";
let hi = [1, 2, 3].pop();
In terms of effective grammar , Expressions are interchangeable . If a statement has an expression slot , We can put any expression there , The code will run . And we won't get grammatical errors .
in other words , We may encounter other problems . for instance , The following code is syntactically valid , But if we try to run it, the browser will crash , Because it will lead to dead circulation :
while ("hello") {
// because "hello" Never change , So the cycle will repeat again and again , Until the script crashes .
// Grammatically valid , But there are still problems .
}
Convenience skills
Want to know a paragraph JS Is the code a statement or an expression ? Try to print it out !
console.log(/* Here is JS Code */);
If it can run , This code is an expression . If you make a mistake , That is the sentence ( Of course , It may also be illegal JS).
Besides , We can even see the result of the expression , Because the results will be printed to the browser console .
This works because the parameters of any function must be expressions . The expression produces a value , And pass the value into the function . Syntax does not produce a value , Therefore, statements cannot be used as arguments to functions .
Even as an experienced developer , I also rely on console.log. It's really a good thing .
Expressions as statements
This is an expression :1 + 2 + 3 .
If we create a that includes only this expression JS file , What's going to happen ? Let's try to save the following content as test.js:
1 + 2 + 3
How many statements are there in this file ?0 One is still 1 individual ?
Here's the thing : Expression cannot exist alone . They are always part of the statement . So in this case , We have a statement that looks like this :
/* Expression slot */
In addition to expression slots , The statement is basically empty . expression 1 + 2 + 3 Filled the slot , Then the statement is generated .
let me put it another way , All the following lines are valid statements :
// sentence 1:
let hi = /* Expression slot */;
// sentence 2:
return /* Expression slot */;
// sentence 3:
if (/* Expression slot */) { }
// sentence 4:
/* Expression slot */
Usually , Some tutorials incorrectly point out , Expressions are statements , But that's not exactly true . Expressions and statements are different things . But the statement may wrap the expression without providing any additional characters . It's like wrapping a sandwich with transparent plastic wrap .
Statements usually end with semicolons , It marks the end of the statement . Semicolons are not necessary for some statements , Such as if sentence 、while Loop and function declarations .
React Practice in
If you've ever used React, You may know braces { and } Allow us to JSX Embed some JavaScript, Just like this. :
function CountdownClock({ secondsRemaining }) {
return (
<div>
Time left:
{Math.round(secondsRemaining / 60)} minutes!
div>
);
}
This is it. React The magic of , It can let us have JavaScript All capabilities of .
But there's a problem — We can't put any JavaScript Code . say concretely , We can only include expressions , It cannot include statements . Braces are essentially in our JSX Create an expression slot in .
If we try to insert a statement inside braces , for instance if/else sentence , We will get mistakes :
function CountdownClock({ secondsRemaining }) {
return (
// Grammatical errors
<div>
{if (secondsRemaining > 0) {
`${secondsRemaining} seconds left`
} else {
"Time expired!"
}}
div>
);
}
This is because statements do not produce values , Only expressions produce values . If we want to JSX Embedded in if/else Logic , We need to use a ternary operator expression :
function CountdownClock({ secondsRemaining }) {
return (
// That's all right.
<div>
{secondsRemaining > 0
? `${secondsRemaining} seconds left`
: "Time expired!"
}
div>
);
}
This seems to be a weird JSX/React Limit , But it is actually a JavaScript Limit .
I think we often blame React Some seemingly arbitrary rules of , For example, a component must return a top-level element . But more often ,React Just warning us about JavaScript The limitation of .
It is very important to understand the difference between statements and expressions . We also need to understand JSX How to compile into JavaScript Of , as well as React How does the scheduling and rendering cycle work … however , These topics are beyond the scope of this article .
summary
One JavaScript A program consists of a series of statements . Every statement is an instruction to do something , for instance , Create a variable , Run one if/else Conditional statements , Or start a cycle .
The expression produces a value , These values are placed in the slot of the statement . An expression is always part of a statement , Even if the statement is empty . for example , The following code does not use when running a loop for sentence , But it still contains a ” Transparent fresh-keeping film ” sentence :
data.forEach(item => console.log(item));
This difference may take some time to become obvious , I hope this article can help you .
That's all of this , Welcome to like collection and forward ~
Link to the original text :https://www.joshwcomeau.com/javascript/statements-vs-expressions/
author :Joshua Comeau
边栏推荐
- Zcmu--1771: looking for cute girls
- Flowable 结束事件EndEvent自定义属性
- MGRE comprehensive experiment
- ReentranLock及源码解析(学思想,一步一步点进源码)
- leetcode 301. 删除无效的括号
- MGRE and OSPF
- Ant begin opens PDF to add authentication parameter data
- 低 EMI、高性能4通道 LED 驱动器TPS61194PWPRQ1
- Interprocess communication - shared memory
- Leetcode-31-next spread
猜你喜欢
![[openfoam Pre - school Preparation 3 - install openfoam - V8]](/img/2a/29b7beadc9a8284a767e0369279af0.png)
[openfoam Pre - school Preparation 3 - install openfoam - V8]

Gavin wood, founder of Poka: what will happen to Poka governance V2?

【图表组件套件开发】上海道宁为开发人员提供Steema下载、试用、教程

Among the top 50 intelligent operation and maintenance enterprises in 2022, Borui data strength was selected

技术分享 | 使用 cURL 发送请求

Creative ribbon style landing page
![[Vuforia] 详解·高通Vuforia识别追踪3D物体/模型,Unity开发](/img/21/b47943605664473d5d6ad1578e9b9a.png)
[Vuforia] 详解·高通Vuforia识别追踪3D物体/模型,Unity开发

The relationship between reinforcement learning (Q-learning) and path search (a*)

面试题:谈谈你对AQS 的理解
![[openfoam pre school preparation 3 - install openfoam-v8]](/img/2a/29b7beadc9a8284a767e0369279af0.png)
[openfoam pre school preparation 3 - install openfoam-v8]
随机推荐
[Vuforia] 详解·高通Vuforia识别追踪3D物体/模型,Unity开发
Fade the background registration + login form page
10分钟带你进入Swagger的世界,快来看一看吧
gradle 打包排除依赖 排除文件
[Voforia] 通过识自己设定图片,显示特定AR模型
scroll-view 固定高度 实现触底效果
Flowable query the current user's to-do task method and report an error
非常全面的IReport的使用
Class的生命周期
Machine learning - matrix derivation basic formula + common formula
从源码探究双亲委派机制
[vuforia] some test records of vuforia plug-ins (3D object recognition and ground recognition)
盘点波卡生态潜力项目 | 跨链特性促进多赛道繁荣
【走进go的内心深处】
从源码学习线程池的使用原理及核心思想解析
在router中判断是pc还是移动端
Neural network loss and ACC drawing method plot
Blue Bridge Cup VIP question bank
现在网上开户安全么?想知道股票开账户如何优惠开户?
Trends in plant science | breeding in the direction of improving ecological plant microbiome interaction