0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript Basics: Variables, Data Types, and Operators

Posted at

Add a subheading.jpg

Introduction

JavaScript is a programming language used in various applications for developing applications. It was introduced by Brendan Eich in 1995. This programming language is commonly used in building web applications as it makes the web applications more dynamic and scalable, which makes the user experience feel better and gives a quick response to every request made by the user.
Furthermore, the JavaScript programming, just like other programming languages, has its own variables, data types, and operators. This article will give you a description of these topics with working examples.

Variables in JavaScript

In JavaScript, variables are containers used to store data. There are keywords that are used for declaring a variable in JavaScript. Given below is the description of keywords that are used to declare a variable in JavaScript.
1.Var
The keyword var is used to declare a global-scope variable. It means variables that are declared using the var keyword are accessible throughout the function where they have been declared or throughout the class; if they are declared outside the function.

The values assigned using the var keyword can be re-declared, meaning the content can be modified or reassigned multiple times even after the declaration of the values. In JavaScript, variables declared using the var keyword can store any type of data, like numeric data, string data, boolean data, complex data, and other data as well.

Example

// JavaScript program to demonstrate the usage of the 'var' keyword

var value1 = 15;                         // Integer value
var value2 = "Welcome to Tpoint Tech";  // String value
var myFloat = -15.78;                   // Floating-point value

console.log(value1);    // Output: 15
console.log(value2);    // Output: Welcome to Tpoint Tech
console.log(myFloat);   // Output: -15.78

Output

15
Welcome to Tpoint Tech
-15.78

2.Let
The keyword let in JavaScript is used to store values similar to the var keyword. The difference between the var and let keywords in the JavaScript programming language is that the variables declared using the var keyword can be assigned globally, whereas in the let keyword are limited to the block only where they have been declared.

Data declared using the let keyword is not globally assigned, but it can store any kind of data similar to the var keyword, and modification is also allowed in the let keyword. It means the data assigned using the let keyword is mutable (that can be changed).

Example

// JavaScript program to demonstrate the working of let keyword
let a = 15;  // integer type
console.log(a);

Output

15

3.Const

The keyword const is used to store the values that are constant and cannot be modified or reassigned, unlike the var and let keywords used in JavaScript. The data store using the const keyword is immutable (cannot be changed). The scope or reach of a const variable is limited to the block of code where the variable has been declared, similar to the let keyword.

Example

// JavaScript program to demonstrate the working of const keyword
const value = 67; // constant integer value
const word = "This word can not be change"; // constant word
const value2 = 67.879; // constant decimal value

console.log("Integer value:", value);
console.log("String value", word);
console.log("Decimal Value:", value2);

Output

Integer value: 67
String value This word can not be change
Decimal Value: 67.879

Data Types in JavaScript

Data type in JavaScript represents the type of operation that is stored in a variable. It also tells the kind of operation that can be performed on data stored in a particular variable. For case, if the data type is of string, we can perform string concatenation, string comparison, case conversion, etc., but we cannot perform mathematical operations like addition or subtraction.

These operations can be performed on a numeric data type. Data types are divided into two categories, which are Primitive Data types and Non-Primitive Data types. Given below is the description of the data type in JavaScript.

1.Primitive Data Types

In JavaScript, primitive data types are the most basic kinds of data that are immutable (cannot be changed) and stored by value. Following are the different values comes under the primitive data types.

Numeric: The data is numeric and it includes both integer, decimal, and float values. (example: 10, 15.265. -15.26). The different mathematical operations, like addition, subtraction, division, and multiplication, can be performed on the numeric data type.

String: This data type contains the sequence of characters enclosed within single or double quotes. Operations which can be performed on string data include string concatenation, case conversion, comparison of two or more strings, etc.(example: “Welcome to Tpoint Tech Tutorial”).

Boolean: The Boolean data type is used to perform logical operations in a programming language. It always returns a value, either true or false, depending on the result.

Null: This data type always returns a null value representing the absence of any object.

Example

// JavaScript program to demonstrate the working of Primitive data type
let a = 10; // integer data type
let b = "Welcome to Tpoint Tech"; // string data type
let isValid = true; // boolean data type
console.log("Integer data type is: ", a);
console.log("String data type is", b);
console.log("Boolean data type is:", isValid);

Output

Integer data type is:  10
String data type is Welcome to Tpoint Tech
Boolean data type is: true

2.Non-Primitive Data Type
Non-primitive data types store references to the memory location instead of storing the actual value. Non-Primitive data types include Array, Functions, Maps, Plain Objects(key-value pairs), etc. Given below is the description of non-primitive data types.

