Hot File

How to Declare Variables in Javascript

View: 218    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Javascript   Fields: Other

9 point/1 review File has been tested

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

Introduction

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

How to Declare Variables in Javascript Posted on 15-09-2016  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 9/10 218

Comment:

To comment you must be logged in members.

Files with category

  • JUnit 5 State Of The Union using java

    View: 471    Download: 0   Comment: 0   Author: none  

    JUnit 5 State Of The Union using java

    Category: Javascript
    Fields: Other

    4.5/1 review
    JUnit 5 has been under development for about 14 months now and the prototype is almost a year old. Time to summarize what happened so far, where the project stands, and where it’s going.

  • Getting Started with Dropwizard using java

    View: 542    Download: 0   Comment: 0   Author: none  

    Getting Started with Dropwizard using java

    Category: Javascript
    Fields: Other

    4.5/1 review
    Dropwizard is a framework for building RESTful web services in Java. In this tutorial we’re going to have a look at how to get started with developing a Dropwizard application by building a new service from scratch.

  • Build Query NULL Value in MySql

    View: 248    Download: 0   Comment: 0   Author: none  

    Build Query NULL Value in MySql

    Category: Javascript
    Fields: Other

    2.5/2 review
    Misunderstanding NULL is common mistake beginners do while writing MySql query. While quering in MySql they compare column name with NULL. In MySql NULL is nothing or in simple word it isUnknown Value so if you use comparison operator for NULL values...

  • Manage Your JavaScript Application State with MobX

    View: 255    Download: 0   Comment: 0   Author: none  

    Manage Your JavaScript Application State with MobX

    Category: Javascript
    Fields: Other

    2.25/2 review
    This article was peer reviewed by Michel Weststrate and Aaron Boyer. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

  • Build Bringing Pages to Life with the Web Animations API

    View: 263    Download: 0   Comment: 0   Author: none  

    Build Bringing Pages to Life with the Web Animations API

    Category: Javascript
    Fields: Other

    4.5/2 review
    This article is by guest author Dudley Storey. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • How to Style Google Custom Search Manually

    View: 237    Download: 0   Comment: 0   Author: none  

    How to Style Google Custom Search Manually

    Category: Javascript
    Fields: Other

    0/0 review
    Website owners very often decide on using Google’s Custom Search Engine (GCSE) for searching through their content instead of using built-in and/or custom search functionality. The reason is simple – it’s much less work, and most often it does the...

  • Test React Components Using Jest

    View: 4859    Download: 0   Comment: 0   Author: none  

    Test React Components Using Jest

    Category: Javascript
    Fields: Other

    4.5/1 review
    This article is by guest author Jack Franklin. SitePoint guest posts aim to bring you engaging content from prominent writers and speakers of the JavaScript community.

  • Programming Question Reverse String without using String function

    View: 641    Download: 0   Comment: 0   Author: none  

    Programming Question Reverse String without using String function

    Category: Javascript
    Fields: Other

    0/0 review
    Write a program to reverse string without using string function. You don’t have to use any in-built string library function. This problem can be solved by multiple approaches. Let’s check it.

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd