Basics of JavaScript (variable, datatype, function, array, loop and more)

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

In this article, we have explained the Basics of JavaScript (variable, datatype, function, array, loop and more).

Table of Contents


1. Introduction

2. Working with JavaScript in the HTML file

3. Type of Variables

3.1. Var

3.2. Let

3.3. Const

4. Data Types

4.1. String

4.2. Number

4.3. Boolean

4.4. Null

4.5. Undefined

4.6. Symbol

4.7. Object

5. Functions

6. Array and Methods

7. Loop

7.1. For

7.2. For...in

7.3. While

8. Math Methods

9. Class

10. Conditional Structures

10.1. If...else

10.2. Switch

11. Final Considerations

Reference


1. Introduction


The JavaScript language was created in the 90s by Brendan Eich in the service of Netscape.
This language was initially known as Mocha, then LiveScript, and nowadays as JavaScript.
JavaScipt is a language that allows the creation of dynamic content, manipulating, for example, multimedia and images.
The company Netscape submitted JavaScript to ECMA International to create a standard specification, which led to the official release of the ECMAScript language specification. This specification has several versions, the most current being ECMA-262 published in 2021.
This article aims to provide a basic overview of the JavaScript language.

2. Working with JavaScript in the HTML file


The JavaScript file can be inserted into an HTML document between the tags <script>...</script> inside the <head>.
In Figure 1, the code returns the message Hello World. Note that the JavaScript file type was specified with type="text/javascript".

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript</title>
    
    <script type="text/javascript">
        alert('Hello World!');
    </script>
   
</head>
<body>
</body>
</html>

Figure 1. JavaScript inserted inside the <head> tag.

Another way to embed JavaScript is inside the <body> tag. In Figure 2, the code generates the message Mocha, LiveScript, JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript</title>
</head>
<body>
    <script type="text/javascript">
        alert('Mocha, LiveScript, JavaScript')
 
    </script>
</body>
</html>

Figure 2. JavaScript inserted inside the <body> tag.

The difference in where to insert the JavaScript file is related to the processing time of the code. When you insert JavaScript code inside the <body>, the processing tends to be faster because all HTML and/or CSS content has loaded before implementing the JavaScript code.

Finally, you can create a file separate from the JavaScript code. For this, it is necessary to specify the path of the JavaScript file in the HTML file.
In Figure 3, we specified the path of the Javascript file (index.js) inside the tag <body>. The index.js file is in the js folder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>javascript</title>
</head>
<body>
   <script type="text/javascript" src="js/index.js"></script>
</body>
</html>

Figure 3. JavaScript file path specified in the HTML file.

3. Type of Variables


The JavaScript language allows you to use a variable before its declaration in the code.
The process occurs due to Hoisting mechanism. In which the variable is transported to the top of its execution context.
In Figure 4, the OpenGenus message was carried to the top of the code, returning no error in the code.

function testHoisting(){
 
    return t;
   
      function t(){
   
        return ("OpenGenus");
      }
    }
  var m = testHoisting();
   
  console.log(m());

Figure 4. Hoisting example inside JavaScript code.

Within JavaScript, there are three types of variables.

3.1. Var


The code of a variable declared with var is its current running context, which is the function it belongs to.
In contrast, for variables declared outside of any function, the scope is global.
Figure 5, initially the variable a has the value of "Python". After this value was redefined as Kotlin.

var  a = ("Python");
{  
var a = ("Kotlin");
}
console.log (a);

Figure 5. Example with keyword var.

3.2. Let


The variable let allows the declaration of variables limiting their scope in the block.
In Figure 6, the code returns the value Python. Unlike Figure 5, resetting the variable to "Kotlin" had no effect because it did not occur within the block with the value "Python".

let  a = ("Python");
{  
let a = ("Kotlin");
}
console.log (a);

Figure 6. Example with the let keyword.

3.3. Const


