Javascript variables var, const, let

published on: | by cindy In category: Python

There are some pieces of information that you may need to reference multiple times in your code. Instead of repeating the same block of code multiple times, store the information in a container and give it a name. In programming, that container is a variable

A variable is a memory location that contains data and can be of any data type. These data can be accessed and modified during code execution. To change the values of a variable, simply assign it new values.

In real life, a container can be of any size depending on the size of its content. Think of a box of chocolates, a box of pizza, a bottle of milk, etc.

How do I Declare variables?

A variable declaration simply means creating a variable. In javascript, you declare a variable using the keyword let, var or const followed by the variable name.

let revenueCollected;

Initializing Variables

After variable declaration, we assign it an initial value, this process is called initialization Simply add the assignment operator "=". and give it a value of any data types i.e string, int, number, etc.

let numberOfDogs= 2     // holds the value 2 of int type
let studentName= "kamau kabue" // contains a string
const companyName = "Oark";
var itemsInStock = 100;

Before we dive deeper, let's learn how to name variables

Naming Variables

Variable are identifiers and javascript has rules on how to name them

  1. A variable name can consist of letters and numbers, but they cannot include any symbol outside of $ and _
  2. A variable name cannot begin with a number.
  3. A variable name is case sensitive .studentName and studentname would refer to two distinct variables.
  4. you cannot use reserved keywords as variables names

There are a few guidelines for naming a variable. These are good practices that make your code readable

Follow a common naming convention such as camel case. If it's just one-word start with a small letter.

Give your variables descriptive names. For example, if you want to describe a patients name instead of something like myName use a name that gives a clue for example patientName

It's good practice to spell out the names instead of using abbreviations

Hoisting

Hoisting is a javascript behavior of lifting variable declarations and function declaration, to the top of the current scope before execution. The current scope could be local or global.

video from udacity simulates hoisting

This ability enables javascript to use variables before they are declared.

Huh? let me illustrate

studentName = ‘Cindy ’;  //asign cindy to studentName
console.log(studentName);
var studentName; //declare student name
var studentName = ‘Cindy ’; //declare student name and asign it the value cindy 
console.log(studentName);

The above examples will have the same output: Cindy

Are initialization hoisted as well?

We have to find out. Check out the examples below and find out the output

    console.log(studentName);
    var studentName = "Charles kabue"; 

What is the output

  1. Undefined
  2. RefferenceError
  3. Charles Kabui

If you guessed the first choice, you got it right. Javascript allows us to use variables before they are declared because of hoisting.

Be careful though because initializations are not hoisted, they remain in place. Only the variable name is hoisted

But why on earth is the output undefined? Hoisted variables are initialized with undefined value if we do not initialize it.

var a = 4; // Initialize a
var b = 4; // Initialize b
console.log(a + b); // output 44


var a = 4; // Initialize a
console.log(a  + b); // output 4 and undefined
var b = 4; // Initialize b

what are the differences between var, const and let?

Wait, what on earth is var, let and const?

previously Before Es6, the only way to declare variables was by using the var keyword. With es6 let and const was introduced. But why introduce new keywords? was var inefficient?

Variables declared with the let and const keywords can have a Block (denoted by curly braces { }) Scope which was not an option Previously. If variables are declared inside a block of code, they are bound to the block which they are declared and cannot be accessed outside that block. They are said to be in *Temporal dead zone * until execution reaches declaration. This behavior prevents variables from being accessed only until after they’ve been declared.

Const

Must be declared and initialized before use.use const keyword then followed by the name.

   const comapyName= "Oark"  //correct

If you are keen enough you must have noticed that I declared and initialized the variable. Const MUST be initialized otherwise it will throw an error.

const comapyName; // SyntaxError: missing initializer

A good place for using will be the number of months in a year, the number of hours in a day, a company name.

When declaring a variable with const the value of that variable won't be modified at any point while the program is running.

 const companyName= "Oark"
 companyName = "zain"; // Uncaught TypeError: Assignment to constant variable.

However, if you declare an object as const, you are able to change the properties.

const animal = {};
animal.colorOfEyes = "blue'; //no error

let

Let is a block scoped and generally, use let in the case of loops and reassignment

Var

Can I still use var? Yes, but why use it when let and const are available?

summary

Keyword Var Let Const
redeclared yes no no
Re-assigned yes yes no
scope Function scope Block Scoped Block scoped
Hoisting yes no no