惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
WordPress大学
WordPress大学
T
The Exploit Database - CXSecurity.com
博客园_首页
MyScale Blog
MyScale Blog
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
F
Full Disclosure
V
V2EX
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Martin Fowler
Martin Fowler
PCI Perspectives
PCI Perspectives
S
Security @ Cisco Blogs
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
Microsoft Azure Blog
Microsoft Azure Blog
K
Kaspersky official blog
G
GRAHAM CLULEY
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
Tor Project blog
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
A Simple Explanation of JavaScript Variables: const, let, var
Dmitri Pavlutin · 2021-06-16 · via Dmitri Pavlutin Blog

A variable is just a holder of a value, like a box holding an item.

In JavaScript, you can create 3 types of variables: using const, let, and var statements. Each variable type has different behavior regarding the declaration, initialization, value access, and assignment steps.

This post will help you solidify your knowledge of JavaScript variables.

Let's get started.

1. Variable identifier

First, let's see what a variable is and how it's identified.

In simple terms, a variable is a placeholder (or a box) for a value. A value in JavaScript can be either a primitive or an object.

JavaScript variable is like a box

The variable has a name, which stricter is called identifier. Examples of variable identifiers are myNumber, name, list, item.

The syntax of an identifier is pretty simple:

An identifier can contain letters, digits 0..9, and special symbols $, _. An identifier cannot start with a digit 0..9.

Examples of valid identifiers are myNumber, my_number, list1, $item, _name, a, b, $, _.

Examples of invalid identifiers are 1number (incorrectly starts with the digit 1), my-number (the symbol - is not allow in an identifier), function (the identifier cannot be a keyword).

Finally,

JavaScript identifiers are case sensitive.

For example, the identifiers myNumber and mynumber are different, because the letter n has different cases in the identifiers (N vs n).

Having that, now let's see the 3 ways you can declare variables in JavaScript: const, let, and var statements.

2. const variables

2.1 const declaration and initialization

Here's how you can declare a const variable with the identifier myConstVariable:


const myConstVariable = initialValue;


The variable myConstVariable is initialized right away with an initialValue, which can be any expression that evaluates to a value.

Examples of initial values are literals (numbers 1, strings 'My Initial Value'), other variables, function calls.

For example the statement:

Declares a const variable with the identifier hero initialized with the string literal 'Batman'.

What's also specific to const variables (contrary to let and var variables described below) is that you have to assign the initial value:


const hero; // SyntaxError: Missing initializer in const declaration


2.2 const access and assignment

After the declaration and initialization, you can access the variable value just by using its name (aka identifier):


const hero = 'Batman';

console.log(hero); // logs 'Batman'

console.log(`Hello, ${hero}!`); // logs 'Hello, Batman!'


What distinguishes const variables from let and var is that you cannot assign a new value to a const variable:


const hero = 'Batman';

hero = 'Joker'; // TypeError: Assignment to constant variable


The code block and a function body create a scope for const variables. The concept of scope defines the limits where the variable is accessible.

In the example below hero variable is declared within the scope of the if conditional block. Thus, you can access hero only within that block, but not outside:


if (true) {

// Code block scope

const hero = 'Batman';

console.log(hero); // logs 'Batman'

}

console.log(hero); // throws ReferenceError


Same way hero is declared inside the scope of the greetBatman() function:


function greetBatman() {

// Function scope

const hero = 'Batman';

console.log(`Hello, ${hero}!`); // logs 'Hello, Batman!'

}

console.log(`Hello, ${hero}!`); // throws ReferenceError

greetBatman();


On top of that, you can also access the const variable value only after the declaration statement, but not before:


console.log(hero); // throws ReferenceError

const hero = 'Batman';


From the usage perspective, you should use const variables as read-only that you don't plan to reassign.

3. let variables

3.1 let declaration and initialization

Here's how you can declare a let variables with the identifiers myVariable1 and myVariable2:


let myVariable1 = initialValue;

