Quick Tip: How to Declare Variables in Javascript
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.
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
var
has been available in JavaScript since its initial releast,let
andconst
are only available in ES6 (ES2015) and up. See this page for browser compatibility.
var
Syntax:
var x; // Declaration and initialization
x = "Hello World"; // Assignment
// Or all in one
var y = "Hello World";
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:
function sayHello(){
var hello = "Hello World";
return hello;
}
console.log(hello);
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:
var hello = "Hello World";
function sayHello(){
return hello;
}
console.log(hello);
let
Syntax:
Continue reading %Quick Tip: How to Declare Variables in Javascript%
LEAVE A REPLY
You must be logged in to post a comment.