June 24, 2021

TriStudy

TriStudy Provide Free Online Tutorials about Programming languages,Digital Marketing, web designing, online earning, web hosting, WordPress etc

Learn Java Variables and Types Part 2

All the variable is defined using the keyword and can contain all types of variables. a variable can hold value with any type of data. A variable is just a named placeholder for a value.

Declare JavaScript variables using var keyword

To declare a variable, var is used to define it, you use the var keyword followed by the variable name as follows:

1var foo;

A variable name can be any valid identifier. The foo the variable is declared and hold a special value undefined.

After declaring a variable, you can assign the variable value as follows:

1foo = “Hello”;

To declare a variable and initialize it at the same time, you use the following syntax:

1var variable_name = value;

For example, the following statement declares the foo variable and assign it a value "Hello"

1var foo = “Hello”;

You can declare two or more variables using one statement, each variable declaration is separated by a comma (,) as follows:

12var foo = “Hello”,    bar = 100;

As mentioned earlier, you can store a number in the foo variable as the following example though it is not recommended.

1foo = 100;

Undefined vs. undeclared variables

It’s important to distinguish between undefined and undeclared variables.

An undefined variable is a variable that has been declared. Because we have not assigned it a value, the variable used the as undifined its initial value. In contrast, an undeclared variable is the one that has not been declared in the accessible scope.

See the following script.

1234var foo; 
console.log(foo); // undefined
console.log(bar); // ReferenceError: bar is not defined

The foo variable is declared but not initialized therefore its value is undefined whereas the bar variable has not been declared hence accessing it causes a ReferenceError.

Global and local variables

In JavaScript, you define a function as follows:

123function function_name() {  // logic}

and call the function using the following syntax:

1function_name();

You will learn more about function in more detail in function tutorial.

The following example defines a function named say that has a local variable named message.

123function say() {  var message = “Hi”;}

The message variable is a local variable. In other words, it only exists inside the function. If you try to access it outside the function as follows:

1234function say() {    var message = ‘Hi’;}console.log(message); // ReferenceError

You will get a ReferenceError because the message variable was not defined.

Variable shadowing

See the following example.

123456789// global variablevar message = “Hello”;function say() {    // local variable    var message = ‘Hi’;    console.log(message); // which message?}say();// Hiconsole.log(message); // Hello

In this example, we have two variables that share the same name: message. The first message variable is a global variable whereas the second one is the local variable.

Inside the say() function, the global message variable is shadowed. It cannot be accessible inside the say() function but outside of the function. This is called variable shadowing.

Accessing global variable inside the function

See the following example.

123456789// global variablevar message = “Hello”;function say() {    // local variable    message = ‘Hi’;    console.log(message); // which message?}say();// Hiconsole.log(message); // Hi

In this example, we define a global variable named message. In the say() function, we reference the global message variable by omitting the var keyword and change its value to a string of Hi.

Although it is possible to refer to a global variable inside a function, it is not recommended. This is because the global variables are very difficult to maintain and potentially cause much confusion.

Non-strict mode

The following example defines a function and declares a variable message. However, the var keyword is not used.

123456function say() {    message = ‘Hi’; // what?    console.log(message);}say(); // Hiconsole.log(message); // Hi

When you execute the script, it outputs the  Hi string twice in the web console.

Why?

strict mode

To avoid creating a global variable accidentally inside the function because of omitting the var keyword, you use the strict mode by adding the "use strict"; at the beginning of a JavaScript file (or a function) as follows:

12345678“use strict”; function say() {    message = ‘Hi’; // ReferenceError    console.log(message);}say(); // Hiconsole.log(message); // Hi

From now on, you should always use the strict mode in your JavaScript code to eliminate some JavaScript silent errors and make your code run faster.

JavaScript variable hoisting

Hoisting is a mechanism that JavaScript engine moves all the variable declarations to the top of their scope, either function or global scope.

If you declare a variable with the var keyword, the variable is hoisted to the top of its enclosing scope. As a result, if you access a variable before declaring it, the variable evaluates to undefined.

See the following example.

12console.log(foo); // undefined var foo;

JavaScript engines move the declaration of the foo variable to the top, so it is equivalent to the following script.

12var foo;console.log(foo); // undefined

If there were no hoisting, you would get a ReferenceError because you referenced to a variable that was not defined.

See another example.

12console.log(baz);var baz = ‘baz’;

JavaScript engine moves only the declaration of the variables to the top. However, it keeps the initial assignment of the variable remains intact. As a result, the code above is equivalent to the following:

123var baz;console.log(baz); // undefinedbaz = ‘baz’;

Using let and const keywords

From ES6, you can use the let keyword to declare a variable. The let the keyword is similar to the var keyword. However, the variable declared using the let the keyword is block-scoped, not function-scoped.

In the following example, we declare the tmp variable within a block surrounding by the curly braces {}. The  tmp variable only exists inside the block, therefore, any reference to it outside of the block will cause a ReferenceError.

123456789var foo = 20, bar = 10; {    let tmp = foo;    foo = bar;    bar = tmp;} console.log(tmp); // ReferenceError

The const keyword works like the let keyword, but the variable that you declare must be initialized immediately with a value, and that value can’t be changed afterward.

12const CODE = 100;CODE = 200; // TypeError: `CODE` is read-only

When a variable is used without first defining a value for it, it is equal to undefined. For example:

var newVariable;
console.log(newVariable); //prints undefined

However, the null value is a different type of value and is used when a variable should be marked as empty. undefined can be used for this purpose, but it should not be used.

var emptyVariable = null;
console.log(emptyVariable);