Scoped variables and constants

When we declare a variable, then it has a local scope and a global scope. We can define a variable anywhere in our script. When we declare a variable in JavaScript, we can assign a value to it at the time of declaration or later. Here is an example:

_xyz123; // variable declared without assigning a value to it
varabc = "Star"; //variable declared while assigning a value to it

In JavaScript, a variable is defined by a dollar sign the same as in query. In JavaScript, we create variables dynamically using the var keyword. Every variable has a name and a value associated with it. These values can be of any type, such as number, array, string, and so on. A variable name could be a combination of characters and numbers. Here is an example:

(a==undefined){
a=5}

A variable that is declared outside a function is a global variable having a global scope. This means that it can be accessed from anywhere within a script.

We can also declare a variable constant with the const keyword. A constant variable value is constant.

Constants can be defined using the const keyword as shown here:

Const a=5;

Note

The const and let keywords work in a similar way that they both are block scoped. However, in the case of const, values cannot be redeclared, redefined, or reinitialized. In short, const values are read-only.

Here is a working example:

const PI = 3.14159265359;

console.log("value of PI = " + PI); //value of PI = 3.14159265359

PI = 3.1415; //<------- Can not re-assign value to PI

console.log("value of PI = " + PI); //value of PI = 3.14159265359

const PI = 2.0312; //<------- Can not re-initialize value of PI

console.log("value of PI = " + PI); //Uncaught TypeError: Identifier 'PI' has already been declared

var PI = 9.2144; //<------- Can not re-declare value of PI

console.log("value of PI = " + PI); //Uncaught TypeError: Identifier 'PI' has already been declared.

The class variables are declared in the class but not within methods of any class, whereas the local variable exits within the methods of any class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.249.42