When learning JavaScript one of the basics is to understand how to use variables. Variables are containers for values of all possible types, e.g. number, string or array (see data types). Every variable gets a name that can later be used inside your application (e.g. to read its value).
In this quick tip you’ll learn how to use variables and the differences between the various declarations.
Key Takeaways
- Variables in JavaScript are declared using ‘var’, ‘let’, or ‘const’ keywords, each with its own scope and usage. ‘Var’ is function-scoped, ‘let’ is block-scoped, and ‘const’ is block-scoped but cannot be reassigned after initialization.
- Declaration, initialization, and assignment are three different steps in variable usage. Declaration introduces a new variable, initialization assigns a value for the first time, and assignment gives a specific value to the variable.
- Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope during the compile phase. However, only the declarations are hoisted, not initializations. ‘Var’ returns ‘undefined’ if accessed before declaration due to hoisting, while ‘let’ and ‘const’ throw an error.
Difference between Declaration, Initialization and Assignment
Before we start learning the various declarations, lets look at the lifecycle of a variable.
- Declaration: The variable is registered using a given name within the corresponding scope (explained below – e.g. inside a function).
- Initialization: When you declare a variable it is automatically initialized, which means memory is allocated for the variable by the JavaScript engine.
- Assignment: This is when a specific value is assigned to the variable.
Declaration Types
Note: while varhas been available in JavaScript since its initial releast, letand const are only available in ES6 (ES2015) and up. See this page for browser compatibility.
var
Syntax:
<span>var x; // Declaration and initialization </span>x <span>= "Hello World"; // Assignment </span> <span>// Or all in one </span><span>var y = "Hello World"; </span>
This declaration is probably the most popular, as there was no alternative until ECMAScript 6. Variables declared with var are available in the scope of the enclosing function. If there is no enclosing function, they are available globally.
Example:
<span>function sayHello(){ </span> <span>var hello = "Hello World"; </span> <span>return hello; </span><span>} </span><span>console.log(hello); </span>
This will cause an error ReferenceError: hello is not defined, as the variable hello is only available within the function sayHello. But the following will work, as the variable will be declared globally – in the same scope console.log(hello) is located:
<span>var hello = "Hello World"; </span><span>function sayHello(){ </span> <span>return hello; </span><span>} </span><span>console.log(hello); </span>
let
Syntax:
<span>var x; // Declaration and initialization </span>x <span>= "Hello World"; // Assignment </span> <span>// Or all in one </span><span>var y = "Hello World"; </span>
let is the descendant of var in modern JavaScript. Its scope is not only limited to the enclosing function, but also to its enclosing block statement. A block statement is everything inside { and }, (e.g. an if condition or loop). The benefit of let is it reduces the possibility of errors, as variables are only available within a smaller scope.
Example:
<span>function sayHello(){ </span> <span>var hello = "Hello World"; </span> <span>return hello; </span><span>} </span><span>console.log(hello); </span>
This will cause an error ReferenceError: hello is not defined as hello is only available inside the enclosing block – in this case the if condition. But the following will work:
<span>var hello = "Hello World"; </span><span>function sayHello(){ </span> <span>return hello; </span><span>} </span><span>console.log(hello); </span>
const
Syntax:
<span>let x; // Declaration and initialization </span>x <span>= "Hello World"; // Assignment </span> <span>// Or all in one </span><span>let y = "Hello World"; </span>
Technically a constant isn’t a variable. The particularity of a constant is that you need to assign a value when declaring it and there is no way to reassign it. A const is limited to the scope of the enclosing block, like let.
Constants should be used whenever a value must not change during the applications running time, as you’ll be notified by an error when trying to overwrite them.
Accidental Global Creation
You can write all of above named declarations in the global context (i.e. outside of any function), but even within a function, if you forget to write var, let or const before an assignment, the variable will automatically be global.
Example:
<span>var name = "Peter"; </span><span>if(name === "Peter"){ </span> <span>let hello = "Hello Peter"; </span><span>} else { </span> <span>let hello = "Hi"; </span><span>} </span><span>console.log(hello); </span>
The above will output Hello World to the console, as there is no declaration before the assignment hello = and therefore the variable is globally available.
Note: To avoid accidentally declaring global variables you can use strict mode.
Hoisting and the Temporal Dead Zone
Another difference between var and let/const relates to variable hoisting. A variable declaration will always internally be hoisted (moved) to the top of the current scope. This means the following:
<span>var name = "Peter"; </span><span>if(name === "Peter"){ </span> <span>let hello = "Hello Peter"; </span> <span>console.log(hello); </span><span>} else { </span> <span>let hello = "Hi"; </span> <span>console.log(hello); </span><span>} </span>
is equivalent to:
<span>const x = "Hello World"; </span>
An indication of this behavior is that both examples will log undefined to the console. If var hello; wouldn’t always be on the top it would throw a ReferenceError.
This behavior called hoisting applies to var and also to let/const. As mentioned above, accessing a var variable before its declaration will return undefined as this is the value JavaScript assigns when initializing it.
But accessing a let/const variable before its declaration will throw an error. This is due to the fact that they aren’t accessible before their declaration in the code. The period between entering the variable’s scope and reaching their declaration is called the Temporal Dead Zone – i.e. the period in which the variable isn’t accessible.
You can read more about hoisting in the article Demystifying JavaScript Variable Scope and Hoisting.
Conclusion
To reduce susceptibility to errors you should use const and let whenever possible. If you really need to use var then be sure to move declarations to the top of the scope, as this avoids unwanted behavior related to hoisting.
Frequently Asked Questions (FAQs) about JavaScript Variable Declaration
What is the difference between variable declaration and initialization in JavaScript?
In JavaScript, variable declaration and initialization are two distinct steps in the process of using variables. Declaration is the process of introducing a new variable to the program. It’s done using the var, let, or const keywords. For example, let x; Here, x is declared but not defined. It’s like telling the program, “Hey, I’m going to use a variable named x.” Initialization, on the other hand, is the process of assigning a value to the declared variable for the first time. For example, x = 5; Here, x is initialized with the value 5. It’s like telling the program, “The variable x I told you about earlier? It’s value is 5.”
Can I declare a variable without initializing it in JavaScript?
Yes, in JavaScript, you can declare a variable without initializing it. When you declare a variable without assigning a value to it, JavaScript automatically assigns it the value of undefined. For example, if you declare a variable like this: let x; and then try to log x to the console, you’ll get undefined because x has been declared but not initialized.
What happens if I use a variable without declaring it in JavaScript?
In JavaScript, if you use a variable without declaring it first, you’ll get a ReferenceError. This is because JavaScript needs to know about a variable before it can be used. If you try to use a variable that hasn’t been declared, JavaScript doesn’t know what you’re referring to and throws an error. For example, if you try to log x to the console without declaring x first, you’ll get a ReferenceError: x is not defined.
What is the difference between var, let, and const in JavaScript variable declaration?
In JavaScript, var, let, and const are all used to declare variables, but they have different behaviors. var is function-scoped, meaning a variable declared with var is available within the function it’s declared in. let and const are block-scoped, meaning they’re only available within the block they’re declared in. Additionally, const is used to declare constants, or variables that can’t be reassigned after they’re initialized.
Can I redeclare a variable in JavaScript?
In JavaScript, whether you can redeclare a variable depends on how you initially declared it. If you declared a variable with var, you can redeclare it. However, if you declared a variable with let or const, you can’t redeclare it within the same scope. Attempting to do so will result in a SyntaxError.
What is hoisting in JavaScript?
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This means that you can use variables and functions before they’re declared. However, only the declarations are hoisted, not initializations. If a variable is declared and initialized after using it, the variable will be undefined.
What is the scope of a variable in JavaScript?
The scope of a variable in JavaScript determines where that variable can be accessed from within your code. Variables declared with var have function scope, meaning they can be accessed anywhere within the function they’re declared in. Variables declared with let and const have block scope, meaning they can only be accessed within the block they’re declared in.
What is the difference between null and undefined in JavaScript?
In JavaScript, null and undefined are both special values that represent the absence of a value. However, they’re used in slightly different ways. undefined is the value assigned to a variable that has been declared but not initialized. null, on the other hand, is a value that represents no value or no object. It needs to be assigned to a variable explicitly.
Can I use special characters in variable names in JavaScript?
In JavaScript, variable names can include letters, digits, underscores, and dollar signs. They must begin with a letter, underscore, or dollar sign. Special characters like !, @, #, %, etc., are not allowed in variable names.
What is a global variable in JavaScript?
A global variable in JavaScript is a variable that’s declared outside of any function or block. Because it’s not tied to a function or block, a global variable can be accessed from anywhere in your code. However, global variables can lead to issues with naming conflicts and are generally best avoided when possible.
The above is the detailed content of Quick Tip: How to Declare Variables in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Linux new version
SublimeText3 Linux latest version

Zend Studio 13.0.1
Powerful PHP integrated development environment