Constants are also block-scoped, similar to let.
The constant value cannot be changed by an assignment and re-declared.
In Figure 7, the code inserted the value "JavaScript at position 2 and added the value "React" to the end of the array. The result was ['Java', 'C++', 'JavaScript', 'React'].

const code = ["Java", "C++", "C#"];

code[2] = "JavaScript";

code.push("React");

console.log(code);

Figure 7. Example with const keyword.

4. Data Types


In Javascript, variables are a way to save and manipulate data.
There are seven types of data:

4.1. String


The string is useful for storing data represented in the form of characters. Remembering that JavaScript is a case-sensitive code, that is, the upper and lower case letters are taken into account.
In Figure 8, the code generates the Codification result.

let str = "Codification"
console.log(str);

Figure 8. An example involving string.

4.2. Number


The number allows storing and manipulating numeric data.
In Figure 9, the code returns a float number 1.1 and an integer number 3.

let num = 1 + 0.1;
let num1 = 2 + 1;
console.log (num +" and "+ num1);

Figure 9. An example involving number.

4.3. Boolean


Codes that use boolean only return two types of result true and false.
In Figure 10, it verifies if the number 5 is greater than 9. The result returns as false.

console.log(Boolean(5 > 9));

Figure 10. An example involving boolean.

4.4. Null


Null can be assigned to a variable as a valueless representation.
In Figure 11, the test variable receives the value "null".
The result generated by the code was null.

var test = null;
console.log (test);

Figure 11. An example involving null.

4.5. Undefined


Undefined is when a variable has been declared but has not yet been assigned a value.
Undefined and null are two distinct types. Undefined is itself undefined while null is an object.
In the example in Figure 12, the variable test is declared but without its value. The value returns as undefined.

var test;
console.log(test);

Figure 12. An example involving undefined.

4.6. Symbol


The symbol is a unique, immutable primitive value. Used as a key of an Object property.
The symbol function creates a unique value every time it is invoked.
In Figure 13, we created a string constant that will not collide with any other value.
The string press can be used for different purposes as it is not unique. However, the string press is unique to the data that contains it.
In the example (Figure 13), we compared two press strings created with the symbol. The value returns false because they are different strings.

console.log(Boolean(Symbol('press') === Symbol('press')));

Figure 13. An example involving symbol.

4.7. Object


The object is a collection of properties. Which each property is defined by a key and value.
In Figure 14, the student data were specified, and later the student's name was requested in the code, returning the value Maria.

var student = {
    name: "Maria",
    subject:"Math"
};

console.log(student.name)

Figure 14. An example involving object.

5. Functions


The role is created so the code can perform some action. Its structure is composed of:[5]

  • function name;
  • list of arguments for the function, enclosed in parentheses and separated by a comma;
  • Javascript statements defining the function, enclosed in braces.
    For the result to be printed, the console.log command was used.
    In Figure 15, the 4x4 multiplication is performed and returns the value of 16.
function square (n) {
    return n*n;
}
console.log(square(4))

Figure 15.Multiplication function.

6. Array and Methods


The array is a structure that can store variables and functions.
We can have an array with string, number, and object.
In Figure 16, we have a string array, which with the sort() method, the list is sorted alphabetically. The result returns ['C', 'Java', 'JavaScript', 'Kotlin', 'Python'].

var code = ["JavaScript", "Kotlin", "Python", "C", "Java"];
console.log(code.sort());

Figure 16. Sample string array with sort() sort method.

In Figure 17, there is an example of an array of numbers that is sorted ascending with the sort() method and then reverses the order with inverse().
The result it returns is * [90, 78, 5, 40, 2, 1] *.

var num = [78, 90, 2, 5, 1, 40]
num.sort();
console.log(num.reverse());

Figure 17. Example of number array with the reverse() method.

In Figure 18 exemplifies an array with an object. In this case, it is the data of a type of mineral. The code asked for the name of the mineral, returning Quartz.

var rock = {
    name: "Quartz",
    color:"Pink",
    status: "weathered",
};

console.log(rock.name);

Figure 18. Object array example.

