1. Home
  2. Docs
  3. Scripting Language
  4. Client Side Scripting
  5. Basic JavaScript

Basic JavaScript

Literals

A literal is a data value that appears directly in a program. The following are all literals:

12 // The number twelve
1.2// The number one point two
"hello world" // A string of text
'Hi' // Another string
true or false // A Boolean value
null // Absence of an object

Reserved Words

The following words are part of the JavaScript language. Many of these (such as if, while, and for) are reserved keywords that must not be used as the names of constants, variables, functions, or classes (though they can all be used as the names of properties within an object). Others (such as from, of, get, and set) are used in limited contexts with no syntactic ambiguity and are perfectly legal as identifiers. Still other keywords (such as let) can’t be fully reserved in order to retain backward compatibility with older programs, and so there are complex rules that govern when they can be used as identifiers and when they cannot. (let can be used as a variable name if declared with var outside of a class, for example, but not if declared inside a class or with const.) The simplest course is to avoid using any of these words as identifiers, except for from, set, and target, which are safe to use and are already in common use.

as const export get null target void
async continue extends if of this while
await debugger false import return throw
with break default finally in set true yield
case delete for instanceof static try catch
do from let super typeof class else function
new switch var

Variable Declaration in JavaScript

Identifiers

An identifier is simply a name. In JavaScript, identifiers are used to name constants, variables, properties, functions, and classes and to provide labels for certain loops in JavaScript code.

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

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (y and Y are different variables)
  • Reserved words (like JavaScript keywords) cannot be used as names

There are 4 ways to declare a variable

  • Using Nothing
  • Using ‘var’
  • Using ‘let’
  • Using ‘const’

The ‘var’ keyword is used in all JavaScript code from 1995 to 2015. The ‘let’ and ‘const’ were later added. When we want to change the value of a variable we use ‘var’ or ‘let’. We use ‘const’ when we don’t want our application to change the value.

const price1 = 5;
const price2 = 6;
let total = price1 + price2;

Operators

Arithmetic

OperatorDescription
+Addition
Subtraction
*Multiplication
**Exponentiation
/Division
%Modulus (Division Remainder)
++Increment
Decrement

Assignment

OperatorExampleSame as
=x = yx = y
+=x += yx = x + y
-=x -= yx = x – y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y
<<=x <<= yx = x << y
>>=x >>= yx = x >> y
>>>=x >>>= yx = x >>> y
&=x &= yx = x & y
^=x ^= yx = x ^ y
|=x |= yx = x | y
**=x **= yx = x ** y

Comparison

OperatorDescription
==equal to
===equal value and equal type
!=not equal
!==not equal value or not equal type
>greater than
<less than
>=greater than or equal to
<=less than or equal to
?ternary operator

/

Logical

OperatorDescription
&&logical and
||logical or
!logical not

Type

OperatorDescription
typeofReturns the type of a variable
instanceofReturns true if an object is an instance of an object type

Bitwise

OperatorDescriptionExampleSame asResultDecimal
&AND5 & 10101 & 00010001 1
|OR5 | 10101 | 00010101 5
~NOT~ 5 ~01011010 10
^XOR5 ^ 10101 ^ 00010100 4
<<left shift5 << 10101 << 11010 10
>>right shift5 >> 10101 >> 10010  2
>>>unsigned right shift5 >>> 10101 >>> 10010  2

Control Statement

If.. else if .. else

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false

if

Sometimes, there is need when we have to just check the condition and run the statements when it is true and do nothing else, in that case we can use it easily without worrying about the false condition.

Syntax

if (condition) {
  //  statements here to run when the above condition is true
}

else

Syntax

if (condition) {
  //  statements here to run when the above condition is true
} else {
  //  statements here to run when the above condition is false
}

Also sometimes, there is need when we have to just check the condition and run the statements when it is true and do something for the false condition, in that case we can extend the case for the false condition as well.

else if

Syntax

if (condition) {
  //  statements here to run when the above condition is true
} else if (condition) {
  //  statements here to run when the above condition is true
} else {
  //  statements here to run if none of the condition fulfills
}

Also sometimes, there is need when we have to just check the condition and run the statements when it is true and check for more conditions and do something /nothing for the false condition, we can easily use this case. In short, when we have to deal with multiple conditions, we can use this structure.

switch case

Syntax

switch(expression) {
  case x:
    // code 
    break;
  case y:
    // code 
    break;
  default:
    // code 
}

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
     day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default:
    day = "Invalid day";
    break;
}

