DEV Community

Devi
Devi

Posted on

JavaScript variables and scope

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:

  1. 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.

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

  3. Reserved keywords must not be used as identifiers.

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

  5. When using strict mode, certain keywords are also restricted.

  6. Avoid using future reserved words.

  7. Other reserved words should be avoided as well.

Variables and Scope

  1. 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;

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay