Javascript Variables

Gowtham
2 min readFeb 10, 2023

A variable in JavaScript is a named storage location for storing data values. It acts as a container for data in the code, allowing you to access and manipulate the data stored in it. Variables are declared with the keyword var, let, or const in JavaScript.

var is the traditional way of declaring variables in JavaScript and it has function-level scope. This means that a variable declared with var inside a function is accessible throughout the function, but it is not accessible outside the function.

let and const are more recent additions to JavaScript, and they have block-level scope. This means that a variable declared with let or const inside a block of code is only accessible within that block, and it is not accessible outside of that block.

The difference between let and const is that let allows you to reassign a new value to the variable, while const is used to declare a constant that cannot be reassigned.

<script>
var name = "John";
console.log(name); // Output: John

name = "Jane";
console.log(name); // Output: Jane

let age = 30;
console.log(age); // Output: 30

age = 31;
console.log(age); // Output: 31

const country = "USA";
console.log(country); // Output: USA

country = "Canada"; // Throws an error, as the value of a constant cannot be changed
</script>

javascript variable declaration

In JavaScript, there are some rules and conventions that you need to follow when naming variables:

  • Variable names can only contain letters, numbers, underscores, and dollar signs.
  • The first character of a variable name must be a letter, an underscore, or a dollar sign.
  • JavaScript is case-sensitive, so age and Age are two different variables.
  • JavaScript reserves some words as keywords, such as var, let, const, function, if, etc. These words cannot be used as variable names.
  • Variable names should be descriptive and meaningful, so that it’s easier to understand what the variable represents in the code.

Here are some examples of valid variable names:

<script>
var firstName;
let last_name;
const _salary;
var $income;
</script>

It’s a good practice to use camelCase or snake_case when naming variables in JavaScript. In camelCase, the first letter of each word is capitalized, except for the first word. In snake_case, words are separated by underscores.

<script>
var firstName;
let lastName;
const monthlyIncome;
var annual_salary;
</script>

By following these rules and conventions, you can make your code more readable, maintainable, and easier for others to understand.

check out my other blogs 👇

javascript comments

What is Hadoop

--

--