The other forms to manipulate the data inside the arrays can be consulted on the w3school website.

7. Loop


The loop is used to execute a code block countless times until it reaches the pre-established requirements limits.

7.1. For


Figure 19 shows a code with the for command returning all existing items within this list, which are checked with the "length" command.
The output generated is JavaScript Java C C++ Kotlin.

const code = ["JavaScript", "Java", "C", "C++", "Kotlin"];

let text = "";
for (let c = 0; c < code.length; c++) {
  text += code[c] + "   ";
}

console.log(text);

Figure 19. Example of the loop with for command.

7.2. For...in


The for...in command iterates through the properties of an object.
In Figure 20, the for...in command cycles through all the mineral data and returns the values contained in its variables.
The result is Sodalite blue dodecahedral.

const mineral = {name:"Sodalite", color:"blue", cleavage:"dodecahedral"}; 

let str = "";
for (let x in mineral) {
  str += mineral[x] + " ";
}

console.log(str);

Figure 20. Example of the loop with for...in command.

7.3. While


The while loop iterates through a block of code as long as the condition meets the specification.

let str = "";
let i = 0;
while (i < 3) {
  str += "<br>The number is " + i;
  i++;
}
console.log(str);

Figure 21. Loop example with while command.

In Figure 21, the code returns as a result:

The number is 0
The number is 1
The number is 2

Figure 22. The result was generated by the code in Figure 21.

There are other commands involving loop that can be consulted on the w3school website.

8. Math Methods


For the manipulation of mathematical data, it is necessary to know about the mathematical operators (Table 1).

Table 1 - Main mathematical operators used in the JavaScript language

Operator Mean
+ sum
- subtraction
* multiplication
/ division
% rest of division

Figure 23 exemplifies the mathematical operations with all the operators mentioned in Table 1.

var x = 10;
var y = 5;

var a = (x + 10) * (x / 2) + 100;
var b = (x - y);
var c = (x % y);

console.log(a);
console.log(b);
console.log(c);

Figure 23. Code containing the major mathematical operators.

The result generated in variable a was 200. This operation involved addition, multiplication, and division.
For variable b with subtraction operation, the value was 5.
And for the variable c, the result was *zero. The x is divisible by y.

9. Class


JavaScript classes make it possible to develop objects more simply and clearly and deal with inheritance.
To build this type of code is necessary:

  • the word class with its name;
  • the constructor method providing the requirements (parameters);
  • this keyword internally associates the value of the parameter contained in the constructor.
    In the class syntax, there is the get & set tool to define the functions. The get method executes and set assigns.
    Figure 24 exemplifies the method using class in which the string Anna is returned.
class Student {
    constructor(name){
        this._name = name
    }
    set name (str) {
        this.name = str
    }
    get name () {
        return this._name
    }
}
var user = new Student ('Anna')

console.log(user.name)

Figure 24. Code developed with class.

10. Conditional Structures


Conditional structures execute a snippet or block of code only if a given condition is true.

10.1. If...else


The if executes a specific piece of code only if the condition matches with what was requested. Figure 25, if the price is less than or equal to 10 returns the value *Coupon accepted!* otherwise the message *Coupon denied!*. For the example (Figure 25), it returned the message *Coupon denied*.
var price = 11;
if ( price <= 10 ) {
    console.log("Coupon accepted!");
} else {
    console.log ("Coupon denied!")
}

Figure 25. Code developed with Class.

10.2. Switch


With the switch, it is possible to create scripts capable of executing different blocks of codes according to the conditions.

auth = true;

switch (auth) {
    case true:
        console.log("You are logged in!");
        break;
    case false:
        console.log("You are not logged in!");
        break;
}

Figure 26. Code developed with the switch() conditional.

11. Final Considerations


JavaScript is an important language, for example, in web page development.
It allows the development of interactive codes.
However, it is necessary to use best practices to create clean codes with higher processing speed.

In this article at OpenGenus, some concepts in the JavaScript language were discussed, but for more details read the w3school website.