[英]Is there any difference between defining and declaring variables in javascript?
It may seem very trivial issue but very confusing and recurring for me. 这似乎是很琐碎的问题,但对我来说却很混乱又反复出现。 In some manuals for javascript or tutorials these terms are used alternately. 在javascript或教程的某些手册中,这些术语是交替使用的。 In others I found the explanation that we declare variables when we create them with var
const
let
and we define variables, when we append some value/object to the declared variable as below: 在其他文章中,我找到了这样的解释:当我们使用var
const
let
创建变量时声明变量,并在将一些值/对象附加到声明的变量时定义变量,如下所示:
var name; //declaring
name = 'Adam' //defining
var age = 'dead' //declaring + defining
Are there any approved and correct rules of using these two terms? 是否有使用这两个术语的任何已批准且正确的规则?
I'd say that " variable definition " is not a standard JavaScript term. 我会说“ 变量定义 ”不是标准的JavaScript术语。
Functions (of all kinds) and object properties can get defined , but variables always get declared . 可以定义 (各种)函数和对象属性,但始终声明变量。 This terminology might hint at the declarative nature of variables - a declaration always applies to the complete current scope, it's not an action that gets executed and does something. 该术语可能暗示变量的声明性-声明始终适用于完整的当前作用域,它不是要执行并执行某些操作的动作。
var name
is a declaration. var name
是一个声明。 var age = 'dead'
is a declaration with an initialiser. var age = 'dead'
是带有初始化程序的声明。 name = 'Adam'
is just an assignment. name = 'Adam'
只是一个分配。 I'd guess that "defining" a variable refers to it no longer being undefined
, so both an assignment statement or the initialiser of the declaration might do that. 我猜想“定义”变量是指它不再是undefined
,因此赋值语句或声明的初始化程序都可以做到这一点。 I'd rather speak of the initialisation of the variable, though. 不过,我宁愿谈论变量的初始化 。
var x
is a declaration because you are not defining what value it holds but you are declaring its existence and the need for memory allocation. var x
是一个声明,因为您没有定义它拥有什么值,而是声明了它的存在以及内存分配的需要。
var x = 1
is both declaration and definition but are separated with x
being declared in the beginning while its definition comes at the line specified (variable assignments happen inline). var x = 1
既是声明又是定义,但是以x
开头分开,而x
的定义位于指定的行(变量赋值以内联方式发生)。
I see that you already understand the concept of hoisting
but for those that don't, Javascript takes every variable and function declaration and brings it to the top (of its corresponding scope) then trickles down assigning them in order. 我看到您已经了解了hoisting
的概念,但对于那些不了解的概念,Javascript接受每个变量和函数声明,并将其置于顶部(位于其相应范围内),然后按顺序向下分配它们。
You seem to know most of this already though. 您似乎已经了解了大部分。 Here's a great resource if you want some advanced, in-depth exploration. 如果您需要进行一些高级的深入研究,这是一个很好的资源。 Yet I have a feeling you've been there before. 但是我有一种感觉,你以前去过那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.