Hey curious reader :) I am back with third tutorial on JavaScript.In this post we will see how comments are used and how variables are declared in JavaScript so let's get started .
1. Comments in JavaScript -:
First of all let me explain what comments exactly are -:
Comments are meaningful information or messages about code that we use enhance readability of code. We don't want these to be executed along with our code.
There are two types of comments in JavaScript -:
- Single line comments -> These are represented by double slash.
So here as you can lines apart from comments executed successfully.
- Multi line Comment -> It can be used to add single as well as multi line comments. So, it is more convenient. It is represented by forward slash with asterisk then asterisk with forward slash.
2. Variable Declaration -:
First of all let's understand what variables are-:
Variable is a symbolic name for a value.
Variables are used to store data that can be referenced and manipulated in a program.
In JavaScript we can declare variables in three ways ->
Using
var
keywordUsing
let
keywordUsing
const
keyword
Let's see each of the declaration seperately.
Using var
keyword
Declaring variables with var
keyword is traditional in JavaScript. These are basically function scoped or global scoped. Now let's understand what this function and global scoped means.
As you can see in above image we have created a function and declared a variable Name
with var
keyword and used within it and it works perfectly fine, but as soon as, we tried using it outside the function an error is generated. So this clearly specifies that Name
variable is accessible within function but it is not accessible outside it.
Now here as we have declared Name
globally it is accessible in whole program.
Using let
keyword
Introduced in ECMAScript 2015 (ES6), let allows you to declare block-scoped variables.
Now you may be thinking that "Aren't var
and let
same? What's the difference between them?"
No they aren't same, let
is block scoped whereas var
is function scoped.
So here as you can see declaring a
let
in block will allow us to use it within that block only, outside of it we can't use it but that's not the case forvar
.
We can redeclare variables with
var
keyword but we cannot do so withlet
keyword.
Using const
keyword
Also introduced in ECMAScript 2015 (ES6), const allows you to declare constants, which are block-scoped like variables declared with let. The value of a constant cannot be reassigned once it is initialized. However, if the constant holds an object or array, the properties or elements of the object or array can still be mutated.
So this is it for this post. I hope you have understood that how declaration is done in JavaScript and how comments are used. In the next post we will see data types. Till then stay connected and don't forget to follow me :)
Top comments (3)
keep learning !
Wow so grateful
Wow great Akshat 😊