JavaScript variables and scope

Rmag Breaking News

JavaScript Identifiers

In JavaScript, we can assign names to functions, variables, and objects. These names are used to reference and utilize the specific function, variable, or object.

Just as we all have names to identify us, functions, variables, and objects in JavaScript have unique names. These are called identifiers.

Rules for Identifiers:

Within a scope, the variable name must be unique. This applies to both block scope and global scope. If the same name is given to multiple variables, the most recently assigned value will be used.

Identifiers should start with an uppercase letter, lowercase letter, underscore, or dollar sign. This rule applies only to the first letter of an identifier.

Reserved keywords must not be used as identifiers.

Identifiers are case-sensitive: ‘helloWorld’ and ‘HelloWorld’ are different.

When using strict mode, certain keywords are also restricted.

Avoid using future reserved words.

Other reserved words should be avoided as well.

Variables and Scope

Any type of variable can be used; once it’s assigned, we can change the type of variable anywhere in the code.

To declare a variable, name it (using var, let, or const), and initialize it using the assignment operator:

var name = “Devi”;

=>The variable name should start with an uppercase letter, lowercase letter, underscore, or dollar sign. This rule applies only to the first letter of an identifier.

=> There should be no space within a single variable name (to avoid an ‘unexpected identifier’ syntax error).

=>While non-Latin words can be used, it’s best to avoid them.

=>Multiple variables can be declared using a single statement

var car = “Audi”, name = “Devi”;
We can reassign any type of value to a variable declared with let:
JavaScript

let a = 100;
a = “hello”;
a = { name: “Devi”, dept: “ECE” };
It’s possible to reference a variable before it’s declared:
JavaScript

name = “Devi”;
console.log(name); // Outputs: Devi
var name;
However, in strict mode, this will not work due to hoisting.

Hoisting
JavaScript moves variable declarations to the top of the code, which prevents errors from occurring when a variable is used before it’s declared:

JavaScript

name = “Devi”;
console.log(name);
var name;

Leave a Reply

Your email address will not be published. Required fields are marked *