Loading...

How to Declare Variables in Javascript

View: 419    Dowload: 0   Comment: 0   Post by: hanhga   Category: Javascript   Fields: Other

This article was peer reviewed by Mark Brown and Mev-Rael. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

 

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.

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 scopeconsole.log(hello) is located:

var hello = "Hello World";
function sayHello(){
  return hello;
}
console.log(hello);

let

Syntax:

let x; // Declaration and initialization
x = "Hello World"; // Assignment

// Or all in one
let y = "Hello World";

et 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:

var name = "Peter";
if(name === "Peter"){
  let hello = "Hello Peter";
} else {
  let hello = "Hi";
}
console.log(hello);

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:

var name = "Peter";
if(name === "Peter"){
  let hello = "Hello Peter";
  console.log(hello);
} else {
  let hello = "Hi";
  console.log(hello);
}

const

Syntax:

const x = "Hello World";

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 varlet or const before an assignment, the variable will automatically be global.

Example:

function sayHello(){
  hello = "Hello World";
  return hello;
}
sayHello();
console.log(hello);

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.

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:

console.log(hello);
var hello;
hello = "I'm a variable";

is equivalent to:

var hello;
console.log(hello);
hello = "I'm a variable";

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.

How to Declare Variables in Javascript

This article was peer reviewed by Mark Brown and Mev-Rael. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be

Posted on 15-09-2016 

Comment:

To comment you must be logged in members.

Files with category

  • Mini Youtube Using ReactJS

    Mini Youtube Using ReactJS

    View: 25    Download: 2   Comment: 0

    Category: Javascript     Fields: none

    This is one the best starter for ReactJS. MiniYoutube as the name suggests is a youtube like website developed using reactJS and youtube API. This project actually let's you search , play and list youtube videos. Do check it out and start learning...

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 62    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 26    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 37    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 204    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 168    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 157    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 169    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that...

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd