Skip to main content

Command Palette

Search for a command to run...

Variables in JavaScript # 02

Updated
2 min read
Variables in JavaScript  # 02
I

I am a versatile developer skilled in web development and data science. My expertise includes HTML, CSS, JavaScript, TypeScript, React, Python, Django, Machine Learning, and Data Analysis. I am currently expanding my knowledge in Java and its applications in software development and data science. My diverse skill set enables me to create dynamic web applications and extract meaningful insights from data, driving innovative solutions.

A JavaScript variable is simply a container for a value that can be changed later on.
In JavaScript, we declare a variable and we do so with the use of keywords var, let and const .

Let's discuss each of the keywords.

1. let keyword :

The let keyword allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used. It cannot redeclare a variable.

2. var keyword :

The var keyword allows you to declare a variable globally, or locally to an entire function regardless of block scope. We can redeclare a variable with the use of the var keyword.

3. const keyword :

The const keyword creates block-scoped constants, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment and it can't be redeclared.

Note : let and const are both relatively new ways to declare variables in JavaScript.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

Assigning Values To JavaScript Variable

After the declaration, the variable has no value
(technically it is undefined).

To assign a value to the variable, use the equal sign '='.

Naming Of JavaScript Variables

The general rules for constructing names for variables (unique identifiers) are:

  1. Names can contain letters, digits, underscores, and dollar signs.

  2. Names must begin with a letter.

  3. Names can also begin with $ and _.

  4. Names are case-sensitive.

  5. Reserved words (like JavaScript keywords) cannot be used as names.

    Note :

    Difference between let keyword and var keyword.

    In most cases var and let behave the same way, but sometimes the behaviour of var is not what you would expect.

    1. var variables have no block scope, their visibility is scoped to the current function, or global if declared outside the function.

    2. var declarations are processed at function start (script start for globals).

If you liked this article, consider following me on Hashnode for my latest publications.