Array: An Array is an object used to store an ordered collection of values. In an Array, the elements are stored in a sequence and accessed by the index of an element ,which starts from 0. The index does not represent the exact memory location of an element in an array. In JavaScript, multiple different data can be stored in a single array.(Example: let arr = [12, “Tpoint Tech”, true, {website: Tpoint Tech}]; )

Example

// JavaScript program to demonstrate the working of non-primitive data type array
// Operation on Array
let trees = ["Palm", "Walnut", "Deciduous", "Cedar"];

console.log("Variety of trees:");
console.log(trees);

// accessing the first index of array trees
console.log("First tree:", trees[0]);

// updating one element of an array tree
trees[1] = "Willow";
console.log("Updated array:", trees);

// adding a new element
trees.push("Beech");
console.log("Array after adding element:", trees);

Output

Variety of trees:
[ 'Palm', 'Walnut', 'Deciduous', 'Cedar' ]
First tree: Palm
Updated array: [ 'Palm', 'Willow', 'Deciduous', 'Cedar' ]
Array after adding element: [ 'Palm', 'Willow', 'Deciduous', 'Cedar', 'Beech' ]

Object: An Object as a non-primitive data type in JavaScript is defined as a collection of objects stored in the form of a key-value pair, where keys are unique and values can be of any data type assigned to the key. The key-value pair in JavaScript together defines a property of an object.

Example

/ JavaScript program to demonstrate the working of non-primittive data type( Object)
// Operation on object
let website = {
    name: "Tpoint Tech",
    subjects: ["Programming", "Database", "Maths"],
    purpose: "Education",
    founded : 2011,
    isAvailable: true
};

console.log("Website Object:");
console.log(website);

// Accessing values of an object
console.log("Name:", website.name);
console.log("Is available on internet:", website["isAvailable"]);

// Updating a value on object
website.purpose= "To provide education";
console.log("Updated Value: ", website.purpose);

// Adding a new key-value pair
website.course = "Data Science";
console.log("After adding course:", website);

Output

Website Object:
{
  name: 'Tpoint Tech',
  subjects: [ 'Programming', 'Database', 'Maths' ],
  purpose: 'Education',
  founded: 2011,
  isAvailable: true
}
Name: Tpoint Tech
Is available on internet: true
Updated Value:  To provide education
After adding course: {
  name: 'Tpoint Tech',
  subjects: [ 'Programming', 'Database', 'Maths' ],
  purpose: 'To provide education',
  founded: 2011,
  isAvailable: true,
  course: 'Data Science'
}

Operators in JavaScript

Operators in JavaScript are special symbols used to perform operations on values stored in a variable. Given below are the different types of operators in JavaScript, along with examples

1.Arithmetic Operators
These operators are used to perform arithmetic operations in JavaScript. The Following are the different arithmetic operators in JavaScript.

  • : This is an addition operator used to perform addition operations. Example: 2 + 3 = 5.
  • : This is a minus operator used to perform the subtraction operation in JavaScript. Example: 2 - 3 = 1.
    : This is a multiplication operator used to perform the multiplication operation. Example: 23 = 6.
    /: This is a division operation used to perform the division operation. Example: 10/2 = 5
    %: This is the modulus operator used to return the remainder value. Example: 7%3 = 1
    : This is a exponential operator used to return the value after mutiplying the base value to it’s power. Example: 23 == 8
    ++: This is an increment operator. It increases the value by 1.
    --: This is a decrement operator. It decreases the value by 1

Example

// JavaScript program to demonstrate the working of Arithmetic operators
let a = 10;
let b = 5;
console.log("Addition result of a + b is = ", a + b);
console.log("Subtraction result a - b is = ", a-b);
console.log("Multiplication result of a*b is= ",a*b);
console.log("Division result of a/b is =", a/b);
console.log("Modulus result of a%b is =" , a%b);
console.log("Exponential result of a**b is = ",a**b);
console.log("Increment result of ++a is  =", ++a);
console.log("Decrement result of --b is = ", --b);

Output

Addition result of a + b is =  15
Subtraction result a - b is =  5
Multiplication result of a*b is=  50
Division result of a/b is = 2
Modulus result of a%b is = 0
Exponential result of a**b is =  100000
Increment result of ++a is = 11
Decrement result of --b is  = 4

2.Comparison Operators

The operators are used to compare two or more values and give the result in true or false, depending on the output of an operation performed by comparison operators. The Following are the different comparison operators used in JavaScript.

== : This operator compares the values; if they are similar , it returns true, otherwise it returns false.
===: This operator strictly compares the value; if they are congruent ,meaning exactly the same ,then it returns true, otherwise it returns false. It also compares the case of a string during comparison.
!=: This operator stands for not equal to. It returns true if the values are not equal; otherwise, it returns false.
!==: This operator stands for strict not equal. It returns true if the values are not strictly equal, while comparison also compares the cases of string ; otherwise, it returns false.