// or

let myVariable2;


The variable myVariable1 is declared and initialized right away with an initialValue.

The variable myVariable2 is declared, however doesn't have an initial value. By default, JavaScript considers uninitialized variables having the special value undefined.

In the following code snippet:


let villain = 'Joker';

let name;


The let variable named villain is declared and initialized with the string literal 'Joker'. name variable also has been defined, but it wasn't initialized.

3.2 let access and assignment

After the declaration and initialization, you can access the let variable value just by writing the identifier:


let villain = 'Joker';

console.log(villain); // logs 'Joker'

console.log(`Hello, ${villain}!`); // logs 'Hello, Joker!'

let name;

console.log(name); // logs undefined


name variable, while being declared, isn't initialized so it has an undefined value.

You can easily update the value of a let variable, a thing you cannot do with const variables - and that's the main difference between them.


let villain = 'Joker';

villain = 'Bane';

console.log(villain); // logs 'Bane'


The scope of the let variables is defined the same way as for const: by a code block or function body.


if (true) {

// Code block scope

let villain = 'Joker';

console.log(villain); // logs 'Joker'

}

console.log(villain); // throws ReferenceError



function greetJoker() {

// Function scope

let villain = 'Joker';

console.log(`Hello, ${villain}!`); // logs 'Hello, Joker!'

}

console.log(`Hello, ${villain}!`); // throws ReferenceError

greetJoker();


Same as with const, you cannot access a let variable before the declaration statement:


console.log(villain); // throws ReferenceError

let villain = 'Joker';


4. var variables

4.1 var declaration and initialization

Here's how you can declare a var variable with the identifier myVariable1 or myVariable2:


var myVariable1 = initialValue;

// or

var myVariable2;


The variable myVariable1 is declared and initialized right away with an initialValue, which can be any kind of expression: literal, function call, etc.

The variable myVariable2 is declared, however doesn't have an initial value. By default, JavaScript considers uninitialized variables as having the special value undefined.

In the following code snippet:


var city = 'Gotham';

var name;


The var variable city is declared and initialized with the string literal 'Gotham'. name variable also has been defined, but it wasn't initialized.

4.2 var access and assignment

After the declaration and optional initialization, you can access the var variable value just by using its name (or identifier):


var city = 'Gotham';

console.log(city); // logs 'Gotham'

console.log(`Welcome to ${city}!`); // logs 'Welcome to Gotham!'

var name;

console.log(name); // logs undefined


name variable, while being declared, it is not yet initialized so it has an undefined value.

Same as with let variables, you can easily reassign var variables:


var city = 'Gotham';

city = 'New York';

console.log(city); // logs 'New York'


In contrast to const and let, the scope of the var variables is defined only by the function body:


function welcomeTo() {

// Function scope

var city = 'Gotham';

console.log(`Welcome to ${city}!`); // logs 'Welcome to Gotham!'

}

console.log(`Welcome to ${city}!`); // throws ReferenceError

welcomeTo();


A code block doesn't create a scope for var variables:


if (true) {

// Code block scope

var city = 'Gotham';

console.log(city); // logs 'Gotham'

}

console.log(city); // logs 'Gotham'


Normally, you won't access a var variable before the declaration statement. But if you do, JavaScript won't throw a reference error, but rather evaluate the variable to undefined:


console.log(city); // logs undefined

var city = 'Gotham';


It happens because a var variables hoists up to the top of the scope.

5. Conclusion

There are 3 ways to declare variables in JavaScript: using const, let, or var statements.

Specific to const variable is that you have to initialize the variable with an initial value. Also, the const variable cannot be reassigned.

let, on the other side, can be declared with or without an initial value. Also let variable value can be updated.

var variables behave almost as let variables: can be initialized or not, as well can be reassigned. However, contrary to let and const, only the function body creates a scope for var variables.

Side challenge: what happens if you assign a value to a non-existing variable nonExisting = 'hello'?