Javascript basics

Codynn
3 Min Read
Contents: Click for quick access

Comments

Comments in JavaScript can be used to explain and improve the readability of the code. In JavaScript, we can write a comment on a single line by using //. The JavaScript interpreter ignores everything after // because it’s not code.

There are two types of comments in JavaScript.

  1. Single-line Comment: It is represented by double forward slashes (//). It can be used before and after the statement. For example:

// comment on code

  1. Multi-line Comment: It is represented by forward slash with asterisk then asterisk with forward slash. For example:

/*  code  */  

Variable

Variables are nothing more than data storage containers (storing data values). In JavaScript, there are two different kinds of variables: local variables and global variables.

When declaring a JavaScript variable, there are some guidelines to follow 

  • A letter (a to z or A to Z), underscore(_), or dollar($) sign must begin the name.
  • We can put numerals (0 to 9) after the initial letter, for example value1.
  • Variables in JavaScript are case sensitive, so y and Y are two separate variables.

There are two major methods for declaring variables. The first method is to use const:

const b = 0

The second way is to use let:

let b = 0

The main difference between const and let is that const defines a constant reference to a value. This indicates that the reference cannot be altered. It is not possible to assign a new value to it.

Using let you can assign a new value to it.

For example, you cannot do this:

const a = 0

a = 1

Because you’ll get the following error: Assignment to a constant variable resulted in a TypeError variable.

On the other hand, you can do it using let:

let a = 0

a = 1

const does not mean “constant” in the sense that it does in other languages such as C. It doesn’t mean the value can’t change; rather, it indicates it can’t be reassigned.

When declaring const variables, value must be assigned

//correct

const PI = 3.141;

//incorrect

const PI;

PI = 3.141;

Var and Let

Var

var y = "pujan bhusal"; // String
var y = 0;    // number

We can update the value of var and redeclare it in the same scope. The scope of these variables refers to where they’re being used.

Let

let y = "pujan bhusal"; // String
let y = 0;       // number
// SyntaxError: 'y' has already been declared

 We can change their values, but unlike var, we can’t redeclare them in the same scope.

Share This Article
Leave a comment

Leave a Reply

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