: This operator returns true if the left side value is greater than the right side, otherwise returns false.
<: This operator returns true if the left side value is smaller than the right side, otherwise returns false.
= : This operator stands for greater than or equal to. It returns true if the left side value is greater than or equal to the right side ; otherwise returns false.
<=: This operator stands for less than or equal to. It returns true if the left side value is less than or equal to the right side; otherwise returns false.

Example

// JavaScript program to demonstrate the working of comparison operator
let a = 10;
let b = 20;
let c = "10";

console.log("Result of a == c is : ", a == c);
console.log("Result of a === c is : ", a === c);
console.log("Result of a != b is : ", a != b);
console.log("Result of b > a :" , b > a);
console.log("Result of b < a :" , b < a);
console.log("Result of a !== c: ", a !== c);
console.log("Result of a >= 10: ", a >= 10);
console.log("Result of a <= 5:", a <= 5);

Output

Result of a == c is :  true
Result of a === c is :  false
Result of a != b is :  true
Result of b > a : true
Result of b < a : false
Result of a !== c:  true
Result of a >= 10:  true
Result of a <= 5: false;

3.Assignment Operators
These operators are used to assign values to a variable. The following is the description of the different assignment operators used in JavaScript.

=: This operator is used to store the right-hand side value to the left side operator. (Example: a = 10)
+=: This operator performs the addition operation and then stores the resultant value in the left variable. (Example: x += 3). It means x = x + 3
-=: This operator performs the subtraction operation and then stores the resultant value to the left side variable. (Example: x -= 3). It means x = x – 3
*=: This operator perform the mutiplication operation and store the result to the left side variable. (Example: x *= 3). It means x = x * 2
/=: This operator performs the division operation and stores the result in the left side variable. (Example: x /= 3). It means x = x /3.
%: This operator performs the modulus operation and stores the result in the left side variable. (Example: x%=3). It means x = x % 3

Example

/ JavaScript program to demonstrate the working of assignment operator
let x = 3;
let y = 7;

console.log("Result of x += 3 is: " , x+=3);
console.log("Result of y -= 3 is: " , y-=3);
console.log("Result of x *= 3 is: ", x*=3 );
console.log("Result of x /= 6 is: ", x/=6);
console.log("Result of y%3 is: ", y%3);

Output

Result of x += 3 is:  6
Result of y -= 3 is:  4
Result of x *= 3 is:  18
Result of x /= 6 is:  3
Result of y%3 is:  1

4.Logical Operators
These operators are used to perform logical operations, and they always return a boolean value. The value returned by logical operators will be either true or false. Given below is the description of different logical operators used in JavaScript.

Logical AND(&&): This operator returns true if both operands are true. If any one of the operands is false, then it will return false. (Example age > 18 and hasLicense = true). If both of the conditions are true, then the output of and operator will be true.

Logical OR(||): This operator returns true if any one of the operands is true. If both the operands are false, then it will return false (Example age > 18 and hasLicense = false). It will return true if any one of the operands is true, otherwise false.

Logical NOT(!): This operator performs the negation operation on its operand. It reverses the boolean value of an expression. If the expression evaluates to true, then this operator turns that result into false.

Example

/ JavaScript program to demonstrate the working of logical operators
 let age = 20;
let hasLicense = true;

if(age > 18 && hasLicense == true) {
    console.log("candidate can drive");
} else {
    console.log("condidate is not allowed to drive");
}

// execution of logical or operator
let groundIsWet = true;
let isRainingOutside = true;

if(groundIsWet == true || isRainingOutside == true) {
    console.log("Person could not play outside");
} else {
    console.log("Person can play outside");
}

// execution of logical not operator
let password = false;
if(!password) {
    console.log("Your Password is correct");
} else {
    console.log("Your Password is wrong");
}

Output

candidate can drive
Person could not play outside
Your Password is correct

5.Ternary/Conditional Operators
These operators take three operands, in which one is a conditional statement and the other two are the expressions to be executed. This operator is followed by a ? symbol. It returns the value of the expression that meets the condition. Given below is the syntax and example of ternary operators in JavaScript

Syntax

condition ? expression1 : expression2 ;

Example

// JavaScript program to demonstrate the working of ternary operator
let signal = "green";
let traffic = (signal == "green") ? "Go" : "Stop";
console.log(traffic);

Output

Go

Conclusion

This article gives a basic description of the variables, data types, and operators used in the JavaScript programming language, along with working examples. I hope this article has provided you a valuable information about the basic and important concepts used in JavaScript programming.

If you are looking for more such kind of information, then I suggest you visit the Tpoint Tech Website , where you can get various articles about programming languages and other technology, along with interview questions, working examples , and an online compiler for almost all programming languages, where you can run and test your code.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?