Common Blocks : We can group the cases to run certain statements. For example, in this case, if the day is 1,2,3,4,5 it displays Weekdays, if it is 0 or 6 then it assigns Weekends and by default it displays “I dont know what to write here”.

switch (new Date().getDay()) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    text = "It is a weekday";
    break;
  case 0:
  case 6:
    text = "It is Weekend";
    break;
  default:
    text = "I dont know what to write here";
    break;
}

Looping Statement

Lets consider an array as below so that we can see what looping does to them

array=[];
array.push("January");
array.push("February");
array.push("March");
array.push("April");
array.push("May");
array.push("June");
array.push("July");
array.push("August");
array.push("September");
array.push("October");
array.push("November");
array.push("December");

for

For ‘for‘ loop we have syntax as

for(<initial expression>; <condition>; <increment expression>){
  //statements here to run
}

Often there are times when we want to loop, but when we want the index and manipulate them through the collection or anything, we use ‘for‘ loop.

document.write("<h3>Using For Loop</h3>");
for (let index = 3; index < 10; index++) {
    document.write("<h5>"+array[index]+"</h5>");
    
}

Above is the program, where we want to loop from index 3 to index 10.

for in

Syntax

for(<initial expression>; <condition>; <increment expression>){
  //statements here to run
}
document.write("<h3>Using For in Loop</h3>");
for (var key in array) {
    document.write("<h5>"+array[key]+"</h5>");
}

Above is the program, where we want to loop every index in the array i.e. from 0 to 11 (in above case). Here in this case, in every loop it takes the index and we can manipulate it using array[key].

for of

Syntax

for(let <item> of <collection>){
  //statements here to run
}
document.write("<h3>Using For of Loop</h3>");
for (let key of array) {
    document.write("<h5>"+key+"</h5>");
}

Above is the program, where we want to loop every item, not index. Here in every loop the item is taken from the array and added to the variable key.

do while

The do/while loop is like a while loop, except that the loop expression is tested at the bottom of the loop rather than at the top. This means that the body of the loop is always executed at least once. The syntax is:

do 
{
   statement 
} while (expression); 

The do/while loop is less commonly used than its while cousin—in practice, it is somewhat uncommon to be certain that you want a loop to execute at least once. Here’s an example of a do/while loop:

function printArray(a) { 
   let len = a.length, i = 0; 
   if (len === 0) { 
      console.log("Empty Array");
   } else { 
      do 
      { 
         console.log(a[i]); 
      } while(++i < len); 
   } 
} 

There are a couple of syntactic differences between the do/while loop and the ordinary while loop. First, the do loop requires both the do keyword (to mark the beginning of the loop) and the while keyword (to mark the end and introduce the loop condition). Also, the do loop must always be terminated with a semicolon. The while loop doesn’t need a semicolon if the loop body is enclosed in curly braces.

while

Just as the if statement is JavaScript’s basic conditional, the while statement is JavaScript’s basic loop. It has the following syntax:

while (expression) 
{
   statement 
}

To execute a while statement, the interpreter first evaluates expression. If the value of the expression is falsy, then the interpreter skips over the statement that serves as the loop body and moves on to the next statement in the program. If, on the other hand, the expression is truthy, the interpreter executes the statement and repeats, jumping back to the top of the loop and evaluating expression again. Another way to say this is that the interpreter executes statement repeatedly while the expression is truthy. Note that you can create an infinite loop with the syntax while(true). Usually, you do not want JavaScript to perform exactly the same operation over and over again. In almost every loop, one or more variables change with each iteration of the loop. Since the variables change, the actions performed by executing statement may differ each time through the loop. Furthermore, if the changing variable or variables are involved in expression, the value of the expression may be different each time through the loop. This is important; otherwise, an expression that starts off truthy would never change, and the loop would never end! Here is an example of a while loop that prints the numbers from 0 to 9:

let count = 0; 
while(count < 10) 
{ 
    console.log(count); 
    count++; 
} 

As you can see, the variable count starts off at 0 and is incremented each time the body of the loop runs. Once the loop has executed 10 times, the expression becomes false. The while statement finishes, and the interpreter can move on to the next statement in the program. Many loops have a counter variable like count. The variable names i, j, and k are commonly used as loop counters, though you should use more descriptive names if it makes your code easier to understand.

Reference : JavaScript Operators (w3schools.com)

Was this article helpful to you? Yes No

How can we help?

Leave a Reply

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